From 50a7083b69619c0ca06c14a60388cbcd1334613c Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 5 Nov 2026 21:37:40 +0000 Subject: [PATCH 1/3] feat: add code jobs alongside agent jobs --- packages/api-client/src/schema.d.ts | 63 +++++++- packages/api/src/exe-vm-backend.ts | 15 +- packages/api/src/execution.ts | 1 + packages/api/src/flow-schemas.ts | 11 +- packages/api/src/flow-service.ts | 30 ++-- packages/api/src/job-contracts.ts | 6 +- packages/api/src/job-domain.ts | 4 + packages/api/src/postgres/job-repository.ts | 6 +- .../src/postgres/job-summary-repository.ts | 6 +- .../api/src/postgres/run-query-repository.ts | 6 +- packages/api/src/postgres/run-scheduler.ts | 37 +++-- packages/api/src/run-read-contracts.ts | 5 +- packages/api/test/api-boundary.test.ts | 2 +- packages/api/test/api-contract.test.ts | 7 + packages/api/test/execution-backend.test.ts | 12 ++ .../api/test/job-lifecycle.postgres.test.ts | 11 ++ .../app/src/features/jobs/editor-state.ts | 7 +- packages/app/src/features/jobs/editor.tsx | 13 +- packages/app/src/features/jobs/header.tsx | 4 +- packages/app/src/features/jobs/list.tsx | 2 +- packages/app/src/features/runs/history.tsx | 4 +- packages/app/src/features/runs/provenance.tsx | 4 +- packages/docs/concepts.mdx | 16 ++ packages/docs/llms-full.txt | 16 ++ packages/docs/openapi.yaml | 141 +++++++++++++++++- 25 files changed, 357 insertions(+), 72 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 90791ea2..f0bc8433 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1810,6 +1810,8 @@ export interface components { workspace_name: string; agent_kind: string; /** @enum {string} */ + execution_type: "agent" | "code"; + /** @enum {string} */ state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; provider: string; backend_kind: string; @@ -1856,6 +1858,8 @@ export interface components { workspace_name: string; agent_kind: string; /** @enum {string} */ + execution_type: "agent" | "code"; + /** @enum {string} */ state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; provider: string; backend_kind: string; @@ -2029,6 +2033,11 @@ export interface components { agent_name: string; workspace_name: string; agent_kind: string; + /** + * @default agent + * @enum {string} + */ + execution_type: "agent" | "code"; /** @enum {string} */ state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; provider: string; @@ -2090,6 +2099,11 @@ export interface components { vm_cleanup_attempt: number; cleanup_next_at: string | null; vm_cleanup_complete: boolean; + /** @default null */ + execution_script: string | null; + execution_configuration: { + [key: string]: unknown; + }; prompt: string; context: { [key: string]: unknown; @@ -2186,7 +2200,11 @@ export interface components { projectId?: string; name: string; slug: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + /** @default */ promptTemplate: string; + script?: string; runNameTemplate?: string; /** @default 1 */ concurrencyLimit: number; @@ -4316,6 +4334,8 @@ export interface operations { model: string; effort: string; agentKind: string; + /** @enum {string} */ + executionType: "agent" | "code"; concurrencyLimit: number; runningCount: number; lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; @@ -4950,7 +4970,10 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; promptTemplate: string; + script?: string; runNameTemplate: string; tags?: string[]; model: string; @@ -4961,6 +4984,9 @@ export interface operations { cwd?: string; agentKind: string; image?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; }; executionConfigId: string; agentKind: string; @@ -5133,6 +5159,8 @@ export interface operations { tags: string[]; /** @enum {string} */ agentKind: "codex" | "claude" | "pi"; + /** @enum {string} */ + executionType?: "agent" | "code"; }; }; }; @@ -5230,7 +5258,10 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; promptTemplate: string; + script?: string; runNameTemplate: string; tags?: string[]; model: string; @@ -5241,6 +5272,9 @@ export interface operations { cwd?: string; agentKind: string; image?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; }; executionConfigId: string; agentKind: string; @@ -5424,7 +5458,10 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; promptTemplate: string; + script?: string; runNameTemplate: string; tags?: string[]; model: string; @@ -5435,6 +5472,9 @@ export interface operations { cwd?: string; agentKind: string; image?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; }; executionConfigId: string; agentKind: string; @@ -5900,7 +5940,10 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; promptTemplate: string; + script?: string; runNameTemplate: string; tags?: string[]; model: string; @@ -5911,6 +5954,9 @@ export interface operations { cwd?: string; agentKind: string; image?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; }; executionConfigId: string; agentKind: string; @@ -6083,7 +6129,11 @@ export interface operations { projectId?: string; name: string; slug: string; - promptTemplate: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + /** @default */ + promptTemplate?: string; + script?: string; runNameTemplate?: string; /** @default 1 */ concurrencyLimit?: number; @@ -6210,7 +6260,10 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; promptTemplate: string; + script?: string; runNameTemplate: string; tags?: string[]; model: string; @@ -6221,6 +6274,9 @@ export interface operations { cwd?: string; agentKind: string; image?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; }; executionConfigId: string; agentKind: string; @@ -6590,6 +6646,11 @@ export interface operations { project_name?: string; /** @enum {string} */ state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped"; + /** + * @default agent + * @enum {string} + */ + execution_type: "agent" | "code"; run_name: string; job_name: string; destination_url: string | null; diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 35df4c95..1f9f32cb 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -110,7 +110,7 @@ export class ExeVmBackend implements ExecutionBackend { } } - async verifyImage(verificationId: string, image: string, agentKind: "codex" | "claude" | "pi", progress: (phase: string) => Promise = async () => {}): Promise { + async verifyImage(verificationId: string, image: string, agentKind: "codex" | "claude" | "pi", progress: (phase: string) => Promise = async () => {}, executionType: "agent" | "code" = "agent"): Promise { const vm = vmNameFor(`verify-${verificationId}`); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const command = `new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)}${tags ? ` ${tags}` : ""} --image=${shellAtom(image)}`; @@ -139,9 +139,9 @@ export class ExeVmBackend implements ExecutionBackend { for (let attempt = 1; (!ssh || !ssh.ok) && attempt < 6; attempt++) ssh = await this.api(`ssh ${shellAtom(vm)} ${shellAtom("true")}`).catch(() => null); if (!ssh?.ok) throw new ExeIntegrationError(`ssh: VM was created from the image, but SSH access failed (${ssh?.status ?? "timeout"}). Ensure the image boots an exe.dev-compatible system with SSH enabled.`); await progress("checking_agent"); - const check = `command -v ${shellAtom(agentKind)} >/dev/null 2>&1 && command -v curl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1`; + const check = executionType === "code" ? "command -v bash >/dev/null 2>&1 && command -v curl >/dev/null 2>&1" : `command -v ${shellAtom(agentKind)} >/dev/null 2>&1 && command -v curl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1`; const agent = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(check)}`).catch(() => null); - if (!agent?.ok) throw new ExeIntegrationError(`agent: SSH works, but the selected ${agentKind} harness prerequisites are missing. Use an image with ${agentKind}, curl, and jq installed.`); + if (!agent?.ok) throw new ExeIntegrationError(executionType === "code" ? "agent: SSH works, but bash and curl prerequisites are missing. Use an exe.dev-compatible image with bash and curl installed." : `agent: SSH works, but the selected ${agentKind} harness prerequisites are missing. Use an image with ${agentKind}, curl, and jq installed.`); } finally { await progress("cleaning_up"); const removed = await this.deleteVm(vm); @@ -151,8 +151,7 @@ export class ExeVmBackend implements ExecutionBackend { async launch(request: LaunchRequest): Promise { const connection = this.connection as ExeRunConnection; - if (!connection.agentKind) throw new Error("The job is missing its agent configuration"); - if (!request.harness) throw new Error("The run is missing its agent harness launch plan"); + if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan"); if (request.traceSources) validateTraceSources(request.traceSources); const vm = vmNameFor(request.runId); const handle: RunHandle = { backendKind: this.kind, id: vm }; @@ -189,15 +188,15 @@ export class ExeVmBackend implements ExecutionBackend { } } - const prompt = base64(request.prompt), output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; + const prompt = base64(request.prompt), code = request.code, output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; const work = [ "set -eu", "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), - `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, "sudo install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job", - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, + ...(code ? [`printf '%s' ${shellAtom(base64(code.script))} | base64 -d > /tmp/factorize-code-job.sh`, `printf '%s' ${shellAtom(base64(JSON.stringify(code.context)))} | base64 -d > /home/exedev/.factorize-job/input.json`, "sudo chown exedev:exedev /home/exedev/.factorize-job/input.json"] : [`printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`]), + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=${code ? "/dev/null" : "file:/tmp/factorize-prompt.md"} --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr ${code ? "env FACTORIZE_RESULT_PATH=/home/exedev/.factorize-job/results.json FACTORIZE_INPUT_PATH=/home/exedev/.factorize-job/input.json bash /tmp/factorize-code-job.sh" : harnessCommand(request.harness!)}; fi`, "echo started", ].join("; "); if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") { diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 05427a47..5b220870 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -18,6 +18,7 @@ export interface LaunchRequest { runProxy?: { targetOrigin: string; credential: string }; traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; + code?: { script: string; context: Record }; } /** Opaque to orchestration. Only the backend that created it may interpret id. */ diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 181bc8c1..631305eb 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -62,7 +62,9 @@ export const jobInputSchema = z.object({ projectId: z.guid().optional(), name: z.string().trim().min(1).max(120), slug: z.string().regex(/^[a-z][a-z0-9_-]{0,29}$/), - promptTemplate: z.string().min(1).max(50_000), + executionType: z.enum(["agent", "code"]).optional(), + promptTemplate: z.string().max(50_000).default(""), + script: z.string().max(50_000).optional(), runNameTemplate: z.string().max(500).optional(), concurrencyLimit: z.number().int().min(1).max(50).default(1), executionConfigId: z.string().min(1), @@ -72,12 +74,15 @@ export const jobInputSchema = z.object({ effort: z.string().trim().max(40).optional(), triggers: z.array(triggerSchema).max(50).default([]), skillIds: z.array(z.guid()).max(50).optional(), -}).strict(); +}).strict().superRefine((value, context) => { + if (value.executionType !== "code" && !value.promptTemplate?.trim()) context.addIssue({ code: "custom", path: ["promptTemplate"], message: "Agent jobs require a prompt template." }); + if (value.executionType === "code" && !value.script?.trim()) context.addIssue({ code: "custom", path: ["script"], message: "Code jobs require a script." }); +}); export const vmImageVerificationInput = z.object({ connectionId: z.string().min(1).max(200), image: publicVmImage(false), tags: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)).max(20), - agentKind: z.enum(["codex", "claude", "pi"]), + agentKind: z.enum(["codex", "claude", "pi"]), executionType: z.enum(["agent", "code"]).optional(), }).strict(); export const vmImageVerificationResponse = z.object({ id: z.guid(), status: z.enum(["queued", "creating", "checking_ssh", "checking_agent", "cleaning_up", "succeeded", "failed", "cleanup_failed"]), phase: z.string(), errorKind: z.string().nullable(), error: z.string().nullable(), createdAt: z.string(), updatedAt: z.string() }); export const jobIdSchema = z.object({ jobId: z.string().min(1) }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 990ed3cc..151d4332 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -129,7 +129,7 @@ export class ApiService { private async presentJob(job: Job, loadedStats?: { running_count: string; last_run_state: string | null }) { const stats = loadedStats ?? (await this.jobStatistics([job.id])).get(job.id); const runningCount = Number(stats?.running_count ?? 0); - return publicValue(jobResponse, { ...job, skills: (job.selectedSkills ?? []).map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, position: skill.position })), triggers: job.triggers.map(trigger => ({ ...trigger, config: trigger.kind === "webhook" ? { ...trigger.config, ...(trigger.config.signingSecret || trigger.config.secret ? { secretConfigured: true } : {}), ...(trigger.config.provider === "cloudflareTail" ? { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(job.id)}` } : {}) } : trigger.config })), runNameTemplate: job.runNameTemplate ?? "", executionConfigId: job.executionConfig.targetId ?? `${job.executionConfig.agentKind === "Amp" ? "amp:" : ""}${job.executionConfig.connectionId}`, agentKind: job.executionConfig.agentKind, runningCount, currentRuns: runningCount, maxConcurrency: job.concurrencyLimit, lastRunState: stats?.last_run_state ?? null }); + return publicValue(jobResponse, { ...job, executionType: job.executionType ?? "agent", skills: (job.selectedSkills ?? []).map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, position: skill.position })), triggers: job.triggers.map(trigger => ({ ...trigger, config: trigger.kind === "webhook" ? { ...trigger.config, ...(trigger.config.signingSecret || trigger.config.secret ? { secretConfigured: true } : {}), ...(trigger.config.provider === "cloudflareTail" ? { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(job.id)}` } : {}) } : trigger.config })), runNameTemplate: job.runNameTemplate ?? "", executionConfigId: job.executionConfig.targetId ?? `${job.executionConfig.agentKind === "Amp" ? "amp:" : ""}${job.executionConfig.connectionId}`, agentKind: job.executionConfig.agentKind, runningCount, currentRuns: runningCount, maxConcurrency: job.concurrencyLimit, lastRunState: stats?.last_run_state ?? null }); } async listSkills(query: { q: string; limit: number; cursor?: string }) { await this.authorize("skills:read"); return publicValue(skillPage, await this.skills().list(query.q, query.limit, query.cursor)); } async getSkill(id: string) { await this.authorize("skills:read"); const value = await this.skills().get(id); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } @@ -207,11 +207,11 @@ export class ApiService { return publicValue(fullRunResponse, JSON.parse(JSON.stringify({ id: run.id, tenant_id: run.tenant_id, job_id: run.job_id, invocation_id: run.invocation_id, execution_handle: run.execution_handle ? { backendKind: run.execution_handle.backendKind, id: run.execution_handle.id } : null, provider: run.provider, issue_id: run.issue_id, issue_url: run.issue_url, issue_title: run.issue_title, - run_name: run.run_name, agent_name: run.agent_name, workspace_name: run.workspace_name, agent_kind: run.agent_kind, + run_name: run.run_name, agent_name: run.agent_name, workspace_name: run.workspace_name, agent_kind: run.agent_kind, execution_type: run.execution_type ?? run.execution_config?.executionType ?? "agent", state: run.state, failure_source: run.failure_source ?? null, agent_error: agentError, execution_backend_kind: run.execution_backend_kind, backend_kind: run.backend_kind, execution_capabilities: run.execution_capabilities, capabilities: run.capabilities, destination_url: run.destination_url, artifact_state: run.artifact_state, artifact_error: run.artifact_error, - claim_released: run.claim_released, vm_cleanup_attempt: run.vm_cleanup_attempt, cleanup_next_at: run.cleanup_next_at, vm_cleanup_complete: run.vm_cleanup_complete, + claim_released: run.claim_released, vm_cleanup_attempt: run.vm_cleanup_attempt, cleanup_next_at: run.cleanup_next_at, vm_cleanup_complete: run.vm_cleanup_complete, execution_script: typeof run.execution_config?.script === "string" ? run.execution_config.script : null, execution_configuration: run.execution_config, created_at: run.created_at, updated_at: run.updated_at, started_at: run.started_at, job_name: run.job_name, prompt: run.prompt, context: run.context, occurrence: run.occurrence, invocation: run.invocation, invocation_source: run.invocation_source, invocation_claim_key: run.invocation_claim_key, invocation_trigger_id: run.invocation_trigger_id, invocation_created_at: run.invocation_created_at, @@ -298,20 +298,24 @@ export class ApiService { async createJob(input: JobInput) { await this.authorize("jobs:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); const vmImage = input.vmImage ? canonicalizeVmImage(input.vmImage) : input.vmImage; - await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); + const executionType = input.executionType ?? "agent"; + if (executionType === "code" && input.executionConfigId.startsWith("amp:")) throw new ServiceError(400, "invalid_request", "Code jobs require an exe.dev integration."); + if (executionType !== "code") await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); const projectId = input.projectId ?? await this.projects().defaultProjectId(); - const selectedSkills = input.skillIds ? await this.skillSelections(input.skillIds) : []; - const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...await this.executionConfig(input.executionConfigId), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, selectedSkills, createdAt: timestamp, updatedAt: timestamp }; + const selectedSkills = executionType === "code" ? [] : input.skillIds ? await this.skillSelections(input.skillIds) : []; + const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...await this.executionConfig(input.executionConfigId), executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, selectedSkills, createdAt: timestamp, updatedAt: timestamp }; try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; } } async updateJob(jobId: string, input: JobInput & { expectedUpdatedAt?: string }) { await this.authorize("jobs:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); const vmImage = input.vmImage ? canonicalizeVmImage(input.vmImage) : input.vmImage; - await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); + const executionType = input.executionType ?? current.executionType ?? "agent"; + if (executionType === "code" && input.executionConfigId.startsWith("amp:")) throw new ServiceError(400, "invalid_request", "Code jobs require an exe.dev integration."); + if (executionType !== "code") await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); - const selectedSkills = input.skillIds === undefined ? current.selectedSkills : await this.skillSelections(input.skillIds); - const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: { ...await this.executionConfig(input.executionConfigId), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, triggers, selectedSkills, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); + const selectedSkills = executionType === "code" ? [] : input.skillIds === undefined ? current.selectedSkills : await this.skillSelections(input.skillIds); + const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: { ...await this.executionConfig(input.executionConfigId), executionType, ...(input.script ? { script: input.script } : {}), ...(vmImage ? { image: vmImage } : {}) }, concurrencyLimit: input.concurrencyLimit, triggers, selectedSkills, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); await this.wakeScheduler(); return this.presentJob(updated); } @@ -319,10 +323,10 @@ export class ApiService { await this.authorize("jobs:write"); const value = vmImageVerificationInput.parse(input), connection = await this.connections().get(`exe:${value.connectionId}`); if (!connection) throw new ServiceError(404, "not_found", "exe.dev integration not found"); - if (connection.agentKind !== value.agentKind) throw new ServiceError(400, "invalid_request", "The selected agent does not match this exe.dev integration."); + if (value.executionType !== "code" && connection.agentKind !== value.agentKind) throw new ServiceError(400, "invalid_request", "The selected agent does not match this exe.dev integration."); const allowedTags = new Set(selectableExeTags(connection)); if (value.tags.some(tag => !allowedTags.has(tag))) throw new ServiceError(400, "invalid_request", "VM tags must be selected from the available exe.dev labels."); - const id = crypto.randomUUID(), db = databaseFor(this.env), config = { connectionId: value.connectionId, image: value.image, tags: value.tags, agentKind: value.agentKind }; + const id = crypto.randomUUID(), db = databaseFor(this.env), config = { connectionId: value.connectionId, image: value.image, tags: value.tags, agentKind: value.agentKind, executionType: value.executionType ?? "agent" }; await db.pool.query("INSERT INTO app.vm_image_verifications(tenant_id,id,status,phase,config) VALUES ($1,$2,'queued','queued',$3)", [this.auth.tenantId, id, config]); const task = this.runVmImageVerification(id, connection, value); if (this.ctx) this.ctx.waitUntil(task); else void task.catch(error => console.error("VM image verification failed", error)); @@ -335,8 +339,8 @@ export class ApiService { const backend = new ExeVmBackend({ ...connection, tags: input.tags }); try { await update("creating"); - await backend.verifyImage(id, input.image, input.agentKind, phase => update(phase)); - await update("succeeded", "Verification passed. Image pull, SSH, and agent prerequisites worked at this time."); + await backend.verifyImage(id, input.image, input.agentKind, phase => update(phase), input.executionType ?? "agent"); + await update("succeeded", input.executionType === "code" ? "Verification passed. Image pull, SSH, and code prerequisites worked at this time." : "Verification passed. Image pull, SSH, and agent prerequisites worked at this time."); } catch (cause) { const message = cause instanceof Error ? cause.message : "Image verification failed."; const cleanup = message.startsWith("cleanup:"), kind = cleanup ? "cleanup" : message.startsWith("ssh:") ? "ssh" : message.startsWith("agent:") ? "agent" : cause instanceof ExeImageVerificationError ? cause.kind : "image_pull"; diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index ab62a720..6c28f01e 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -13,7 +13,7 @@ export type JobPageQuery = z.infer; export const jobSelectorItem = z.object({ id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean() }); export const jobSummary = jobSelectorItem.extend({ projectId: z.guid(), - model: z.string(), effort: z.string(), agentKind: z.string(), + model: z.string(), effort: z.string(), agentKind: z.string(), executionType: z.enum(["agent", "code"]), concurrencyLimit: z.number().int(), runningCount: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(), }); @@ -35,8 +35,8 @@ export const triggerResponse = z.discriminatedUnion("kind", [ ]); export const jobResponse = z.object({ id: z.guid(), projectId: z.guid().optional(), name: z.string(), slug: z.string(), enabled: z.boolean(), - promptTemplate: z.string(), runNameTemplate: z.string(), tags: z.array(z.string()).optional(), model: z.string(), effort: z.string().optional(), - executionConfig: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string(), image: z.string().optional() }), + executionType: z.enum(["agent", "code"]).optional(), promptTemplate: z.string(), script: z.string().optional(), runNameTemplate: z.string(), tags: z.array(z.string()).optional(), model: z.string(), effort: z.string().optional(), + executionConfig: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string(), image: z.string().optional(), executionType: z.enum(["agent", "code"]).optional(), script: z.string().optional() }), executionConfigId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), triggers: z.array(triggerResponse), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 79ff56c1..ce807dca 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -6,6 +6,7 @@ export type InvocationSource = "manual" | TriggerKind; export type JobRunState = "queued" | "reserved" | "running" | "succeeded" | "failed" | "stopped"; export interface ExecutionConfig { + executionType?: "agent" | "code"; targetId?: string; connectionId: string; workspace: string; @@ -13,6 +14,7 @@ export interface ExecutionConfig { agentKind: string; tags?: string[]; image?: string; + script?: string; } export interface Trigger { @@ -32,6 +34,8 @@ export interface Job { name: string; slug: string; promptTemplate: string; + executionType?: "agent" | "code"; + script?: string; runNameTemplate?: string; model: string; effort?: string; diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 7d3416d3..212a0418 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -26,7 +26,7 @@ export class PostgresJobRepository implements JobRepository { const skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (db === this.database.orm ? (await this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.job_id=$2 ORDER BY js.position", [this.tenantId, row.id])).rows : (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows); - return { id: row.id, projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + return { id: row.id, projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { @@ -157,9 +157,9 @@ export class PostgresJobRepository implements JobRepository { await client.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,run_name,agent_name,workspace_name,agent_kind,state,execution_backend_kind,execution_config,execution_capabilities,result_protocol_version,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$8,'',j.slug,j.execution_config->>'agentKind',$7, CASE WHEN j.execution_config->>'agentKind'='Amp' THEN 'amp' ELSE 'exe-vm' END, - j.execution_config || jsonb_build_object('model',j.model,'effort',j.effort,'tags',j.tags), + j.execution_config || jsonb_build_object('model',j.model,'effort',j.effort,'tags',j.tags,'inputContext',i.context), CASE WHEN j.execution_config->>'agentKind'='Amp' THEN '["stop"]'::jsonb ELSE '["recovery","stop"]'::jsonb END,1,$9,$10 - FROM app.jobs j + FROM app.jobs j JOIN app.invocations i ON i.tenant_id=j.tenant_id AND i.id=$4 WHERE j.tenant_id=$1 AND j.id=$3`, [this.tenantId, run.id, run.jobId, run.invocationId, invocation.source, invocation.claimKey, run.state, run.runName ?? "", run.createdAt, run.updatedAt]); await client.query("INSERT INTO app.wake_hints(key,not_before) VALUES ('global',now()) ON CONFLICT (key) DO UPDATE SET not_before=least(app.wake_hints.not_before,excluded.not_before),updated_at=now()"); return true; diff --git a/packages/api/src/postgres/job-summary-repository.ts b/packages/api/src/postgres/job-summary-repository.ts index 615cc9c2..bc05a187 100644 --- a/packages/api/src/postgres/job-summary-repository.ts +++ b/packages/api/src/postgres/job-summary-repository.ts @@ -3,7 +3,7 @@ import type { JobPageQuery } from "../job-contracts"; interface SummaryRow { id: string; project_id: string; name: string; slug: string; enabled: boolean; model: string; effort: string; - agent_kind: string; concurrency_limit: number; running_count: string; last_run_state: string | null; + agent_kind: string; execution_type: string | null; concurrency_limit: number; running_count: string; last_run_state: string | null; created_at: Date; updated_at: Date; } @@ -16,7 +16,7 @@ export class JobSummaryRepository { const sort = input.sort ?? "id"; const result = await this.database.pool.query(` WITH page AS MATERIALIZED ( - SELECT id,project_id project_id,name,slug,enabled,model,effort,execution_config->>'agentKind' agent_kind, + SELECT id,project_id project_id,name,slug,enabled,model,effort,execution_config->>'agentKind' agent_kind,execution_config->>'executionType' execution_type, concurrency_limit,created_at,updated_at FROM app.jobs WHERE tenant_id=$1 AND ($2::uuid IS NULL OR ($7='updated' OR id<$2)) AND ($3='' OR strpos(lower(name),lower($3))>0 OR strpos(lower(slug),lower($3))>0) @@ -34,7 +34,7 @@ export class JobSummaryRepository { const rows = result.rows.slice(0, input.limit); return { items: rows.map(row => ({ id: row.id, projectId: row.project_id, name: row.name, slug: row.slug, enabled: row.enabled, - ...(selector ? {} : { model: row.model, effort: row.effort, agentKind: row.agent_kind, + ...(selector ? {} : { model: row.model, effort: row.effort, agentKind: row.agent_kind, executionType: row.execution_type ?? "agent", concurrencyLimit: row.concurrency_limit, runningCount: Number(row.running_count ?? 0), lastRunState: row.last_run_state ?? null, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }) })), nextCursor: result.rows.length > input.limit ? rows.at(-1)!.id : null, diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 1c0e0c7a..a7722fbb 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -34,7 +34,7 @@ export class RunQueryRepository { } values.push(limit + 1); const order = sort ? `CASE WHEN ${sortExpressions[sort]} IS NULL THEN 1 ELSE 0 END ASC, ${sortExpressions[sort]} ${direction} NULLS LAST, r.id ${direction}` : "r.created_at DESC,r.id DESC"; - const result = await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,r.state,r.failure_source, + const result = await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,coalesce(r.execution_config->>'executionType','agent') execution_type,r.state,r.failure_source, CASE WHEN r.agent_error_reason IS NULL THEN NULL ELSE jsonb_build_object('reason',r.agent_error_reason,'reported_at',r.agent_error_reported_at,'reporter',jsonb_build_object('user_id',r.agent_error_reporter_user_id,'kind',r.agent_error_reporter_kind,'id',r.agent_error_reporter_id)) END agent_error, r.provider,r.execution_backend_kind backend_kind,r.execution_capabilities capabilities,r.destination_url,r.artifact_state,r.artifact_error,r.created_at,r.updated_at,jr.started_at, CASE WHEN r.state IN ('succeeded','failed','stopped') AND jr.started_at IS NOT NULL AND jr.updated_at >= jr.started_at @@ -64,11 +64,11 @@ export class RunQueryRepository { return { items: rows, nextCursor }; } async get(runId: string) { - return (await this.database.pool.query(`SELECT r.*,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.source_job_id invocation_source_job_id,i.source_run_id invocation_source_run_id,i.created_at invocation_created_at + return (await this.database.pool.query(`SELECT r.*,coalesce(r.execution_config->>'executionType','agent') execution_type,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.source_job_id invocation_source_job_id,i.source_run_id invocation_source_run_id,i.created_at invocation_created_at FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0] ?? null; } async status(runId: string) { - const row = (await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,pr.name project_name,jr.state,r.run_name,j.name job_name,r.destination_url,r.failure_source, + const row = (await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,pr.name project_name,jr.state,r.run_name,j.name job_name,r.destination_url,r.failure_source,coalesce(r.execution_config->>'executionType','agent') execution_type, CASE WHEN r.agent_error_reason IS NULL THEN NULL ELSE jsonb_build_object('reason',r.agent_error_reason,'reported_at',r.agent_error_reported_at,'reporter',jsonb_build_object('user_id',r.agent_error_reporter_user_id,'kind',r.agent_error_reporter_kind,'id',r.agent_error_reporter_id)) END agent_error, r.created_at,greatest(r.updated_at,jr.updated_at) updated_at,jr.started_at,r.artifact_state, (jr.state IN ('succeeded','failed','stopped') AND (r.artifact_state IN ('pending','collecting') OR NOT r.vm_cleanup_complete)) finalizing, diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index f87604fe..2623e27b 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -40,6 +40,15 @@ export class RunScheduler { } private async launch(run: PersistedRun) { + if (run.executionConfig.executionType === "code") { + if (typeof run.executionConfig.script !== "string" || !run.executionConfig.script.trim()) throw new Error("The code job has no saved script"); + const backend = await this.backend(run), context = run.executionConfig.inputContext; + if (!context || typeof context !== "object" || Array.isArray(context)) throw new Error("The code job input context snapshot is missing"); + const launched = await backend.launch({ runId: run.id, prompt: "", code: { script: run.executionConfig.script, context } }); + await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); + if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); + return; + } if (run.executionConfig.agentKind === "Amp") throw new Error("Amp execution is unavailable for new runs because it cannot deliver the required structured result file. Choose an exe.dev agent integration."); const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); @@ -93,31 +102,35 @@ export class RunScheduler { try { await this.collectHarnessLog(run, backend, artifacts); } catch { errors.push("Harness log collection or storage failed"); } } - const sources = this.sources(run); - if (sources.primary.provider === "codex" && sources.primary.kind !== "execution_stream") errors.push("Historical Codex native source is read-only; canonical execution stream was not declared"); - if (sources.primary.kind === "execution_stream" && !stored.some(item => item.kind === "execution_stream" && item.state === "stored")) { - try { - const collected = await this.collectArtifact(run, backend, sources.primary, true); - if (!collected.ok) errors.push(`Canonical execution stream upload failed: ${sources.primary.path}`); - } catch { errors.push(`Canonical execution stream collection failed: ${sources.primary.path}`); } + const sources = run.executionConfig.executionType === "code" ? undefined : this.sources(run); + if (run.executionConfig.executionType === "code") { + // Code jobs have no agent session trace; preserve the shared result, + // log, output directory, supervision, and cleanup lifecycle. + } else { + const sourceSet = sources!; + if (sourceSet.primary.provider === "codex" && sourceSet.primary.kind !== "execution_stream") errors.push("Historical Codex native source is read-only; canonical execution stream was not declared"); + if (sourceSet.primary.kind === "execution_stream" && !stored.some(item => item.kind === "execution_stream" && item.state === "stored")) { + try { const collected = await this.collectArtifact(run, backend, sourceSet.primary, true); if (!collected.ok) errors.push(`Canonical execution stream upload failed: ${sourceSet.primary.path}`); } + catch { errors.push(`Canonical execution stream collection failed: ${sourceSet.primary.path}`); } } - if (sources.primary.provider !== "codex" && !stored.some(item => item.kind === "native_session" && item.state === "stored")) { + if (sourceSet.primary.provider !== "codex" && !stored.some(item => item.kind === "native_session" && item.state === "stored")) { try { const collected = await this.collectArtifact(run, backend); if (!collected.ok) { errors.push("Native session upload failed"); traceMetric("missing_native_artifact", run.tenantId, run.id, { attempt: run.finalizationAttempt ?? 0 }); } } catch { errors.push("Native session collection or storage failed"); traceMetric("missing_native_artifact", run.tenantId, run.id, { attempt: run.finalizationAttempt ?? 0 }); } } - if (sources.primary.kind === "execution_stream") { - try { errors.push(...await this.finalizePrimary(run, sources.primary)); } + if (sourceSet.primary.kind === "execution_stream") { + try { errors.push(...await this.finalizePrimary(run, sourceSet.primary)); } catch { errors.push("Retained primary trace projection failed"); } } + } if (run.resultProtocolVersion === 1) { try { const current = await artifacts.list(run.id); const retained = new Set(current.filter(item => item.kind === "job_file" && item.state === "stored").map(item => item.source_path)); for (const path of await backend.listJobFiles(run.executionHandle!)) { if (retained.has(path)) continue; - const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path, artifactType: "job_file", contentType: "application/octet-stream", provider: run.executionConfig.agentKind, format: "file", expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); + const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path, artifactType: "job_file", contentType: "application/octet-stream", provider: run.executionConfig.executionType === "code" ? "code" : run.executionConfig.agentKind, format: "file", expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); const uploaded = await backend.collectJobFile(run.executionHandle!, { path, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); if (!uploaded.ok) throw new Error(uploaded.detail ?? "Job file upload failed"); } @@ -175,7 +188,7 @@ export class RunScheduler { const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), byte => byte.toString(16).padStart(2, "0")).join(""); const key = artifactKey(run.tenantId, run.id, "harness/stderr.txt"); await this.env.RUN_ARTIFACTS.put(key, bytes, { httpMetadata: { contentType: "text/plain; charset=utf-8" }, sha256 }); - await artifacts.record({ runId: run.id, kind: "terminal_log", objectKey: key, provider: String(run.executionConfig.agentKind), format: "text", byteSize: bytes.length, sha256 }); + await artifacts.record({ runId: run.id, kind: "terminal_log", objectKey: key, provider: run.executionConfig.executionType === "code" ? "code" : String(run.executionConfig.agentKind), format: "text", byteSize: bytes.length, sha256 }); } private sources(run: PersistedRun): TraceSources { diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index 7af6d7ec..ac0c74d2 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -7,6 +7,7 @@ export const executionState = z.enum(["queued", "reserved", "starting", "running export const agentErrorResponse = z.object({ reason: z.string(), reported_at: z.string(), reporter: z.object({ user_id: z.string(), kind: z.enum(["api_key", "oauth", "session"]), id: z.string() }) }); export const runStatusResponse = z.object({ id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), state: executionState, + execution_type: z.enum(["agent", "code"]).default("agent"), run_name: z.string(), job_name: z.string(), destination_url: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), @@ -22,7 +23,7 @@ export const revisionTracePage = z.object({ items: z.array(traceEventResponse), // A statement snapshot binds metadata and events, even during canonical replacement. export const traceRevisionSql = "jsonb_build_array(c.generation,p.source_kind,p.artifact_sha256,p.parser_version,p.updated_at)::text"; export const runSummaryResponse = z.object({ - id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), job_name: z.string(), issue_id: z.string(), issue_url: z.string().nullable(), issue_title: z.string(), run_name: z.string(), agent_name: z.string(), workspace_name: z.string(), agent_kind: z.string(), state: z.enum([...executionState.options, "done", "ignored"]), provider: z.string(), backend_kind: z.string(), capabilities: z.array(z.string()), destination_url: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), artifact_error: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), + id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), job_name: z.string(), issue_id: z.string(), issue_url: z.string().nullable(), issue_title: z.string(), run_name: z.string(), agent_name: z.string(), workspace_name: z.string(), agent_kind: z.string(), execution_type: z.enum(["agent", "code"]), state: z.enum([...executionState.options, "done", "ignored"]), provider: z.string(), backend_kind: z.string(), capabilities: z.array(z.string()), destination_url: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), artifact_error: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), failure_source: z.enum(["system", "agent"]).nullable(), agent_error: agentErrorResponse.nullable(), elapsed_time: z.union([ z.object({ duration: z.number() }), @@ -40,7 +41,7 @@ export const fullRunResponse = runSummaryResponse.extend({ tenant_id: z.string(), invocation_id: z.string(), execution_handle: z.object({ backendKind: z.string(), id: z.string() }).nullable(), execution_backend_kind: z.string(), execution_capabilities: z.array(z.string()), - claim_released: z.boolean(), vm_cleanup_attempt: z.number().int(), cleanup_next_at: z.string().nullable(), vm_cleanup_complete: z.boolean(), + claim_released: z.boolean(), vm_cleanup_attempt: z.number().int(), cleanup_next_at: z.string().nullable(), vm_cleanup_complete: z.boolean(), execution_type: z.enum(["agent", "code"]).default("agent"), execution_script: z.string().nullable().default(null), execution_configuration: record, job_name: z.string(), prompt: z.string(), context: record, occurrence: record.nullable(), invocation: z.object({ id: z.string(), source: z.string(), claim_key: z.string(), trigger_id: z.string().nullable(), context: record, occurrence: record.nullable(), source_job_id: z.string().nullable(), source_run_id: z.string().nullable(), created_at: z.string() }), invocation_source: z.string(), invocation_claim_key: z.string(), invocation_trigger_id: z.string().nullable(), invocation_created_at: z.string(), diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index b2c34e07..021ea09c 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -176,7 +176,7 @@ describe("Worker OpenAPI request/response boundaries", () => { }); it("documents the job name in run detail for clients with only runs:read", async () => { - vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, job_result: null, run_artifacts: [], prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, source_job_id: null, source_run_id: null, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); + vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", execution_type: "agent", execution_script: null, execution_configuration: {}, state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, job_result: null, run_artifacts: [], prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, source_job_id: null, source_run_id: null, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); const result = await assertResponse(await request("GET", "/api/v1/runs/run-1", undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", "/api/v1/runs/{runId}", 200); expect(result.job_name).toBe("Job name"); }); diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index 6cc957b7..d01e91ad 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -56,6 +56,13 @@ describe("versioned API contract", () => { expect(operation?.parameters.shape.projectId).toBeDefined(); expect(openapi.paths["/api/v1/projects/{projectId}/graph"].get["x-required-scope"]).toBe("projects:read"); }); + it("accepts code jobs without agent prompts or models and rejects missing scripts", () => { + it("accepts code jobs without agent prompts or models and rejects missing scripts", () => { + const code = { name: "Export", slug: "export", executionType: "code", script: "#!/bin/sh\nprintf '{\"status\":\"succeeded\"}' > \"$FACTORIZE_RESULT_PATH\"", executionConfigId: "exe", triggers: [] }; + expect(jobInputSchema.safeParse(code).success).toBe(true); + expect(jobInputSchema.safeParse({ ...code, script: " " }).success).toBe(false); + expect(jobInputSchema.safeParse({ name: "Agent", slug: "agent", promptTemplate: "Run", executionConfigId: "exe", triggers: [] }).success).toBe(true); + }); it("has full bidirectional method/path equality with the executable catalog", () => { const documented = Object.entries(openapi.paths).flatMap(([path, item]) => Object.keys(item as object) diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index c2ee2663..d29b9c91 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -103,6 +103,18 @@ describe("ExeVmBackend", () => { expect(requests[0]).toContain("--image='ghcr.io/acme/base:release'\"'\"'candidate'"); }); + it("runs code jobs as exedev without an agent harness and writes their input context", async () => { + const requests: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { requests.push(String(init.body)); return new Response(requests.length === 1 ? '{"name":"factorize-code"}' : "started", { headers: { "X-Exe-Exit": "0" } }); })); + const launched = await new ExeVmBackend({ apiToken: "secret", tags: ["jobs"], image: "example/base:latest" }).launch({ runId: "code", prompt: "", code: { script: "echo done", context: { source: { outputs: { count: 3 } } } } }); + expect(launched.handle.id).toBe("factorize-code"); + expect(requests[1]).toContain("FACTORIZE_RESULT_PATH=/home/exedev/.factorize-job/results.json"); + expect(requests[1]).toContain("FACTORIZE_INPUT_PATH=/home/exedev/.factorize-job/input.json"); + expect(requests[1]).toContain("bash /tmp/factorize-code-job.sh"); + expect(requests[1]).toContain("--uid=exedev --gid=exedev"); + expect(requests[1]).not.toContain("codex"); + }); + it.each(["codex", "claude", "pi"] as const)("passes %s harness environment as systemd options instead of an executable", async kind => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index affd6019..4e9d2365 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -73,6 +73,17 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po expect(await deliveries()).toHaveLength(1); }); + it("snapshots a code script and structured trigger context when queued", async () => { + const a = await tenant(), id = crypto.randomUUID(), timestamp = new Date().toISOString(); + const trigger: Trigger = { id: crypto.randomUUID(), jobId: id, kind: "manual", slug: "trigger-1", enabled: true, config: {}, createdAt: timestamp, updatedAt: timestamp }; + const code = await repository(a).create({ id, name: "Code", slug: `code-${id}`, executionType: "code", script: "echo original", promptTemplate: "", runNameTemplate: "", model: "", executionConfig: { connectionId: "exe", agentKind: "codex", executionType: "code", script: "echo original" }, concurrencyLimit: 1, enabled: true, triggers: [trigger], createdAt: timestamp, updatedAt: timestamp } as Job); + const invocation = await new InvocationService(repository(a), value => encrypt(value, key)).invoke(id, { source: "manual", triggerId: trigger.id, claimKey: crypto.randomUUID(), context: { "trigger-1": { outputs: { count: 3 } } } }); + const snapshot = await database.pool.query<{ execution_config: any; result_protocol_version: number }>("SELECT execution_config,result_protocol_version FROM app.runs WHERE tenant_id=$1 AND id=$2", [a, invocation.run.id]); + expect(snapshot.rows[0]).toMatchObject({ execution_config: { executionType: "code", script: "echo original", inputContext: { "trigger-1": { outputs: { count: 3 } } } }, result_protocol_version: 1 }); + await repository(a).update({ ...code, script: "echo edited", executionConfig: { ...code.executionConfig, script: "echo edited" }, updatedAt: new Date().toISOString() }); + expect((await database.pool.query<{ execution_config: any }>("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [a, invocation.run.id])).rows[0].execution_config.script).toBe("echo original"); + }); + it("stores manual permissions tenant-locally and removes their edges when a job is deleted", async () => { const a = await tenant(), b = await tenant(), source = await job(a), destination = await job(a), foreign = await job(b); await database.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES ($1,$2,$3)", [a, source.id, destination.id]); diff --git a/packages/app/src/features/jobs/editor-state.ts b/packages/app/src/features/jobs/editor-state.ts index d740be3a..740d0028 100644 --- a/packages/app/src/features/jobs/editor-state.ts +++ b/packages/app/src/features/jobs/editor-state.ts @@ -2,14 +2,14 @@ import type { components, operations } from "factorize-api-client"; export type JobInput = components["schemas"]["JobInput"]; export type Job = operations["get_api_v1_jobs_jobId"]["responses"][200]["content"]["application/json"]; export type Trigger = JobInput["triggers"][number]; -export const emptyJob = (): JobInput => ({ name: "", slug: "", promptTemplate: "", runNameTemplate: "", executionConfigId: "", concurrencyLimit: 1, tags: [], vmImage: "", model: "", effort: "", skillIds: [], triggers: [{ kind: "manual", slug: "trigger-1", enabled: true, config: {} }] }); +export const emptyJob = (): JobInput => ({ executionType: "agent", name: "", slug: "", promptTemplate: "", script: "", runNameTemplate: "", executionConfigId: "", concurrencyLimit: 1, tags: [], vmImage: "", model: "", effort: "", skillIds: [], triggers: [{ kind: "manual", slug: "trigger-1", enabled: true, config: {} }] }); export function canonicalizeVmImage(value: string): string { const trimmed = value.trim(), digestAt = trimmed.indexOf("@"), reference = digestAt < 0 ? trimmed : trimmed.slice(0, digestAt), digest = digestAt < 0 ? "" : trimmed.slice(digestAt); const slash = reference.lastIndexOf("/"), colon = reference.lastIndexOf(":"), tag = colon > slash ? reference.slice(colon) : "", name = tag ? reference.slice(0, -tag.length) : reference; return `${name.toLowerCase()}${tag}${digest}`; } export function editableJob(job: Job): JobInput { - return { projectId: job.projectId, name: job.name, slug: job.slug, promptTemplate: job.promptTemplate, runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { + return { executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, slug: job.slug, promptTemplate: job.promptTemplate, script: job.script ?? "", runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { const { id, slug, kind, enabled } = trigger; const config = trigger.kind === "webhook" ? Object.fromEntries(Object.entries(trigger.config).filter(([key]) => !["destination", "secretConfigured"].includes(key))) : trigger.config; return { id, slug, kind, enabled, config } as Trigger; @@ -35,7 +35,8 @@ export function writeInput(draft: JobInput): JobInput { export function validateJobInput(input: JobInput): string | undefined { if (!input.name.trim() || input.name.length > 120) return "Enter a job name between 1 and 120 characters."; if (!/^[a-z][a-z0-9_-]{0,29}$/.test(input.slug)) return "Slug must start with a lowercase letter and contain at most 30 characters."; - if (!input.promptTemplate || input.promptTemplate.length > 50_000) return "Enter a prompt template between 1 and 50,000 characters."; + if (input.executionType === "agent" && (!input.promptTemplate || input.promptTemplate.length > 50_000)) return "Enter a prompt template between 1 and 50,000 characters."; + if (input.executionType === "code" && (!input.script?.trim() || input.script.length > 50_000)) return "Enter a script between 1 and 50,000 characters."; if (!Number.isInteger(input.concurrencyLimit) || input.concurrencyLimit < 1 || input.concurrencyLimit > 50) return "Concurrency limit must be between 1 and 50."; if (!input.executionConfigId) return "Choose an execution integration."; if ((input.tags?.length ?? 0) > 20 || input.tags?.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) return "VM tags are invalid."; diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index 773563af..e917446f 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -45,7 +45,7 @@ function EditorForm({ initial }: { initial?: Job }) { const verificationGeneration = useRef(0); const activeVerificationId = verificationRef?.fingerprint === verificationFingerprint ? verificationRef.id : ""; const verification = useQuery({ queryKey: ["vm-image-verification", activeVerificationId], enabled: !!activeVerificationId, queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/vm-image-verifications/{verificationId}", { params: { path: { verificationId: activeVerificationId } }, signal }); if (!data || error) throw new Error(messageOf(error)); return data; }, refetchInterval: query => query.state.data && ["succeeded", "failed", "cleanup_failed"].includes(query.state.data.status) ? false : 1500, refetchIntervalInBackground: true }); - const verifyImage = useMutation({ retry: false, mutationFn: async (snapshot: { fingerprint: string; generation: number }) => { const { data, error } = await api.POST("/api/v1/vm-image-verifications", { body: { connectionId: draft.executionConfigId, image: draft.vmImage?.trim() ?? "", tags: draft.tags ?? [], agentKind: target?.agentKind as "codex" | "claude" | "pi" } }); if (!data || error) throw new Error(messageOf(error)); return { ...snapshot, id: data.id }; }, onSuccess: value => { if (currentVerificationFingerprint.current !== value.fingerprint || verificationGeneration.current !== value.generation) return; const record = { fingerprint: value.fingerprint, id: value.id }; setVerificationRef(record); localStorage.setItem(verificationKey, JSON.stringify(record)); } }); + const verifyImage = useMutation({ retry: false, mutationFn: async (snapshot: { fingerprint: string; generation: number }) => { const { data, error } = await api.POST("/api/v1/vm-image-verifications", { body: { connectionId: draft.executionConfigId, image: draft.vmImage?.trim() ?? "", tags: draft.tags ?? [], agentKind: target?.agentKind as "codex" | "claude" | "pi", executionType: draft.executionType ?? "agent" } }); if (!data || error) throw new Error(messageOf(error)); return { ...snapshot, id: data.id }; }, onSuccess: value => { if (currentVerificationFingerprint.current !== value.fingerprint || verificationGeneration.current !== value.generation) return; const record = { fingerprint: value.fingerprint, id: value.id }; setVerificationRef(record); localStorage.setItem(verificationKey, JSON.stringify(record)); } }); const projectId = new URLSearchParams(location.searchStr).get("projectId") ?? undefined; const selectedProjectId = initial?.projectId ?? draft.projectId ?? projectId; const [projectDialog, setProjectDialog] = useState(false); @@ -86,17 +86,18 @@ function EditorForm({ initial }: { initial?: Job }) {
{ e.preventDefault(); save.mutate(); }}>

Job details

Name this job and set its stable identifier.

{!initial &&
{projects.isPending &&

Loading projects…

}{projects.error &&

{projects.error.message}

}
} -

Execution

Choose an integration for this job, then configure its VM tags, model, effort, and concurrency.

+

Execution

Choose an integration for this job, then configure its VM tags, model, effort, and concurrency.

{targets.isPending &&

Loading integrations…

}{targets.error &&

{targets.error.message}

}{targets.data?.length === 0 &&

Connect an execution provider in settings before creating a job.

} {target?.kind !== "amp" &&
{draft.vmImage &&

{verification.data?.status === "succeeded" && activeVerificationId ? `Verified: ${verification.data?.phase}` : verification.data?.status === "failed" && activeVerificationId ? `${verification.data?.errorKind}: ${verification.data?.error}` : verification.data?.status === "cleanup_failed" && activeVerificationId ? `Cleanup unresolved: ${verification.data?.error}` : activeVerificationId ? `Verification ${verification.data?.status}: ${verification.data?.phase}` : "Not verified"}

}{draft.vmImage && }{verifyImage.error &&

{verifyImage.error.message}

}
} - + {(draft.executionType ?? "agent") === "agent" && <> - -

Skills

Ordered global instructions are composed before this job context. Bodies remain literal.

{(draft.skillIds ?? []).map((id, index) => { const skill = skills.data?.items.find(item => item.id === id); return
{index + 1}. {skill?.key ?? "Unavailable skill"}
; })}
Create or edit skills

Prompt and context

Write instructions using context supplied by your triggers.

update("promptTemplate", value)} triggers={draft.triggers} /> + } + {(draft.executionType ?? "agent") === "code" &&