diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index b5114302..c154183c 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2310,8 +2310,10 @@ export interface paths { get: operations["get_api_v1_runs"]; put?: never; /** - * Start a project VM run with a literal prompt and optional launch skill - * @description Requires the runs:start scope. + * Start a project VM run with a prompt or script and per-run execution overrides + * @description Supply exactly one of prompt or script. Omitted execution settings use project defaults, then user defaults. Omitted integrationIds inherit this MCP client's effective integration access; explicit IDs select a subset, including an empty set. runScopes is limited to the caller's effective permissions. + * + * Requires the runs:start scope. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ @@ -2344,6 +2346,34 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/user/run-defaults": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get user defaults for direct VM runs + * @description Requires the projects:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_user_run_defaults"]; + /** + * Set user defaults for direct VM runs + * @description Requires the projects:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_user_run_defaults"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/search": { parameters: { query?: never; @@ -6773,6 +6803,11 @@ export interface operations { updatedAt: string; runDefaults?: { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -6833,6 +6868,11 @@ export interface operations { updatedAt: string; runDefaults?: { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -6889,6 +6929,11 @@ export interface operations { updatedAt: string; runDefaults?: { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -6951,6 +6996,11 @@ export interface operations { updatedAt: string; runDefaults?: { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -9671,9 +9721,21 @@ export interface operations { "application/json": { /** Format: uuid */ projectId?: string; - prompt: string; + prompt?: string; + script?: string; skill?: string; name?: string; + executionConfigId?: string; + vmImage?: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; + model?: string; + /** @description Factorize application permissions to grant. Omission inherits effective client permissions and an empty list grants none. */ + runScopes?: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + integrationIds?: string[]; inputs?: { [key: string]: unknown; }; @@ -9722,6 +9784,11 @@ export interface operations { content: { "application/json": { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -9748,6 +9815,11 @@ export interface operations { content: { "application/json": { executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: string; effort?: string; vmImage?: string; @@ -9776,6 +9848,124 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_user_run_defaults: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description User run defaults */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; + model?: string; + effort?: string; + vmImage?: unknown; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @description Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. */ + runScopes?: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + } | null; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_user_run_defaults: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; + model?: string; + effort?: string; + vmImage?: string; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @description Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. */ + runScopes?: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + }; + }; + }; + responses: { + /** @description User run defaults */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + executionConfigId: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; + model?: string; + effort?: string; + vmImage?: unknown; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @description Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. */ + runScopes?: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_search: { parameters: { query?: { diff --git a/packages/api/migrations/0066_user_run_defaults.sql b/packages/api/migrations/0066_user_run_defaults.sql new file mode 100644 index 00000000..a7eceaf5 --- /dev/null +++ b/packages/api/migrations/0066_user_run_defaults.sql @@ -0,0 +1,9 @@ +CREATE TABLE app.user_run_defaults ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, + run_defaults jsonb NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, user_id) +); + +INSERT INTO app.schema_migrations(version) VALUES ('0066_user_run_defaults') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 32785d85..5fba33f8 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -96,6 +96,7 @@ export class AgentApiService { return {id: row.id, kind, config, policy: row}; } private selected(row: AgentIntegration, config: Record) { + if (Array.isArray(config.agentIntegrationIds)) return config.agentIntegrationIds.includes(row.id); switch(row.kind) { case "bearer": return Array.isArray(config.portableIntegrationIds) && config.portableIntegrationIds.includes(row.credential_id); case "github": return Array.isArray(config.githubInstallationIds) && config.githubInstallationIds.includes(Number(row.credential_id)); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 06f6a7d7..c97b0319 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -15,7 +15,7 @@ import { z } from "zod"; import type { ApiService } from "./flow-service"; import { jobInputSchema, - startRunInput, startRunReceipt, projectRunDefaults, storedRunDefaults, manualInvocationSchema, + startRunInput, startRunReceipt, projectRunDefaults, storedRunDefaults, userRunDefaults, manualInvocationSchema, renameRunSchema, reportRunErrorSchema, invocationPermissionsInput, @@ -1001,13 +1001,16 @@ export const API_ROUTES: RouteContract[] = [ (service, { params }) => service.deleteJob(params.jobId), ), route("POST","/api/v1/runs","runs:start",{ - summary:"Start a project VM run with a literal prompt and optional launch skill", + summary:"Start a project VM run with a prompt or script and per-run execution overrides", + description:"Supply exactly one of prompt or script. Omitted execution settings use project defaults, then user defaults. Omitted integrationIds inherit this MCP client's effective integration access; explicit IDs select a subset, including an empty set. runScopes is limited to the caller's effective permissions.", responses:{"202":{description:"Accepted run",content:{"application/json":{schema:jsonSchema(startRunReceipt,"output")}}}}, },(service,{body})=>service.startRun(body),{body:startRunInput,maxBodyBytes:256_000}), route("PUT","/api/v1/projects/{projectId}/run-defaults","projects:write",{ summary:"Set the VM configuration, permissions and capacity for direct launches", responses:{"200":{description:"Project run defaults",content:{"application/json":{schema:jsonSchema(storedRunDefaults,"output")}}}}, },(service,{params,body})=>service.setRunDefaults(params.projectId,body),{body:projectRunDefaults,parameters:z.object({projectId:z.guid()}),ownerSession:true}), + route("GET","/api/v1/user/run-defaults","projects:read",{summary:"Get user defaults for direct VM runs",responses:{"200":{description:"User run defaults",content:{"application/json":{schema:jsonSchema(userRunDefaults.nullable(),"output")}}}}},service=>service.getUserRunDefaults()), + route("PUT","/api/v1/user/run-defaults","projects:write",{summary:"Set user defaults for direct VM runs",responses:{"200":{description:"User run defaults",content:{"application/json":{schema:jsonSchema(userRunDefaults,"output")}}}}},(service,{body})=>service.setUserRunDefaults(body),{body:userRunDefaults,ownerSession:true}), route( "GET", "/api/v1/runs", diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index a8d4b590..00b4766c 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -115,18 +115,29 @@ export const jobConditionsTestSchema = z.object({ export type JobInput = z.infer; export type ManualInvocationInput = z.infer; +const modelProvider = z.enum(["codex", "claude", "pi"]).optional().describe("Agent harness used for the selected model."); export const startRunInput = z.object({ projectId: z.guid().optional(), - prompt: z.string().min(1).max(50_000).refine(value => !!value.trim()), + prompt: z.string().min(1).max(50_000).refine(value => !!value.trim()).optional(), + script: z.string().min(1).max(200_000).refine(value => !!value.trim()).optional(), skill: z.string().min(1).max(64).optional(), name: z.string().trim().min(1).max(120).optional(), + executionConfigId: z.string().min(1).optional(), + vmImage: jobInputSchema.shape.vmImage, + modelProvider, + model: jobInputSchema.shape.model, + runScopes: jobInputSchema.shape.runScopes.describe("Factorize application permissions to grant. Omission inherits effective client permissions and an empty list grants none."), + integrationIds: z.array(z.uuid()).max(100).refine(ids => new Set(ids).size === ids.length, "Integration IDs must be unique").optional(), inputs: z.record(z.string(), z.unknown()).refine(value => new TextEncoder().encode(JSON.stringify(value)).length <= 200_000, "Inputs exceed 200,000 bytes").optional(), idempotencyKey: z.string().trim().min(1).max(200).optional(), -}).strict(); +}).strict().refine(value => Number(Boolean(value.prompt)) + Number(Boolean(value.script)) === 1, { + message: "Supply exactly one of prompt or script.", + path: ["prompt"], +}); export const startRunReceipt = z.object({runId:z.guid(), url:z.url(), outcomeUri:z.string(), duplicate:z.boolean()}); export const projectRunDefaults = z.object({ executionConfigId: jobInputSchema.shape.executionConfigId, - model: jobInputSchema.shape.model, effort: jobInputSchema.shape.effort, vmImage: jobInputSchema.shape.vmImage, + modelProvider, model: jobInputSchema.shape.model, effort: jobInputSchema.shape.effort, vmImage: jobInputSchema.shape.vmImage, tags: jobInputSchema.shape.tags, modelAccountId: jobInputSchema.shape.modelAccountId, portableIntegrationIds: jobInputSchema.shape.portableIntegrationIds, githubInstallationIds: jobInputSchema.shape.githubInstallationIds, linearConnectionId: jobInputSchema.shape.linearConnectionId, xConnectionIds: jobInputSchema.shape.xConnectionIds, @@ -134,3 +145,4 @@ export const projectRunDefaults = z.object({ }).strict(); export const storedRunDefaults = projectRunDefaults.extend({vmImage:z.string().optional()}); +export const userRunDefaults = projectRunDefaults.omit({capacity:true}); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index ce1e35a8..42ac9684 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -5,7 +5,7 @@ import { SkillLibrary } from "./skill-library"; import { configureLibrary } from "./skill-library-contract"; import { submitRun } from "./postgres/run-submission"; import type { DatabaseClient } from "./postgres/database"; -import { startRunInput,projectRunDefaults } from "./flow-schemas"; +import { startRunInput,projectRunDefaults,userRunDefaults as userRunDefaultsSchema,scopeSchema } from "./flow-schemas"; import { grantVm, revokeVmGrant } from "./vm-grants"; import { AgentApiService, listAgentPolicies } from "./agent-api"; import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; @@ -253,7 +253,7 @@ export class ApiService { }; } - private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) { + private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[], modelProvider?: keyof typeof effortOptions) { if (id === "docker") throw new ServiceError(400, "invalid_request", "Docker test execution supports code jobs only."); if (id.startsWith("amp:")) return; const connection = await this.connections().get(`exe:${id}`); @@ -261,9 +261,11 @@ export class ApiService { if (await this.flyExecutionConfigs().get(id)) return; throw new ServiceError(400, "invalid_request", "execution integration not found"); } - const availableModels = connection.modelsByAgent?.[connection.agentKind ?? "codex"] ?? connection.models ?? []; - const availableEfforts = effortOptions[connection.agentKind ?? "codex"] ?? []; - if (model && availableModels.length && !availableModels.includes(model)) throw new ServiceError(400, "invalid_request", "Model is not available on this agent."); + const provider = modelProvider ?? connection.agentKind ?? "codex"; + const sameProvider = provider === (connection.agentKind ?? "codex"); + const availableModels = connection.modelsByAgent?.[provider] ?? (sameProvider ? connection.models : undefined) ?? []; + const availableEfforts = effortOptions[provider]; + if (model && (availableModels.length || !sameProvider) && !availableModels.includes(model)) throw new ServiceError(400, "invalid_request", "Model is not available on this agent."); if (effort && availableEfforts.length && !availableEfforts.includes(effort)) throw new ServiceError(400, "invalid_request", "Effort is not available on this agent."); const availableTags = new Set(selectableExeTags(connection)); if (tags.some(tag => !availableTags.has(tag))) throw new ServiceError(400, "invalid_request", "VM tags must be selected from the available exe.dev labels."); @@ -979,24 +981,42 @@ export class ApiService { return input; } - private async resolveRunDefaults(input: z.infer) { - await this.validateExecutionOptions( + async getUserRunDefaults() { + await this.authorize("projects:read"); + const result = await databaseFor(this.env).pool.query("SELECT run_defaults FROM app.user_run_defaults WHERE tenant_id=$1 AND user_id=$2", [this.auth.tenantId, this.auth.userId]); + return result.rows[0]?.run_defaults ?? null; + } + + async setUserRunDefaults(input: z.infer) { + await this.authorizeOwnerSession("projects:write"); + await this.resolveRunDefaults({...input, capacity: 4}); + const result = await databaseFor(this.env).pool.query(`INSERT INTO app.user_run_defaults(tenant_id,user_id,run_defaults) + VALUES($1,$2,$3) ON CONFLICT(tenant_id,user_id) DO UPDATE SET run_defaults=excluded.run_defaults,updated_at=now() RETURNING run_defaults`, [this.auth.tenantId, this.auth.userId, input]); + return result.rows[0].run_defaults; + } + + private async resolveRunDefaults(input: z.infer, executionType: "agent" | "code" = "agent") { + if (input.executionConfigId !== "docker" || executionType === "agent") await this.validateExecutionOptions( input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? [], + input.modelProvider, ); const config = await this.executionConfig(input.executionConfigId); if (config.agentKind === "Amp") throw new ServiceError(400, "invalid_request", "Select a VM agent configuration."); - const portable = await this.portableSelections(config, "agent", { + if (input.modelProvider && config.executionProvider !== "exe" && input.modelProvider !== config.agentKind) + throw new ServiceError(400, "invalid_request", "Model provider is unavailable on the selected VM configuration."); + if (input.modelProvider) config.agentKind = input.modelProvider; + const portable = await this.portableSelections(config, executionType, { ...input, modelAccess: input.modelAccountId ? "portable" : undefined, }); return { ...config, ...portable, - executionType: "agent", + executionType, model: input.model ?? "", effort: input.effort, tags: input.tags ?? [], @@ -1064,15 +1084,60 @@ export class ApiService { if (prior) return prior; const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); - if (!project.runDefaults) - throw new ServiceError(409, "run_defaults_required", "Configure this project's VM run defaults first."); - const config = await this.resolveRunDefaults(project.runDefaults); + const userDefaultsResult = await db.pool.query("SELECT run_defaults FROM app.user_run_defaults WHERE tenant_id=$1 AND user_id=$2", [auth.tenantId, auth.userId]); + const userDefaults = userDefaultsResult.rows[0]?.run_defaults; + const defaults = { ...(userDefaults ?? {}), ...(project.runDefaults ?? {}) }; + if (!defaults.executionConfigId && !input.executionConfigId) + throw new ServiceError(409, "run_defaults_required", "Configure project or user VM run defaults first."); + const isAgentClient = auth.authMethod === "oauth" || auth.authMethod === "vm_grant" || auth.authMethod === "vendor_identity"; + const access = isAgentClient ? await this.agentApi().reflection() : undefined; + const effectiveScopes = access?.scopes ?? normalizeScopes(auth.scopes); + const callerScopes = auth.runId ? [] : scopeSchema.options.filter(scope => effectiveScopes.includes(scope)); + const runScopes = input.runScopes ?? callerScopes; + if (runScopes.some(scope => !callerScopes.includes(scope))) + throw new ServiceError(403, "forbidden", "Requested run permissions exceed this client's effective Factorize access."); + + const granted = access?.integrations.filter(item => item.access === "granted" && + (auth.authMethod !== "oauth" || effectiveScopes.includes("proxy:use"))) ?? []; + const byId = new Map(granted.map(item => [item.id, item])); + const integrationIds = input.integrationIds ?? granted.map(item => item.id); + const selected = integrationIds.map(id => { + const integration = byId.get(id); + if (!integration) throw new ServiceError(403, "forbidden", "Requested integrations exceed this client's effective integration access."); + return integration; + }); + const inheritConfigured = auth.authMethod === "session" && input.integrationIds === undefined; + const selections = inheritConfigured ? defaults : { + portableIntegrationIds: selected.filter(item => item.kind === "bearer").map(item => item.credentialId), + githubInstallationIds: selected.filter(item => item.kind === "github").map(item => Number(item.credentialId)), + linearConnectionId: selected.some(item => item.kind === "linear") ? "linear" : undefined, + xConnectionIds: selected.filter(item => item.kind === "x").map(item => item.credentialId), + modelAccountId: selected.find(item => item.kind === "model" && item.credentialId === defaults.modelAccountId)?.credentialId, + }; + const resolved = await this.resolveRunDefaults({ + ...defaults, + ...selections, + capacity: defaults.capacity ?? 4, + executionConfigId: input.executionConfigId ?? defaults.executionConfigId, + vmImage: input.vmImage ?? (project.runDefaults?.vmImage || userDefaults?.vmImage), + model: input.script ? "" : input.model ?? (project.runDefaults?.model || userDefaults?.model), + modelProvider: input.script ? undefined : input.modelProvider ?? defaults.modelProvider, + effort: input.script ? undefined : defaults.effort, + modelAccountId: input.script ? undefined : selections.modelAccountId, + }, input.script ? "code" : "agent"); + const config = { + ...resolved, + runScopes, + ...(inheritConfigured ? {} : {agentIntegrationIds: integrationIds}), + ...(input.script ? {script: input.script} : {}), + }; const skill = input.skill ? await this.skills().get(input.skill) : null; + if (input.script && skill) throw new ServiceError(400, "invalid_request", "Script runs cannot include an agent skill."); if (input.skill && !skill) throw new ServiceError(404, "not_found", "Launch skill not found"); - const text = + const text = input.prompt ? input.inputs && Object.keys(input.inputs).length ? input.prompt + "\n\nInputs (JSON)\n" + JSON.stringify(input.inputs) - : input.prompt; + : input.prompt : ""; const prompt = composePrompt(skill ? [{ body: skill.body! }] : [], text); const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const encryptedSkills = skill @@ -1084,10 +1149,7 @@ export class ApiService { ) : undefined; const result = await db.transaction(async (client) => { - const locked = await client.query( - "SELECT run_defaults=$3::jsonb matches FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE", - [auth.tenantId, projectId, project.runDefaults], - ); + const locked = await client.query("SELECT run_defaults IS NOT DISTINCT FROM $3::jsonb matches FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [auth.tenantId, projectId, project.runDefaults ?? null]); const duplicate = await existing(client); if (duplicate) return duplicate; if (!locked.rows[0]?.matches) @@ -1096,6 +1158,9 @@ export class ApiService { "configuration_changed", "Project configuration changed. Retry this request.", ); + const currentUserDefaults = await client.query("SELECT run_defaults FROM app.user_run_defaults WHERE tenant_id=$1 AND user_id=$2 FOR SHARE", [auth.tenantId, auth.userId]); + if (JSON.stringify(currentUserDefaults.rows[0]?.run_defaults ?? null) !== JSON.stringify(userDefaults ?? null)) + throw new ServiceError(409, "configuration_changed", "User run defaults changed. Retry this request."); if (auth.runId) { const active = await client.query( "SELECT id FROM app.runs WHERE tenant_id=$1 AND id=$2 AND project_id=$3 AND state IN ('starting','running','blocked') FOR SHARE", diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index ee90679a..c4f6676b 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -102,6 +102,7 @@ export const linearWorkspaces = app.table("linear_workspaces", { organizationId: export const githubInstallations = app.table("github_installations", { installationId: bigint("installation_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), accountLogin: text("account_login").notNull(), accountType: text("account_type").notNull(), state: text("state").$type<"active" | "suspended">().notNull(), updatedAt: updatedAt() }, t => [unique().on(t.tenantId, t.installationId), check("github_installations_state_check", sql`${t.state} in ('active','suspended')`)]); export const githubSetupStates = app.table("github_setup_states", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), nonce: text("nonce").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.nonce] }), index("github_setup_states_expiration").on(t.expiresAt,t.tenantId,t.nonce)]); export const projects = app.table("projects", { runDefaults:jsonb("run_defaults"), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), description: text("description"), createdAt: createdAt(), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.name), index("projects_tenant_updated").on(t.tenantId, t.updatedAt)]); +export const userRunDefaults = app.table("user_run_defaults", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, {onDelete:"cascade"}), userId: uuid("user_id").notNull().references(() => authUsers.id, {onDelete:"cascade"}), runDefaults: jsonb("run_defaults").notNull(), updatedAt: updatedAt() }, t => [primaryKey({columns:[t.tenantId,t.userId]})]); export const jobs = app.table("jobs", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), projectId: uuid("project_id").notNull(), name: text("name").notNull(), description: text("description").notNull().default(""), slug: text("slug").notNull(), runScopes: jsonb("run_scopes").$type().notNull().default(DEFAULT_RUN_SCOPES), encryptedPromptTemplate: text("encrypted_prompt_template").notNull(), encryptedRunNameTemplate: text("encrypted_run_name_template").notNull().default(""), executionConfig: jsonb("execution_config").$type().notNull(), tags: jsonb("tags").$type().notNull().default([]), model: text("model").notNull().default(""), effort: text("effort").notNull().default(""), concurrencyLimit: integer("concurrency_limit").notNull(), enabled: boolean("enabled").notNull().default(true), createdAt: createdAt(), updatedAt: updatedAt(), diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 1655126a..86a80147 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -185,7 +185,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("delete_job", "Delete a saved job and its triggers, retaining its runs", jobIdSchema, ({ jobId }: any) => service.deleteJob(jobId)); tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true)); tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false)); - tool("start_run","Start a detached project VM run. Supply a literal prompt and optionally a launch skill. Subscribe to the returned outcome URI.",startRunInput,(input:any)=>service.startRun(input)); + tool("start_run","Start a detached project VM run with exactly one literal prompt or shell script. Omitted execution settings use project defaults, then user defaults. Omitted integrationIds inherit this MCP client's effective integration access; explicit IDs select a subset, including an empty set. Omitted runScopes inherit this MCP client's effective Factorize permissions. Subscribe to the returned outcome URI.",startRunInput,(input:any)=>service.startRun(input)); tool("invoke_job", "Invoke a job's manual trigger with an optional display name, prompt, and JSON data exposed beneath that trigger's stable slug. Manual invocations are never coalesced; a full job queue returns queue_full. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); tool("get_job_invocation_permissions", "List the destinations a source job may manually invoke.", jobIdSchema, ({ jobId }: any) => service.getInvocationPermissions(jobId)); tool("set_job_invocation_permissions", "Replace manual invocation destinations for a source job. Requires an owner session, scoped API key, or authorized OAuth client with jobs:write; destination IDs must belong to the same tenant.", z.object({ jobId: z.string().min(1), destinationJobIds: z.array(z.string().uuid()).max(1000) }).strict(), ({ jobId, destinationJobIds }: any) => service.setInvocationPermissions(jobId, destinationJobIds)); diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index 1364c115..035dd5f0 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -8,7 +8,7 @@ import { isDeclaredApiOperation, matchApiOperation, } from "../src/api-contract"; -import { listRunsSchema, jobInputSchema, vmImageVerificationInput } from "../src/flow-schemas"; +import { listRunsSchema, jobInputSchema, vmImageVerificationInput, startRunInput } from "../src/flow-schemas"; export const openapi = parse( readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"), @@ -25,6 +25,15 @@ const methods = new Set([ ]); describe("versioned API contract", () => { + it("accepts direct prompt and script launches with bounded overrides and permission subsets", () => { + expect(startRunInput.safeParse({ prompt: "hello" }).success).toBe(true); + expect(startRunInput.safeParse({ script: "#!/bin/sh\necho ok", vmImage: "ghcr.io/org/image@sha256:" + "a".repeat(64), executionConfigId: "config", model: "gpt-test", runScopes: [] }).success).toBe(true); + expect(startRunInput.safeParse({}).success).toBe(false); + expect(startRunInput.safeParse({ prompt: "hello", script: "echo ok" }).success).toBe(false); + expect(startRunInput.safeParse({ prompt: " " }).success).toBe(false); + expect(startRunInput.safeParse({ script: " " }).success).toBe(false); + expect(startRunInput.safeParse({ script: "echo ok", runScopes: ["integration:private"] }).success).toBe(false); + }); it("validates run sorting fields and directions", () => { expect(listRunsSchema.safeParse({ sort: "job", direction: "asc" }).success).toBe(true); expect(listRunsSchema.safeParse({ sort: "agent", direction: "desc" }).success).toBe(true); diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts new file mode 100644 index 00000000..a012306f --- /dev/null +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService, ServiceError } from "../src/flow-service"; +import { ConnectionRepository } from "../src/postgres/connection-repository"; +import { encrypt } from "../src/crypto"; +import { MANAGED_BEARER_PREFIX } from "../src/postgres/credential-repository"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +const defaults = (vmImage: string) => ({ executionConfigId: "local", model: "", effort: "", vmImage, tags: [], portableIntegrationIds: [], githubInstallationIds: [], xConnectionIds: [], runScopes: [] }); + +describe.skipIf(!url)("direct run defaults and integration access", { timeout: 30_000 }, () => { + it("uses user defaults when the project has none and inherits or narrows effective integrations", async () => { + const f = await loadingFixture(url!); + try { + const credentialId = crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1)", [f.tenantId]); + const encryptedPayload = await encrypt(`${MANAGED_BEARER_PREFIX}test-only-secret`, f.env.CREDENTIAL_ENCRYPTION_KEY); + await f.db.pool.query("INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,revision,encrypted_payload) VALUES($1,$2,'bearer','Direct test','https://upstream.test',1,$3)", [f.tenantId, credentialId, encryptedPayload]); + await f.db.pool.query("UPDATE app.agent_integrations SET policy='baseline' WHERE tenant_id=$1 AND kind='bearer' AND credential_id=$2", [f.tenantId, credentialId]); + const integrationRow = await f.db.pool.query("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind='bearer' AND credential_id=$2", [f.tenantId, credentialId]); + const effectiveIntegrationId = integrationRow.rows[0].id as string; + await f.db.pool.query("INSERT INTO app.user_run_defaults(tenant_id,user_id,run_defaults) VALUES($1,$2,$3)", [f.tenantId, f.userId, defaults("ghcr.io/factorize/direct-run:test")]); + + const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "projects:read", "integrations:read", "proxy:use"] }); + const inherited = await service.startRun({ projectId: f.projectId, prompt: "Keep prompt requests compatible", idempotencyKey: "inherit" }); + const inheritedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, inherited.runId])).rows[0].execution_config; + expect(inheritedConfig.image).toBe("ghcr.io/factorize/direct-run:test"); + expect(inheritedConfig.portableIntegrationIds).toEqual([credentialId]); + expect(inheritedConfig.agentIntegrationIds).toEqual([effectiveIntegrationId]); + + const empty = await service.startRun({ projectId: f.projectId, script: "echo direct", integrationIds: [], idempotencyKey: "empty" }); + const emptyConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, empty.runId])).rows[0].execution_config; + expect(emptyConfig.executionType).toBe("code"); + expect(emptyConfig.agentIntegrationIds).toEqual([]); + expect(emptyConfig.portableIntegrationIds).toEqual([]); + + const narrowed = await service.startRun({ projectId: f.projectId, script: "echo narrowed", integrationIds: [effectiveIntegrationId], runScopes: ["projects:read"] }); + const narrowedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, narrowed.runId])).rows[0].execution_config; + expect(narrowedConfig).toMatchObject({agentIntegrationIds: [effectiveIntegrationId], runScopes: ["projects:read"]}); + const withoutProxy = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "narrow", oauthClientId: "client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start"] }); + await expect(withoutProxy.startRun({ projectId: f.projectId, prompt: "narrowed token", integrationIds: [effectiveIntegrationId] })).rejects.toMatchObject({ status: 403 }); + const denied = crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) VALUES($1,$2,'bearer',$3,'Requestable only',true,'requestable')", [f.tenantId, denied, crypto.randomUUID()]); + await expect(service.startRun({ projectId: f.projectId, prompt: "not authorized", integrationIds: [denied], idempotencyKey: "denied" })).rejects.toMatchObject({ status: 403, code: "forbidden" } satisfies Partial); + } finally { await f.cleanup(); } + }); + + it("uses project execution defaults before user defaults", async () => { + const f = await loadingFixture(url!); + try { + await f.db.pool.query("INSERT INTO app.user_run_defaults(tenant_id,user_id,run_defaults) VALUES($1,$2,$3)", [f.tenantId, f.userId, { ...defaults("ghcr.io/factorize/user-default:test"), model: "user-default-model" }]); + const projectDefaults = { ...defaults("ghcr.io/factorize/project-default:test"), capacity: 4 } as Record; + projectDefaults.model = ""; + await f.db.pool.query("UPDATE app.projects SET run_defaults=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.projectId, projectDefaults]); + const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "projects:read", "integrations:read", "proxy:use"] }); + const run = await service.startRun({ projectId: f.projectId, prompt: "project wins", integrationIds: [], idempotencyKey: "project-first" }); + const config = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, run.runId])).rows[0].execution_config; + expect(config.image).toBe("ghcr.io/factorize/project-default:test"); + expect(config.model).toBe("user-default-model"); + } finally { await f.cleanup(); } + }); + + it("inherits effective MCP scopes, accepts an empty subset, and rejects disabled scopes", async () => { + const f = await loadingFixture(url!); + try { + await f.db.pool.query("INSERT INTO app.user_run_defaults(tenant_id,user_id,run_defaults) VALUES($1,$2,$3)", [f.tenantId, f.userId, defaults("ghcr.io/factorize/direct-run:test")]); + await f.db.pool.query("INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,disabled_scopes) VALUES($1,'oauth','test-grant',$2,$3,$4)", [f.tenantId, f.userId, f.auth.sessionVersion, ["jobs:write"]]); + const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "projects:read", "integrations:read", "jobs:write"] }); + + const inherited = await service.startRun({ projectId: f.projectId, prompt: "inherit effective access", idempotencyKey: "effective-scopes" }); + const inheritedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, inherited.runId])).rows[0].execution_config; + expect(inheritedConfig.runScopes).toContain("runs:start"); + expect(inheritedConfig.runScopes).not.toContain("jobs:write"); + + const empty = await service.startRun({ projectId: f.projectId, script: "echo no permissions", integrationIds: [], runScopes: [], idempotencyKey: "empty-scopes" }); + const emptyConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, empty.runId])).rows[0].execution_config; + expect(emptyConfig.runScopes).toEqual([]); + + await expect(service.startRun({ projectId: f.projectId, prompt: "cannot delegate disabled scope", runScopes: ["jobs:write"], idempotencyKey: "denied-scope" })).rejects.toMatchObject({ status: 403, code: "forbidden" } satisfies Partial); + } finally { await f.cleanup(); } + }); + + it("validates the resolved agent model against the selected execution provider", async () => { + const f = await loadingFixture(url!); + try { + await new ConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).put("exe:local", { apiToken: "private-exe-token", agentKind: "codex", models: ["supported-model"], modelsByAgent: {claude: ["claude-model"]} }); + await f.db.pool.query("INSERT INTO app.user_run_defaults(tenant_id,user_id,run_defaults) VALUES($1,$2,$3)", [f.tenantId, f.userId, defaults("")]); + const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "projects:read", "integrations:read", "proxy:use"] }); + await expect(service.startRun({ projectId: f.projectId, prompt: "invalid model", model: "other-model", integrationIds: [], idempotencyKey: "invalid-model" })).rejects.toMatchObject({ status: 400, code: "invalid_request" }); + await expect(service.startRun({ projectId: f.projectId, prompt: "mismatch", modelProvider: "claude", model: "supported-model" })).rejects.toMatchObject({ status: 400 }); + const override = await service.startRun({ projectId: f.projectId, prompt: "provider override", modelProvider: "claude", model: "claude-model" }); + const overrideConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, override.runId])).rows[0].execution_config; + expect(overrideConfig).toMatchObject({ agentKind: "claude", model: "claude-model" }); + const script = await service.startRun({ projectId: f.projectId, script: "echo direct", model: "other-model", vmImage: "alpine:3.22", integrationIds: [], idempotencyKey: "script" }); + const scriptConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, script.runId])).rows[0].execution_config; + expect(scriptConfig).toMatchObject({ executionType: "code", model: "", script: "echo direct", image: "alpine:3.22" }); + const run = await service.startRun({ projectId: f.projectId, prompt: "valid model", model: "supported-model", integrationIds: [], idempotencyKey: "valid-model" }); + const config = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, run.runId])).rows[0].execution_config; + expect(config.agentKind).toBe("codex"); + expect(config.model).toBe("supported-model"); + } finally { await f.cleanup(); } + }); +}); diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index 4955c709..569344f4 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -91,7 +91,8 @@ JS await raw.upload!("/tmp/fixture-ca.crt",new Uint8Array(await readFile(join(tls,"ca.crt")))); // This signing key exists only inside this isolated fixture. Production // trusts Fly's JWKS; it cannot accept this test issuer key. - const source=`const http=require('node:http'),crypto=require('node:crypto');const key=${JSON.stringify(pair.privateKey.export({type:"pkcs8",format:"pem"}).toString())};require('node:fs').mkdirSync('/.fly',{recursive:true});http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{const now=Math.floor(Date.now()/1000),h=Buffer.from(JSON.stringify({alg:'RS256',kid:'docker-fixture'})).toString('base64url'),p=Buffer.from(JSON.stringify({iss:${JSON.stringify(issuer)},sub:${JSON.stringify(org+":"+app+":"+app+"-"+runId)},aud:JSON.parse(body).aud,machine_id:${JSON.stringify(id)},iat:now,exp:now+120})).toString('base64url'),data=h+'.'+p;res.end(data+'.'+crypto.sign('RSA-SHA256',Buffer.from(data),key).toString('base64url'));});}).listen('/.fly/api');`; + const machine = await infrastructure.machines.inspectMachine(app, id); + const source=`const http=require('node:http'),crypto=require('node:crypto');const key=${JSON.stringify(pair.privateKey.export({type:"pkcs8",format:"pem"}).toString())};require('node:fs').mkdirSync('/.fly',{recursive:true});http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{const now=Math.floor(Date.now()/1000),h=Buffer.from(JSON.stringify({alg:'RS256',kid:'docker-fixture'})).toString('base64url'),p=Buffer.from(JSON.stringify({iss:${JSON.stringify(issuer)},sub:${JSON.stringify(org+":"+app+":"+machine.name)},aud:JSON.parse(body).aud,machine_id:${JSON.stringify(id)},iat:now,exp:now+120})).toString('base64url'),data=h+'.'+p;res.end(data+'.'+crypto.sign('RSA-SHA256',Buffer.from(data),key).toString('base64url'));});}).listen('/.fly/api');`; await raw.upload!("/tmp/vendor-fixture.cjs",new TextEncoder().encode(source)); const started=await raw.run(["sh","-c","nohup node /tmp/vendor-fixture.cjs >/tmp/vendor-fixture.log 2>&1 "$FACTORIZE_RESULT_PATH" +`, + }); + let directRun; + const directDeadline = Date.now() + 60_000; + do { + await runner.tick(); + directRun = (await db.pool.query("SELECT job_id,state,job_result,failure_reason FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId,direct.runId])).rows[0]; + if (["succeeded", "failed", "stopped"].includes(directRun.state)) break; + await wait(200); + } while (Date.now() < directDeadline); + expect(directRun, directRun.failure_reason).toMatchObject({job_id: null, state: "succeeded", job_result: {outputs: {mode: "direct"}}}); }finally{ await runner?.close();await api?.close();vi.unstubAllGlobals(); for(const id of docker("ps","-aq","--filter",`label=sh.factorize.test.namespace=${app}`).split("\n").filter(Boolean))docker("rm","-f",id); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 30d714fc..00dc3eaf 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -8649,6 +8649,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -8809,6 +8816,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -8971,6 +8985,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -9120,6 +9141,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -15803,7 +15831,13 @@ paths: minLength: 1 /api/v1/runs: post: - summary: Start a project VM run with a literal prompt and optional launch skill + summary: Start a project VM run with a prompt or script and per-run execution overrides + description: |- + Supply exactly one of prompt or script. Omitted execution settings use project defaults, then user defaults. Omitted integrationIds inherit this MCP client's effective integration access; explicit IDs select a subset, including an empty set. runScopes is limited to the caller's effective permissions. + + Requires the runs:start scope. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "202": description: Accepted run @@ -15847,10 +15881,6 @@ paths: $ref: "#/components/responses/Error500" "503": $ref: "#/components/responses/Error503" - description: |- - Requires the runs:start scope. - - Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_runs tags: - runs @@ -15876,6 +15906,10 @@ paths: type: string minLength: 1 maxLength: 50000 + script: + type: string + minLength: 1 + maxLength: 200000 skill: type: string minLength: 1 @@ -15884,6 +15918,50 @@ paths: type: string minLength: 1 maxLength: 120 + executionConfigId: + type: string + minLength: 1 + vmImage: + type: string + maxLength: 512 + pattern: ^(?:(?:(?:[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*\/)?[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*(?:\/[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[a-f0-9]{64})?))?$ + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi + model: + type: string + maxLength: 120 + runScopes: + description: Factorize application permissions to grant. Omission inherits effective client permissions and an empty list grants none. + maxItems: 13 + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + integrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ inputs: type: object propertyNames: @@ -15893,8 +15971,6 @@ paths: type: string minLength: 1 maxLength: 200 - required: - - prompt additionalProperties: false get: summary: List runs @@ -16067,6 +16143,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -16187,6 +16270,13 @@ paths: executionConfigId: type: string minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi model: type: string maxLength: 120 @@ -16261,6 +16351,326 @@ paths: required: - executionConfigId additionalProperties: false + /api/v1/user/run-defaults: + get: + summary: Get user defaults for direct VM runs + responses: + "200": + description: User run defaults + content: + application/json: + schema: + anyOf: + - type: object + properties: + executionConfigId: + type: string + minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi + model: + type: string + maxLength: 120 + effort: + type: string + maxLength: 40 + vmImage: {} + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + portableIntegrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + maxItems: 100 + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" + xConnectionIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + runScopes: + description: Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. + maxItems: 13 + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + required: + - executionConfigId + additionalProperties: false + - type: "null" + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the projects:read scope. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + operationId: get_api_v1_user_run_defaults + tags: + - user + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: projects:read + x-owner-session-required: false + put: + summary: Set user defaults for direct VM runs + responses: + "200": + description: User run defaults + content: + application/json: + schema: + type: object + properties: + executionConfigId: + type: string + minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi + model: + type: string + maxLength: 120 + effort: + type: string + maxLength: 40 + vmImage: {} + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + portableIntegrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + maxItems: 100 + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" + xConnectionIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + runScopes: + description: Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. + maxItems: 13 + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + required: + - executionConfigId + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the projects:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: put_api_v1_user_run_defaults + tags: + - user + security: + - cookieAuth: [] + x-required-scope: projects:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + executionConfigId: + type: string + minLength: 1 + modelProvider: + description: Agent harness used for the selected model. + type: string + enum: + - codex + - claude + - pi + model: + type: string + maxLength: 120 + effort: + type: string + maxLength: 40 + vmImage: + type: string + maxLength: 512 + pattern: ^(?:(?:(?:[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*\/)?[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*(?:\/[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*)*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[a-f0-9]{64})?))?$ + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + modelAccountId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + portableIntegrationIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + maxItems: 100 + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" + xConnectionIds: + maxItems: 100 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + runScopes: + description: Factorize API scopes for new job runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. jobs:write permits configuring jobs and their future run scopes. + maxItems: 13 + type: array + items: + type: string + enum: + - projects:read + - projects:write + - jobs:read + - jobs:write + - runs:read + - runs:invoke + - runs:start + - runs:cancel + - runs:write + - integrations:read + - integrations:write + - skills:read + - skills:write + required: + - executionConfigId + additionalProperties: false /api/v1/search: get: summary: Search jobs and runs by approximate metadata matches diff --git a/scripts/background-run-acceptance.mjs b/scripts/background-run-acceptance.mjs index b607520b..6bb6e5e8 100644 --- a/scripts/background-run-acceptance.mjs +++ b/scripts/background-run-acceptance.mjs @@ -178,4 +178,13 @@ export async function backgroundRunAcceptance({ assert.equal(retained.invocation.template_job_id, template.body.id); assert.equal(retained.launch_skill_key, "dev"); assert.equal(retained.prompt, savedRun.prompt); + const ambiguous = await rpc(token, "start_run", { ...args, script: "echo ambiguous" }); + assert.ok(!ambiguous.result?.runId, ambiguous.text); + const directScript = await rpc(token, "start_run", { projectId, script: "echo direct", integrationIds: [], runScopes: [] }); + assert.ok(directScript.result?.runId, directScript.text); + const snapshot = (await db.query("SELECT job_id, execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenant, directScript.result.runId])).rows[0]; + assert.equal(snapshot.job_id, null); + assert.equal(snapshot.execution_config.script, "echo direct"); + assert.equal(snapshot.execution_config.executionType, "code"); + await rpc(token, "stop_run", { runId: directScript.result.runId }); }