Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
03d8570
feat(hosted-git): land the hosted-git seam without the Durable Object…
raphaeltm Nov 17, 2026
caef0e1
fix(hosted-git): address L16 review findings
raphaeltm Nov 17, 2026
9406993
task: archive L16 hosted-git seam task
raphaeltm Nov 17, 2026
4b9a6dd
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 17, 2026
9a40c5c
fix: retain hosted repository cleanup when Artifacts is disabled
raphaeltm Nov 17, 2026
cfe0f36
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 17, 2026
9abd1be
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 17, 2026
7495af6
test(api): allow shared CI budget for speech import graph
raphaeltm Nov 17, 2026
fcdd51c
fix(vm-agent): honor callback username for standalone clones
raphaeltm Nov 18, 2026
4bd1f57
test(vm-agent): simplify standalone callback regression
raphaeltm Nov 18, 2026
70931e9
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
1fe679c
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
da9f91b
fix(vm-agent): normalize hosted git HTTPS ports
raphaeltm Nov 18, 2026
7a6048b
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
bcc3735
fix(vm-agent): preserve hosted git credentials across port forms
raphaeltm Nov 18, 2026
12e7109
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
2de1924
fix(vm-agent): require HTTPS for hosted git credentials
raphaeltm Nov 18, 2026
5ced633
test(vm-agent): group hosted credential expectations
raphaeltm Nov 18, 2026
bda3332
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
c7a06b2
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ import type { TaskRunnerContext, TaskRunnerState } from './types';

type TaskRunnerProjectRepo = {
repoProvider: string | null;
repository: string;
};

async function loadTaskRunnerProjectRepo(
state: TaskRunnerState,
rc: TaskRunnerContext
): Promise<TaskRunnerProjectRepo | null> {
return rc.env.DATABASE.prepare(`SELECT repo_provider AS repoProvider FROM projects WHERE id = ?`)
return rc.env.DATABASE.prepare(
`SELECT repo_provider AS repoProvider, repository FROM projects WHERE id = ?`
)
.bind(state.projectId)
.first<TaskRunnerProjectRepo>();
}
Expand All @@ -38,6 +41,7 @@ async function createWorkspaceOnVmAgent(
const gitSource = await resolveWorkspaceGitSource(drizzle(rc.env.DATABASE, { schema }), {
id: state.projectId,
repoProvider: projectRepo?.repoProvider ?? 'github',
repository: projectRepo?.repository ?? state.config.repository,
});
const checkoutBranch = state.config.outputBranch || state.config.branch;
const baseBranch =
Expand Down
6 changes: 2 additions & 4 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import { aiProxyAnthropicRoutes } from './routes/ai-proxy-anthropic';
import { aiProxyPassthroughRoutes } from './routes/ai-proxy-passthrough';
import { analyticsIngestRoutes } from './routes/analytics-ingest';
import { apiTokenRoutes } from './routes/api-tokens';
import { artifactsConfigRoutes } from './routes/artifacts-config';
import { authRoutes } from './routes/auth';
import { bootstrapRoutes } from './routes/bootstrap';
import { cachedCommandRoutes } from './routes/cached-commands';
Expand Down Expand Up @@ -272,10 +273,7 @@ app.get('/health', (c) => {
});

// Public config — exposes feature flags the UI needs before auth
app.get('/api/config/artifacts-enabled', (c) => {
applyCacheHeaders(c, 'public-config');
return c.json({ enabled: c.env.ARTIFACTS_ENABLED === 'true' && !!c.env.ARTIFACTS });
});
app.route('/api/config', artifactsConfigRoutes);

app.route('/api/config', platformCapabilitiesRoutes);

Expand Down
13 changes: 13 additions & 0 deletions apps/api/src/repo-hosting-ports/artifacts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports';

import type { Env } from '../env';
import { resolveArtifactsBackend } from '../services/hosted-git/backend';

/**
* Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam:
* the Cloudflare Artifacts binding, or the backend a self-host build registered. The package hands
* over its narrow env; the full worker env is what reached it.
*/
export const artifactsPort: ArtifactsBackendPort = {
resolve: (env) => resolveArtifactsBackend(env as Env),
};
7 changes: 6 additions & 1 deletion apps/api/src/repo-hosting-wiring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
*/
import { configureRepoHostingPorts } from '@simple-agent-manager/repo-hosting/ports';

import { artifactsPort } from './repo-hosting-ports/artifacts';
import { authPort } from './repo-hosting-ports/auth';
import { platformConfigPort } from './repo-hosting-ports/platform-config';

configureRepoHostingPorts({ platformConfig: platformConfigPort, auth: authPort });
configureRepoHostingPorts({
platformConfig: platformConfigPort,
auth: authPort,
artifacts: artifactsPort,
});
17 changes: 17 additions & 0 deletions apps/api/src/routes/artifacts-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Hono } from 'hono';

