From a97d7fcebd739970113fb2dce150345b13aff504 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 19 Nov 2026 23:52:13 +0000 Subject: [PATCH 1/9] Add script launches and direct run overrides --- packages/api/src/api-contract.ts | 3 +- packages/api/src/flow-schemas.ts | 12 +++++-- packages/api/src/flow-service.ts | 23 +++++++++--- packages/api/src/protected-api.ts | 2 +- packages/api/test/api-contract.test.ts | 11 +++++- packages/docs/openapi.yaml | 48 ++++++++++++++++++++++---- 6 files changed, 83 insertions(+), 16 deletions(-) diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 06f6a7d7..05bdc4e3 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1001,7 +1001,8 @@ 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 run defaults. Optional executionConfigId, vmImage, model and runScopes override those defaults; 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",{ diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index a8d4b590..91a8514d 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -117,12 +117,20 @@ export type ManualInvocationInput = z.infer; 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, + model: jobInputSchema.shape.model, + runScopes: jobInputSchema.shape.runScopes, 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, diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index ce1e35a8..003f8dec 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,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"; @@ -1066,13 +1066,28 @@ export class ApiService { 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 defaults = project.runDefaults; + const selectedConfigId = input.executionConfigId ?? defaults.executionConfigId; + const model = input.model ?? defaults.model ?? ""; + const config = await this.resolveRunDefaults({ ...defaults, executionConfigId: selectedConfigId, model }); + if (input.vmImage) config.image = input.vmImage; + if (input.script) { + if (config.agentKind === "Amp") throw new ServiceError(400, "invalid_request", "Script runs require a VM execution provider."); + config.executionType = "code"; + (config as Record).script = input.script; + } + const callerScopes = this.auth.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; + const requestedScopes = input.runScopes ?? callerScopes; + if (requestedScopes.some(scope => !this.auth.scopes.includes(scope))) + throw new ServiceError(403, "forbidden", "Requested run permissions exceed this client's effective Factorize access."); + config.runScopes = requestedScopes; 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 diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 1655126a..b007b17f 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. Optional executionConfigId, vmImage, model, and runScopes override the project defaults; 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/docs/openapi.yaml b/packages/docs/openapi.yaml index 30d714fc..56a7d301 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -15803,7 +15803,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 run defaults. Optional executionConfigId, vmImage, model and runScopes override those defaults; 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 +15853,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 +15878,10 @@ paths: type: string minLength: 1 maxLength: 50000 + script: + type: string + minLength: 1 + maxLength: 200000 skill: type: string minLength: 1 @@ -15884,6 +15890,36 @@ 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})?))?$ + model: + type: string + maxLength: 120 + 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 inputs: type: object propertyNames: @@ -15893,8 +15929,6 @@ paths: type: string minLength: 1 maxLength: 200 - required: - - prompt additionalProperties: false get: summary: List runs From 6e0d623f1bc84dfc4071bd0af486574b2b96f83e Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:14:06 +0000 Subject: [PATCH 2/9] Add direct-run defaults and integration bounds --- packages/api-client/src/schema.d.ts | 146 ++++++++- .../api/migrations/0066_user_run_defaults.sql | 9 + packages/api/src/agent-api.ts | 1 + packages/api/src/api-contract.ts | 6 +- packages/api/src/flow-schemas.ts | 2 + packages/api/src/flow-service.ts | 59 +++- packages/api/src/postgres/schema.ts | 1 + packages/api/src/protected-api.ts | 2 +- .../test/direct-run-defaults.postgres.test.ts | 69 ++++ packages/docs/openapi.yaml | 308 +++++++++++++++++- 10 files changed, 585 insertions(+), 18 deletions(-) create mode 100644 packages/api/migrations/0066_user_run_defaults.sql create mode 100644 packages/api/test/direct-run-defaults.postgres.test.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index b5114302..c9b13f35 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; @@ -9671,9 +9701,16 @@ export interface operations { "application/json": { /** Format: uuid */ projectId?: string; - prompt: string; + prompt?: string; + script?: string; skill?: string; name?: string; + executionConfigId?: string; + vmImage?: string; + model?: 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")[]; + integrationIds?: string[]; inputs?: { [key: string]: unknown; }; @@ -9776,6 +9813,109 @@ 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; + 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; + 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; + 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..bbeeabeb 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) && config.agentIntegrationIds.includes(row.id)) return true; 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 05bdc4e3..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, @@ -1002,13 +1002,15 @@ export const API_ROUTES: RouteContract[] = [ ), route("POST","/api/v1/runs","runs:start",{ 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 run defaults. Optional executionConfigId, vmImage, model and runScopes override those defaults; runScopes is limited to the caller's effective permissions.", + 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 91a8514d..48ee98c1 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -125,6 +125,7 @@ export const startRunInput = z.object({ vmImage: jobInputSchema.shape.vmImage, model: jobInputSchema.shape.model, runScopes: jobInputSchema.shape.runScopes, + 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().refine(value => Number(Boolean(value.prompt)) + Number(Boolean(value.script)) === 1, { @@ -142,3 +143,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 003f8dec..12ecc84e 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,scopeSchema } 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"; @@ -979,6 +979,20 @@ export class ApiService { return input; } + 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) { await this.validateExecutionOptions( input.executionConfigId, @@ -1064,12 +1078,35 @@ 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 defaults = project.runDefaults; - const selectedConfigId = input.executionConfigId ?? defaults.executionConfigId; - const model = input.model ?? defaults.model ?? ""; - const config = await this.resolveRunDefaults({ ...defaults, executionConfigId: selectedConfigId, model }); + 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 baseDefaults = defaults.executionConfigId ? defaults : { ...defaults, executionConfigId: input.executionConfigId, model: "", effort: "", tags: [], runScopes: [], capacity: 4 }; + const accessible = (await this.agentApi().reflection()).integrations.filter(item => item.access === "granted"); + const accessibleById = new Map(accessible.map(item => [item.id, item])); + const integrationIds = input.integrationIds ?? accessible.map(item => item.id); + if (integrationIds.some(id => !accessibleById.has(id))) + throw new ServiceError(403, "forbidden", "Requested integrations exceed this client's effective integration access."); + const selectedIntegrations = integrationIds.map(id => accessibleById.get(id)!); + const selectedConfigId = input.executionConfigId ?? baseDefaults.executionConfigId; + const model = input.model ?? baseDefaults.model ?? ""; + const selected = { + ...baseDefaults, + capacity: baseDefaults.capacity ?? 4, + executionConfigId: selectedConfigId, + model, + portableIntegrationIds: selectedIntegrations.filter(item => item.kind === "bearer").map(item => item.credentialId), + githubInstallationIds: selectedIntegrations.filter(item => item.kind === "github").map(item => Number(item.credentialId)), + linearConnectionId: selectedIntegrations.some(item => item.kind === "linear") ? "linear" : undefined, + xConnectionIds: selectedIntegrations.filter(item => item.kind === "x").map(item => item.credentialId), + agentIntegrationIds: integrationIds, + ...(baseDefaults.modelAccountId && selectedIntegrations.some(item => item.kind === "model" && item.credentialId === baseDefaults.modelAccountId) ? {} : {modelAccountId: undefined}), + ...(selectedIntegrations.some(item => item.kind === "model") && baseDefaults.modelAccountId && selectedIntegrations.some(item => item.kind === "model" && item.credentialId === baseDefaults.modelAccountId) ? {modelAccess:"portable" as const} : {modelAccess:"native" as const}), + }; + const config = await this.resolveRunDefaults(selected); + (config as Record).agentIntegrationIds = integrationIds; if (input.vmImage) config.image = input.vmImage; if (input.script) { if (config.agentKind === "Amp") throw new ServiceError(400, "invalid_request", "Script runs require a VM execution provider."); @@ -1099,10 +1136,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) @@ -1111,6 +1145,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 b007b17f..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 with exactly one literal prompt or shell script. Optional executionConfigId, vmImage, model, and runScopes override the project defaults; omitted runScopes inherit this MCP client's effective Factorize permissions. 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/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts new file mode 100644 index 00000000..430ced4a --- /dev/null +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -0,0 +1,69 @@ +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"; + +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 integrationId = crypto.randomUUID(), credentialId = crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1)", [f.tenantId]); + 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,'ciphertext')", [f.tenantId, credentialId]); + await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) VALUES($1,$2,'bearer',$3,'Direct test',true,'baseline')", [f.tenantId, integrationId, credentialId]); + 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"] }); + 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([integrationId]); + + 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 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; + delete 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"] }); + 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("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"] }); + 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"] }); + await expect(service.startRun({ projectId: f.projectId, prompt: "invalid model", model: "other-model", integrationIds: [], idempotencyKey: "invalid-model" })).rejects.toMatchObject({ status: 400, code: "invalid_request" }); + 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/docs/openapi.yaml b/packages/docs/openapi.yaml index 56a7d301..fd68cd5b 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -15805,7 +15805,7 @@ paths: post: 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 run defaults. Optional executionConfigId, vmImage, model and runScopes override those defaults; runScopes is limited to the caller's effective permissions. + 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. @@ -15920,6 +15920,13 @@ paths: - 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: @@ -16295,6 +16302,305 @@ 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 + 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 + 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 + 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 From cd433206d77ead300b8547c0b20e79fb058e1f0a Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:18:05 +0000 Subject: [PATCH 3/9] Fix direct-run integration test fixture --- .../api/test/direct-run-defaults.postgres.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts index 430ced4a..28a535bc 100644 --- a/packages/api/test/direct-run-defaults.postgres.test.ts +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -2,6 +2,8 @@ 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() })); @@ -13,10 +15,13 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 it("uses user defaults when the project has none and inherits or narrows effective integrations", async () => { const f = await loadingFixture(url!); try { - const integrationId = crypto.randomUUID(), credentialId = crypto.randomUUID(); + const credentialId = crypto.randomUUID(); await f.db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1)", [f.tenantId]); - 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,'ciphertext')", [f.tenantId, credentialId]); - await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) VALUES($1,$2,'bearer',$3,'Direct test',true,'baseline')", [f.tenantId, integrationId, credentialId]); + 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"] }); @@ -24,7 +29,7 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 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([integrationId]); + 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; From 1e564c5fc2e9cbdc9a794ab39e422e12905289f9 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:22:11 +0000 Subject: [PATCH 4/9] Use effective MCP access for direct runs --- packages/api/src/flow-service.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 12ecc84e..d7e68d24 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1084,7 +1084,9 @@ export class ApiService { if (!defaults.executionConfigId && !input.executionConfigId) throw new ServiceError(409, "run_defaults_required", "Configure project or user VM run defaults first."); const baseDefaults = defaults.executionConfigId ? defaults : { ...defaults, executionConfigId: input.executionConfigId, model: "", effort: "", tags: [], runScopes: [], capacity: 4 }; - const accessible = (await this.agentApi().reflection()).integrations.filter(item => item.access === "granted"); + const callerAccess = await this.agentApi().reflection(); + const callerScopes = callerAccess.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; + const accessible = callerAccess.integrations.filter(item => item.access === "granted"); const accessibleById = new Map(accessible.map(item => [item.id, item])); const integrationIds = input.integrationIds ?? accessible.map(item => item.id); if (integrationIds.some(id => !accessibleById.has(id))) @@ -1113,9 +1115,8 @@ export class ApiService { config.executionType = "code"; (config as Record).script = input.script; } - const callerScopes = this.auth.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; const requestedScopes = input.runScopes ?? callerScopes; - if (requestedScopes.some(scope => !this.auth.scopes.includes(scope))) + if (requestedScopes.some(scope => !callerScopes.includes(scope))) throw new ServiceError(403, "forbidden", "Requested run permissions exceed this client's effective Factorize access."); config.runScopes = requestedScopes; const skill = input.skill ? await this.skills().get(input.skill) : null; From c457741cba9baa0e39406600238a2ee07a3daba7 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:25:45 +0000 Subject: [PATCH 5/9] Keep child run scopes empty by default --- packages/api/src/flow-service.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index d7e68d24..b712454b 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1085,7 +1085,9 @@ export class ApiService { throw new ServiceError(409, "run_defaults_required", "Configure project or user VM run defaults first."); const baseDefaults = defaults.executionConfigId ? defaults : { ...defaults, executionConfigId: input.executionConfigId, model: "", effort: "", tags: [], runScopes: [], capacity: 4 }; const callerAccess = await this.agentApi().reflection(); - const callerScopes = callerAccess.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; + // A parent run may start a child, but does not delegate its own API scopes. + // MCP OAuth clients inherit their currently effective scopes instead. + const callerScopes = auth.runId ? [] : callerAccess.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; const accessible = callerAccess.integrations.filter(item => item.access === "granted"); const accessibleById = new Map(accessible.map(item => [item.id, item])); const integrationIds = input.integrationIds ?? accessible.map(item => item.id); From 4c35d48a837f2a5424d5eaf2eb363a94346b75b5 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:28:50 +0000 Subject: [PATCH 6/9] Test effective direct-run permission inheritance --- .../test/direct-run-defaults.postgres.test.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts index 28a535bc..09714dff 100644 --- a/packages/api/test/direct-run-defaults.postgres.test.ts +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -58,6 +58,26 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 } 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 { From ed72e8aa6dfc32961a7358a1f741515042db6fef Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:37:33 +0000 Subject: [PATCH 7/9] Resolve direct-run provider and access settings before VM launch --- packages/api-client/src/schema.d.ts | 52 ++++++++- packages/api/src/agent-api.ts | 2 +- packages/api/src/flow-schemas.ts | 6 +- packages/api/src/flow-service.ts | 100 ++++++++++-------- .../test/direct-run-defaults.postgres.test.ts | 17 ++- packages/docs/openapi.yaml | 72 ++++++++++++- scripts/background-run-acceptance.mjs | 9 ++ 7 files changed, 203 insertions(+), 55 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index c9b13f35..c154183c 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -6803,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; @@ -6863,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; @@ -6919,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; @@ -6981,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; @@ -9707,8 +9727,13 @@ export interface operations { name?: string; executionConfigId?: string; vmImage?: string; + /** + * @description Agent harness used for the selected model. + * @enum {string} + */ + modelProvider?: "codex" | "claude" | "pi"; model?: 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. */ + /** @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?: { @@ -9759,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; @@ -9785,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; @@ -9830,6 +9865,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?: unknown; @@ -9866,6 +9906,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; @@ -9890,6 +9935,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?: unknown; diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index bbeeabeb..5fba33f8 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -96,7 +96,7 @@ export class AgentApiService { return {id: row.id, kind, config, policy: row}; } private selected(row: AgentIntegration, config: Record) { - if (Array.isArray(config.agentIntegrationIds) && config.agentIntegrationIds.includes(row.id)) return true; + 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/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 48ee98c1..00b4766c 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -115,6 +115,7 @@ 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()).optional(), @@ -123,8 +124,9 @@ export const startRunInput = z.object({ 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, + 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(), @@ -135,7 +137,7 @@ export const startRunInput = z.object({ 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, diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index b712454b..28c3a894 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -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."); @@ -993,24 +995,28 @@ export class ApiService { return result.rows[0].run_defaults; } - private async resolveRunDefaults(input: z.infer) { - await this.validateExecutionOptions( + 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 ?? [], @@ -1083,44 +1089,48 @@ export class ApiService { 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 baseDefaults = defaults.executionConfigId ? defaults : { ...defaults, executionConfigId: input.executionConfigId, model: "", effort: "", tags: [], runScopes: [], capacity: 4 }; - const callerAccess = await this.agentApi().reflection(); - // A parent run may start a child, but does not delegate its own API scopes. - // MCP OAuth clients inherit their currently effective scopes instead. - const callerScopes = auth.runId ? [] : callerAccess.scopes.filter(scope => scopeSchema.safeParse(scope).success) as z.infer[]; - const accessible = callerAccess.integrations.filter(item => item.access === "granted"); - const accessibleById = new Map(accessible.map(item => [item.id, item])); - const integrationIds = input.integrationIds ?? accessible.map(item => item.id); - if (integrationIds.some(id => !accessibleById.has(id))) - throw new ServiceError(403, "forbidden", "Requested integrations exceed this client's effective integration access."); - const selectedIntegrations = integrationIds.map(id => accessibleById.get(id)!); - const selectedConfigId = input.executionConfigId ?? baseDefaults.executionConfigId; - const model = input.model ?? baseDefaults.model ?? ""; - const selected = { - ...baseDefaults, - capacity: baseDefaults.capacity ?? 4, - executionConfigId: selectedConfigId, - model, - portableIntegrationIds: selectedIntegrations.filter(item => item.kind === "bearer").map(item => item.credentialId), - githubInstallationIds: selectedIntegrations.filter(item => item.kind === "github").map(item => Number(item.credentialId)), - linearConnectionId: selectedIntegrations.some(item => item.kind === "linear") ? "linear" : undefined, - xConnectionIds: selectedIntegrations.filter(item => item.kind === "x").map(item => item.credentialId), - agentIntegrationIds: integrationIds, - ...(baseDefaults.modelAccountId && selectedIntegrations.some(item => item.kind === "model" && item.credentialId === baseDefaults.modelAccountId) ? {} : {modelAccountId: undefined}), - ...(selectedIntegrations.some(item => item.kind === "model") && baseDefaults.modelAccountId && selectedIntegrations.some(item => item.kind === "model" && item.credentialId === baseDefaults.modelAccountId) ? {modelAccess:"portable" as const} : {modelAccess:"native" as const}), - }; - const config = await this.resolveRunDefaults(selected); - (config as Record).agentIntegrationIds = integrationIds; - if (input.vmImage) config.image = input.vmImage; - if (input.script) { - if (config.agentKind === "Amp") throw new ServiceError(400, "invalid_request", "Script runs require a VM execution provider."); - config.executionType = "code"; - (config as Record).script = input.script; - } - const requestedScopes = input.runScopes ?? callerScopes; - if (requestedScopes.some(scope => !callerScopes.includes(scope))) + 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."); - config.runScopes = requestedScopes; + + 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 = !isAgentClient && 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"); diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts index 09714dff..b1e8e3b9 100644 --- a/packages/api/test/direct-run-defaults.postgres.test.ts +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -24,7 +24,7 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 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"] }); + 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"); @@ -48,9 +48,9 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 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; - delete projectDefaults.model; + 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"] }); + 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"); @@ -81,10 +81,17 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 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"] }); + 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"] }); + 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"); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index fd68cd5b..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 @@ -15897,11 +15925,18 @@ paths: 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 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. + description: Factorize application permissions to grant. Omission inherits effective client permissions and an empty list grants none. maxItems: 13 type: array items: @@ -16108,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 @@ -16228,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 @@ -16317,6 +16366,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 @@ -16427,6 +16483,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 @@ -16532,6 +16595,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 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 }); } From 0458f1e629423782bb0d707fd3666de77765f9e4 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:38:29 +0000 Subject: [PATCH 8/9] Exercise a jobless script through VM scheduling and finalization --- packages/api/src/flow-service.ts | 2 +- .../test/direct-run-defaults.postgres.test.ts | 5 +++++ packages/api/test/docker-code-job.e2e.test.ts | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 28c3a894..42ac9684 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1106,7 +1106,7 @@ export class ApiService { if (!integration) throw new ServiceError(403, "forbidden", "Requested integrations exceed this client's effective integration access."); return integration; }); - const inheritConfigured = !isAgentClient && input.integrationIds === undefined; + 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)), diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts index b1e8e3b9..a012306f 100644 --- a/packages/api/test/direct-run-defaults.postgres.test.ts +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -37,6 +37,11 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 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); diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index 4955c709..82146bba 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -122,6 +122,23 @@ JS expect(docker("ps","-aq","--filter",`id=${id}`)).toBe(""); const artifacts=(await db.pool.query("SELECT object_key FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2",[tenantId,runId])).rows;expect(artifacts.length).toBeGreaterThan(0); for(const artifact of artifacts){const object=await env.RUN_ARTIFACTS!.get(artifact.object_key);expect(await object!.text()).not.toContain(secret);} + + const direct = await json("/runs", "POST", { + projectId: project.id, executionConfigId: "docker", integrationIds: [], runScopes: [], + script: `#!/bin/bash +set -eu +printf '%s' '{"status":"succeeded","outputs":{"mode":"direct"}}' > "$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 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).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); From d0282512a8008f528ae73c41715268d8277cc961 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 00:57:02 +0000 Subject: [PATCH 9/9] Bind each test guest identity to its own provisioned machine --- packages/api/test/docker-code-job.e2e.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index 82146bba..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_R const directDeadline = Date.now() + 60_000; do { await runner.tick(); - directRun = (await db.pool.query("SELECT job_id,state,job_result FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId,direct.runId])).rows[0]; + 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).toMatchObject({job_id: null, state: "succeeded", job_result: {outputs: {mode: "direct"}}}); + 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);