import type { Env } from '../env';
import { applyCacheHeaders } from '../lib/cache-headers';
import { isArtifactsAvailable } from '../services/hosted-git/backend';

/**
* Public config: whether this install can create SAM-native (Artifacts) repositories. True only
* when ARTIFACTS_ENABLED is set and a backend exists (the Cloudflare binding, or the backend a
* self-host build registered), so the UI never offers a provider that would fail on use.
*/
export const artifactsConfigRoutes = new Hono<{ Bindings: Env }>();

artifactsConfigRoutes.get('/artifacts-enabled', (c) => {
applyCacheHeaders(c, 'public-config');
return c.json({ enabled: isArtifactsAvailable(c.env) });
});
7 changes: 5 additions & 2 deletions apps/api/src/routes/projects/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
deleteProjectLibraryObjects,
getProjectDeleteCleanupBatchSize,
} from '../../services/file-library';
import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend';
import { getRuntimeLimits } from '../../services/limits';
import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history';
import { registerProjectCreateRoute } from './project-create';
Expand All @@ -42,13 +43,15 @@ async function cleanupArtifactsRepoOnProjectDelete(
action: 'orphaned_artifacts_repo_on_delete',
};

if (!env.ARTIFACTS || typeof env.ARTIFACTS.delete !== 'function') {
// Disabling Artifacts stops serving, but must not prevent cleanup of existing repositories.
const artifacts = resolveArtifactsBackendForCleanup(env);
if (!artifacts || typeof artifacts.delete !== 'function') {
log.warn('project_delete.artifacts_delete_unavailable', orphanDetails);
return;
}

try {
const deleted = await env.ARTIFACTS.delete(project.artifactsRepoId);
const deleted = await artifacts.delete(project.artifactsRepoId);
if (!deleted) {
log.warn('project_delete.artifacts_delete_returned_false', orphanDetails);
}
Expand Down
8 changes: 5 additions & 3 deletions apps/api/src/routes/projects/project-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
requireGitLabUserAccessToken,
verifyGitLabProjectAccess,
} from '../../services/gitlab';
import { resolveArtifactsBackend } from '../../services/hosted-git/backend';
import { getRuntimeLimits } from '../../services/limits';
import {
assertRepositoryAccess,
Expand Down Expand Up @@ -83,7 +84,8 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
if (!artifactsEnabled) {
throw errors.badRequest('Artifacts repo provider is not enabled');
}
if (!c.env.ARTIFACTS) {
const artifacts = resolveArtifactsBackend(c.env);
if (!artifacts) {
throw errors.internal('Artifacts binding is not configured');
}

Expand Down Expand Up @@ -119,7 +121,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
// Must be sanitized: Artifacts rejects uppercase/spaces (the ULID projectId
// is uppercase and normalizedName preserves spaces).
const repoName = toArtifactsRepoName(normalizedName, projectId);
const created = await c.env.ARTIFACTS.create(repoName, {
const created = await artifacts.create(repoName, {
description: description || undefined,
setDefaultBranch: defaultBranch,
});
Expand Down Expand Up @@ -148,7 +150,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>):
// Best-effort cleanup: the repo exists but has no usable content, and no
// project row will reference it. Delete it so it does not leak quota.
try {
await c.env.ARTIFACTS.delete(created.name);
await artifacts.delete(created.name);
} catch (cleanupError) {
log.error('project_create.artifacts_seed_cleanup_failed', {
projectId,
Expand Down
11 changes: 9 additions & 2 deletions apps/api/src/routes/workspaces/runtime-git-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
requireGitLabUserAccessTokenResultForOwner,
verifyGitLabProjectAccess,
} from '../../services/gitlab';
import { resolveArtifactsBackend } from '../../services/hosted-git/backend';
import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source';
import { assertRepositoryAccess } from '../projects/_helpers';
import {
assertWorkspaceAcceptsCallback,
Expand Down Expand Up @@ -221,7 +223,8 @@ runtimeRoutes.post('/:id/git-token', async (c) => {
if (c.env.ARTIFACTS_ENABLED !== 'true') {
throw errors.forbidden('Artifacts provider is not enabled');
}
if (!c.env.ARTIFACTS || !artifactsRepoId) {
const artifacts = resolveArtifactsBackend(c.env);
if (!artifacts || !artifactsRepoId) {
throw errors.internal('Artifacts binding or repo ID missing');
}

Expand All @@ -232,7 +235,7 @@ runtimeRoutes.post('/:id/git-token', async (c) => {
const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600;
// Use requested scope or default to 'write' (agents need push access)
const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const);
const repo = await c.env.ARTIFACTS.get(artifactsRepoId);
const repo = await artifacts.get(artifactsRepoId);
await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token');
const tokenResult = await repo.createToken(requestedScope, ttl);

Expand Down Expand Up @@ -269,6 +272,10 @@ runtimeRoutes.post('/:id/git-token', async (c) => {
token: tokenSecret,
expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at,
cloneUrl,
// The VM agent's credential helper answers with username "x" only for Cloudflare Artifacts
// hosts it knows by name. For a bound self-hosted host, name it here so a refresh presents
// the same username the clone used. Cloudflare responses are unchanged.
...(boundArtifactsRepositoryHost(cloneUrl) ? { username: 'x' } : {}),
Comment thread
simple-agent-manager[bot] marked this conversation as resolved.
Resolved
});
}

Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/routes/workspaces/workspace-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,11 @@ export function registerWorkspaceCreateRoute(crudRoutes: Hono<{ Bindings: Env }>
resolvedReservation,
createdAt: now,
},
linkedProject: { id: linkedProject.id, repoProvider: linkedProject.repoProvider },
linkedProject: {
id: linkedProject.id,
repoProvider: linkedProject.repoProvider,
repository: linkedProject.repository,
},
taskId: chatTaskId,
chatSessionId,
mustProvisionNode,
Expand Down
48 changes: 48 additions & 0 deletions apps/api/src/services/hosted-git/backend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* The SAM-native repository backend: one answer to "which `Env.ARTIFACTS` does this install use?".
*
* - `ARTIFACTS_ENABLED !== 'true'`: none.
* - A Cloudflare Artifacts binding is present: that binding. This is every Cloudflare deployment.
* - Otherwise, the fallback backend the self-host build registered, if any. The Cloudflare build
* registers none, so on Cloudflare the result is exactly the binding or null.
*
* The self-host build (`apps/api/src/selfhost/`, never imported by `src/index.ts`) registers SAM's own
* git server here. This module holds only the selection, so the Cloudflare bundle carries no
* hosted-git implementation.
*
* Every caller that needs the backend goes through `resolveArtifactsBackend`, so the capability
* flag, project creation, browsing and git tokens cannot disagree. Deletion uses the same
* selection without the enable flag, so disabling the feature cannot orphan existing repositories.
*/
import type { Env } from '../../env';

export type ArtifactsBackend = NonNullable<Env['ARTIFACTS']>;

/** Builds the fallback backend for an install with no Artifacts binding, or returns null. */
export type ArtifactsBackendFallback = (env: Env) => ArtifactsBackend | null;

let fallback: ArtifactsBackendFallback | null = null;

/**
* Installs the backend used when Artifacts is enabled but no Cloudflare binding exists. Called once
* at module load by the self-host build. Passing null removes it (tests).
*/
export function registerArtifactsBackendFallback(factory: ArtifactsBackendFallback | null): void {
fallback = factory;
}

/** The backend this install uses for SAM-native repositories, or null when it has none. */
export function resolveArtifactsBackend(env: Env): ArtifactsBackend | null {
if (env.ARTIFACTS_ENABLED !== 'true') return null;
return resolveArtifactsBackendForCleanup(env);
}

/** Existing repositories still need cleanup after the feature is disabled. Never use for serving. */
export function resolveArtifactsBackendForCleanup(env: Env): ArtifactsBackend | null {
return env.ARTIFACTS ?? fallback?.(env) ?? null;
}

/** Whether this install can create and serve SAM-native (Artifacts) repositories. */
export function isArtifactsAvailable(env: Env): boolean {
return resolveArtifactsBackend(env) !== null;
}
1 change: 1 addition & 0 deletions apps/api/src/services/instant-restore-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export async function loadInstantRestoreWorkspace(
const source = await resolveWorkspaceGitSource(db, {
id: input.projectId,
repoProvider: row.repoProvider,
repository: row.repository,
});
return {
workspaceId: input.workspaceId,
Expand Down
53 changes: 52 additions & 1 deletion apps/api/src/services/workspace-git-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export type WorkspaceGitSource = {
repositoryPath: string | null;
};

export type WorkspaceGitSourceProject = Pick<schema.Project, 'id' | 'repoProvider'>;
/**
* `repository` is required so every caller passes the clone URL it already holds: resolving an
* Artifacts project's host must not cost a D1 read on workspace creation.
*/
export type WorkspaceGitSourceProject = Pick<schema.Project, 'id' | 'repoProvider' | 'repository'>;

const DEFAULT_GITHUB_SOURCE: WorkspaceGitSource = {
repoProvider: 'github',
Expand All @@ -35,11 +39,57 @@ function normalizeRepoProvider(
}
}

/** Cloudflare Artifacts hosts; the VM agent recognizes these by name (`gitrepo.IsArtifactsHost`). */
function isCloudflareArtifactsHost(host: string): boolean {
return host === 'artifacts.cloudflare.net' || host.endsWith('.artifacts.cloudflare.net');
}

/**
* An Artifacts project's clone URL is `projects.repository` (the backend's `create().remote`). For a
* Cloudflare Artifacts remote nothing is added: the VM agent knows that host by name. A remote on
* any other host (a self-hosted install's own git server) is bound as `repositoryHost`, the only
* host the VM agent then attaches the workspace's git token to (`isBoundHostedArtifactsHost`).
*
* This trusts `repository` because SAM assigns it: `project-create.ts` stores the backend's remote
* and no route lets a user edit it for an Artifacts project. A route that ever does must validate
* the host, or it lets a user send a workspace token to any https host.
*/
/**
* The host the VM agent must be bound to for an Artifacts remote, or null when none is needed: a
* Cloudflare Artifacts host (the VM agent knows those by name), a non-https or unparseable remote,
* or a direct-provisioning request persisted by NodeLifecycle before `repository` was passed.
*/
export function boundArtifactsRepositoryHost(repository: string | undefined): string | null {
if (typeof repository !== 'string') return null;
let url: URL;
try {
url = new URL(repository);
} catch {
return null;
}
const host = url.host.toLowerCase();
if (url.protocol !== 'https:' || !host || isCloudflareArtifactsHost(host)) return null;
return host;
}

function resolveArtifactsGitSource(repository: string | undefined): WorkspaceGitSource {
const artifactsSource: WorkspaceGitSource = {
...DEFAULT_GITHUB_SOURCE,
repoProvider: 'artifacts',
};
const host = boundArtifactsRepositoryHost(repository);
if (!host || !repository) return artifactsSource;
return { ...artifactsSource, cloneUrl: repository, repositoryHost: host };
}

export async function resolveWorkspaceGitSource(
db: Db,
project: WorkspaceGitSourceProject
): Promise<WorkspaceGitSource> {
const repoProvider = normalizeRepoProvider(project.repoProvider);
if (repoProvider === 'artifacts') {
return resolveArtifactsGitSource(project.repository);
}
if (repoProvider !== 'gitlab') {
return {
...DEFAULT_GITHUB_SOURCE,
Expand Down Expand Up @@ -75,6 +125,7 @@ export async function resolveWorkspaceGitSourceByProjectId(
.select({
id: schema.projects.id,
repoProvider: schema.projects.repoProvider,
repository: schema.projects.repository,
})
.from(schema.projects)
.where(eq(schema.projects.id, projectId))
Expand Down
5 changes: 4 additions & 1 deletion apps/api/tests/setup/repo-hosting-ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* have registered, so the ports delegate to whatever worker modules the test mocked (most often
* `services/platform-config` and `auth`), as when repo hosting imported them directly. Each port
* loads on its own, so a test whose partial mocks break one port's module graph still gets the
* other, and fails only if it reaches the port it broke.
* others, and fails only if it reaches the port it broke.
*/
import { beforeAll } from 'vitest';

Expand All @@ -23,5 +23,8 @@ beforeAll(async () => {
import('../../src/repo-hosting-ports/auth')
.then((m) => configureRepoHostingPort('auth', m.authPort))
.catch(() => undefined),
import('../../src/repo-hosting-ports/artifacts')
.then((m) => configureRepoHostingPort('artifacts', m.artifactsPort))
.catch(() => undefined),
]);
}, PORT_SETUP_TIMEOUT_MS);
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,18 @@ function makeState(branch: string, outputBranch: string): TaskRunnerState {
} as TaskRunnerState;
}

function makeContext(): TaskRunnerContext {
function makeContext(projectRow?: { repoProvider: string; repository: string }): TaskRunnerContext {
const prepare = vi.fn((query: string) => ({
bind: vi.fn(() => ({
first: vi.fn(async () => {
if (query.includes('SELECT dispatched_at')) return { dispatched_at: null };
if (query.includes('FROM projects') && projectRow) {
// Return only the columns the statement actually selects.
return {
repoProvider: projectRow.repoProvider,
...(/\brepository\b/.test(query) ? { repository: projectRow.repository } : {}),
};
}
if (query.includes('FROM projects'))
return { repoProvider: 'github', installationId: 'installation-1' };
return null;
Expand Down Expand Up @@ -94,6 +101,19 @@ describe('TaskRunner workspace branch dispatch', () => {
});
});

it('passes the Artifacts clone URL from its existing project read to the git-source resolver', async () => {
const remote = 'https://api.sam.example/git/demo-01abc.git';
await handleWorkspaceDispatch(
makeState('sam/out-1', 'sam/out-1'),
makeContext({ repoProvider: 'artifacts', repository: remote })
);
expect(mocks.resolveWorkspaceGitSource).toHaveBeenCalledWith(expect.anything(), {
id: 'project-1',
repoProvider: 'artifacts',
repository: remote,
});
});

it.each([
{
scenario: 'generated output branch',
Expand Down
Loading
Loading