diff --git a/docs/factorize-validation-runner.md b/docs/factorize-validation-runner.md index 1a0a68cb..2b465cb3 100644 --- a/docs/factorize-validation-runner.md +++ b/docs/factorize-validation-runner.md @@ -52,6 +52,31 @@ PostgreSQL admin URL, so missing image prerequisites fail before migrations or the full suite. A failure requires correcting the image or bootstrap and publishing a new digest, followed by repeating this sequence. +## Background run acceptance + +`npm run test:local` includes the background run acceptance scenario. It starts +the Worker and PostgreSQL locally. A deterministic VM backend receives the +scheduler's launch requests and supplies success and failure responses. The +test dispatches through MCP, listens for a resource update, and delivers each +terminal outcome to a durable conversation inbox. It also exercises vendor +identity, duplicate submissions, capacity, cancellation, replay, and run +history after template deletion. Chromium covers the launch form and skill +filter in the browser lane. + +For a focused rerun after `npm ci`, run `npm run bootstrap:test`, export the +local database variables it prints, then run: + +```sh +npm run build --workspace=factorize-app +node --test scripts/agent-api-runtime.test.mjs +node --test --test-name-pattern='filter direct runs' packages/app/test/runs.browser.test.mjs +``` + +The [host adapter](../scripts/watch-run.mjs) accepts an authenticated MCP +request function, a conversation ID, and an idempotent delivery callback. +The [acceptance test](../scripts/background-run-acceptance.mjs) supplies a +PostgreSQL inbox and verifies delivery after reconnecting. + ## Validated image record | Field | Value | diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index c25bc7e0..02f8714a 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2159,6 +2159,34 @@ 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. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_runs"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/projects/{projectId}/run-defaults": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Set the VM configuration, permissions and capacity for direct launches + * @description Requires the projects:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_projects_projectId_run_defaults"]; post?: never; delete?: never; options?: never; @@ -2506,10 +2534,13 @@ export interface components { }; Run: { id: string; - job_id: string; + job_id: string | null; + launch_skill_id?: string | null; + launch_skill_key?: string | null; + launch_skill_revision?: number | null; project_id?: string; project_name?: string; - job_name: string; + job_name: string | null; issue_id: string; issue_url: string | null; issue_title: string; @@ -2560,10 +2591,13 @@ export interface components { RunPage: { items: { id: string; - job_id: string; + job_id: string | null; + launch_skill_id?: string | null; + launch_skill_key?: string | null; + launch_skill_revision?: number | null; project_id?: string; project_name?: string; - job_name: string; + job_name: string | null; issue_id: string; issue_url: string | null; issue_title: string; @@ -2742,10 +2776,13 @@ export interface components { }; RunDetail: { id: string; - job_id: string; + job_id: string | null; + launch_skill_id?: string | null; + launch_skill_key?: string | null; + launch_skill_revision?: number | null; project_id?: string; project_name?: string; - job_name: string; + job_name: string | null; issue_id: string; issue_url: string | null; issue_title: string; @@ -2841,6 +2878,7 @@ export interface components { id: string; source: string; claim_key: string; + template_job_id?: string | null; trigger_id: string | null; context: { [key: string]: unknown; @@ -2902,7 +2940,7 @@ export interface components { }; RunDiagnostics: { runId: string; - jobId: string; + jobId: string | null; state: string; provider?: string; backendKind?: string; @@ -2936,7 +2974,7 @@ export interface components { /** @default 1 */ concurrencyLimit: number; /** @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:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; executionConfigId: string; tags?: string[]; vmImage?: string; @@ -3039,6 +3077,7 @@ export interface components { sourceJobIds: string[]; }; })[]; + launchSkillId?: string | null; skillIds?: string[]; portableIntegrationIds?: string[]; /** @enum {string} */ @@ -4040,7 +4079,7 @@ export interface operations { /** @constant */ role: "owner"; }; - capabilities: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + capabilities: ("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")[]; /** Format: date-time */ expiresAt: string; }; @@ -5716,7 +5755,7 @@ export interface operations { "application/json": { id: string; name: string; - scopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + scopes: ("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")[]; created_at: string; expires_at: string; last_used_at?: string | null; @@ -5745,7 +5784,7 @@ export interface operations { content: { "application/json": { name: string; - scopes: (("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write") | ("flows:read" | "flows:write"))[]; + scopes: (("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") | ("flows:read" | "flows:write"))[]; expiryDays: 7 | 30 | 90; }; }; @@ -5760,7 +5799,7 @@ export interface operations { "application/json": { id: string; name: string; - scopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + scopes: ("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")[]; created_at: string; expires_at: string; last_used_at?: string | null; @@ -6310,6 +6349,23 @@ export interface operations { description?: string; createdAt: string; updatedAt: string; + runDefaults?: { + 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")[]; + /** @default 4 */ + capacity: number; + }; jobCount: number; }[]; }; @@ -6353,6 +6409,23 @@ export interface operations { description?: string; createdAt: string; updatedAt: string; + runDefaults?: { + 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")[]; + /** @default 4 */ + capacity: number; + }; jobCount: number; }; }; @@ -6392,6 +6465,23 @@ export interface operations { description?: string; createdAt: string; updatedAt: string; + runDefaults?: { + 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")[]; + /** @default 4 */ + capacity: number; + }; jobCount: number; }; }; @@ -6437,6 +6527,23 @@ export interface operations { description?: string; createdAt: string; updatedAt: string; + runDefaults?: { + 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")[]; + /** @default 4 */ + capacity: number; + }; jobCount: number; }; }; @@ -6879,7 +6986,7 @@ export interface operations { executionType?: "agent" | "code"; script?: string; }; - runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; portableIntegrationIds?: string[]; /** @enum {string} */ modelAccess?: "native" | "portable"; @@ -6888,6 +6995,7 @@ export interface operations { githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; xConnectionIds?: string[]; + launchSkillId?: string | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7179,7 +7287,7 @@ export interface operations { executionType?: "agent" | "code"; script?: string; }; - runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; portableIntegrationIds?: string[]; /** @enum {string} */ modelAccess?: "native" | "portable"; @@ -7188,6 +7296,7 @@ export interface operations { githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; xConnectionIds?: string[]; + launchSkillId?: string | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7391,7 +7500,7 @@ export interface operations { executionType?: "agent" | "code"; script?: string; }; - runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; portableIntegrationIds?: string[]; /** @enum {string} */ modelAccess?: "native" | "portable"; @@ -7400,6 +7509,7 @@ export interface operations { githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; xConnectionIds?: string[]; + launchSkillId?: string | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -8358,7 +8468,7 @@ export interface operations { executionType?: "agent" | "code"; script?: string; }; - runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; portableIntegrationIds?: string[]; /** @enum {string} */ modelAccess?: "native" | "portable"; @@ -8367,6 +8477,7 @@ export interface operations { githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; xConnectionIds?: string[]; + launchSkillId?: string | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -8548,7 +8659,7 @@ export interface operations { /** @default 1 */ concurrencyLimit?: number; /** @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:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; executionConfigId: string; tags?: string[]; vmImage?: string; @@ -8651,6 +8762,7 @@ export interface operations { sourceJobIds: string[]; }; })[]; + launchSkillId?: string | null; skillIds?: string[]; portableIntegrationIds?: string[]; /** @enum {string} */ @@ -8701,7 +8813,7 @@ export interface operations { executionType?: "agent" | "code"; script?: string; }; - runScopes: ("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + 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")[]; portableIntegrationIds?: string[]; /** @enum {string} */ modelAccess?: "native" | "portable"; @@ -8710,6 +8822,7 @@ export interface operations { githubInstallationIds?: number[]; linearConnectionId?: "linear" | null; xConnectionIds?: string[]; + launchSkillId?: string | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -8903,6 +9016,7 @@ export interface operations { projectId?: string | string[]; jobId?: string | string[]; state?: ("queued" | "reserved" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "succeeded" | "stopping" | "stopped") | ("queued" | "reserved" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "succeeded" | "stopping" | "stopped")[]; + launchSkillId?: string | "none"; contextQuery?: string; sort?: "job" | "run" | "status" | "created" | "agent"; direction?: "asc" | "desc"; @@ -8934,6 +9048,123 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_runs: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + projectId?: string; + prompt: string; + skill?: string; + name?: string; + inputs?: { + [key: string]: unknown; + }; + idempotencyKey?: string; + }; + }; + }; + responses: { + /** @description Accepted run */ + 202: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + runId: string; + /** Format: uri */ + url: string; + outcomeUri: string; + duplicate: boolean; + }; + }; + }; + 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"]; + }; + }; + put_api_v1_projects_projectId_run_defaults: { + parameters: { + query?: never; + header?: never; + path: { + projectId: string; + }; + 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")[]; + /** @default 4 */ + capacity?: number; + }; + }; + }; + responses: { + /** @description Project run defaults */ + 200: { + headers: { + [name: string]: unknown; + }; + 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")[]; + /** @default 4 */ + capacity: number; + }; + }; + }; + 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?: { @@ -9073,7 +9304,10 @@ export interface operations { content: { "application/json": { id: string; - job_id: string; + job_id: string | null; + launch_skill_id?: string | null; + launch_skill_key?: string | null; + launch_skill_revision?: number | null; project_id?: string; project_name?: string; /** @enum {string} */ @@ -9084,7 +9318,7 @@ export interface operations { */ execution_type: "agent" | "code"; run_name: string; - job_name: string; + job_name: string | null; destination_url: string | null; created_at: string; updated_at: string; diff --git a/packages/api/migrations/0061_project_runs.sql b/packages/api/migrations/0061_project_runs.sql new file mode 100644 index 00000000..51ce0c9a --- /dev/null +++ b/packages/api/migrations/0061_project_runs.sql @@ -0,0 +1,52 @@ +ALTER TABLE app.job_skills ADD COLUMN context_skill boolean NOT NULL DEFAULT true; +ALTER TABLE app.projects ADD COLUMN run_defaults jsonb; +ALTER TABLE app.invocations ALTER COLUMN job_id DROP NOT NULL, ALTER COLUMN trigger_id DROP NOT NULL, + ADD FOREIGN KEY (tenant_id) REFERENCES app.tenants(id) ON DELETE CASCADE, + ADD COLUMN caller text, ADD COLUMN request_hash text, + DROP CONSTRAINT invocations_source_check, + ADD CONSTRAINT invocations_source_check CHECK(source IN ('manual','schedule','webhook','jobLifecycle','jobIdle','direct')); +ALTER TABLE app.job_runs ALTER COLUMN job_id DROP NOT NULL; +ALTER TABLE app.runs ALTER COLUMN job_id DROP NOT NULL, ADD COLUMN project_id uuid, + ADD COLUMN launch_skill_id uuid, ADD COLUMN launch_skill_key text, ADD COLUMN launch_skill_revision integer, + ADD COLUMN source_job_name text; +UPDATE app.runs r SET project_id=j.project_id,source_job_name=j.name FROM app.jobs j WHERE j.tenant_id=r.tenant_id AND j.id=r.job_id; +ALTER TABLE app.runs ALTER COLUMN project_id SET NOT NULL, + ADD FOREIGN KEY(tenant_id,project_id) REFERENCES app.projects(tenant_id,id) DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE app.invocations ADD COLUMN template_job_id uuid, ADD COLUMN origin_trigger_id uuid; +UPDATE app.invocations SET template_job_id=job_id,origin_trigger_id=trigger_id; +CREATE FUNCTION app.snapshot_invocation_origin() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + NEW.template_job_id := NEW.job_id; + NEW.origin_trigger_id := NEW.trigger_id; + RETURN NEW; +END $$; +CREATE TRIGGER snapshot_invocation_origin BEFORE INSERT ON app.invocations FOR EACH ROW EXECUTE FUNCTION app.snapshot_invocation_origin(); +-- Allow the previous application writer to continue inserting job launches during rollout. +CREATE FUNCTION app.capture_run_project() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.job_id IS NOT NULL THEN + SELECT project_id,name INTO NEW.project_id,NEW.source_job_name FROM app.jobs WHERE tenant_id=NEW.tenant_id AND id=NEW.job_id; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER capture_run_project BEFORE INSERT ON app.runs FOR EACH ROW EXECUTE FUNCTION app.capture_run_project(); +ALTER TABLE app.runs DROP CONSTRAINT runs_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id); +ALTER TABLE app.job_runs DROP CONSTRAINT job_runs_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id); +ALTER TABLE app.invocations DROP CONSTRAINT invocations_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id), + DROP CONSTRAINT invocations_tenant_id_trigger_id_fkey, ADD FOREIGN KEY(tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id) ON DELETE SET NULL (trigger_id); +CREATE UNIQUE INDEX direct_run_claim ON app.invocations(tenant_id,caller,claim_key) WHERE source='direct'; +CREATE INDEX runs_project_skill ON app.runs(tenant_id,project_id,launch_skill_id,created_at DESC,id DESC); +CREATE INDEX runs_skill ON app.runs(tenant_id,launch_skill_id,created_at DESC,id DESC); + +-- A terminal run has one outcome for its lifetime. Recording it on the row +-- covers queued cancellations as well as the scheduler's terminal transaction. +ALTER TABLE app.runs ADD COLUMN outcome_id uuid; +UPDATE app.runs SET outcome_id=id WHERE state IN ('succeeded','failed','stopped'); +CREATE FUNCTION app.capture_run_outcome() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.state IN ('succeeded','failed','stopped') THEN NEW.outcome_id := NEW.id; END IF; + RETURN NEW; +END $$; +CREATE TRIGGER capture_run_outcome BEFORE INSERT OR UPDATE OF state ON app.runs FOR EACH ROW EXECUTE FUNCTION app.capture_run_outcome(); + +INSERT INTO app.schema_migrations(version) VALUES ('0061_project_runs') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index 54459b1e..5f6e2f8c 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -3,7 +3,7 @@ import type { Env, OAuthProps } from "./types"; import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; -export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const; +export const ACCESS_SCOPES = ["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"] as const; export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"]; export type AccessScope = typeof ACCESS_SCOPES[number]; export type LegacyScope = "flows:read" | "flows:write"; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index bc5af2d1..a4248518 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -13,7 +13,7 @@ import { z } from "zod"; import type { ApiService } from "./flow-service"; import { jobInputSchema, - manualInvocationSchema, + startRunInput, startRunReceipt, projectRunDefaults, storedRunDefaults, manualInvocationSchema, renameRunSchema, reportRunErrorSchema, invocationPermissionsInput, @@ -978,6 +978,14 @@ export const API_ROUTES: RouteContract[] = [ { summary: "Delete job", responses: { "200": { description: "Deleted" } } }, (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", + 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/runs", diff --git a/packages/api/src/api-document.json b/packages/api/src/api-document.json index bcecae1d..807509f0 100644 --- a/packages/api/src/api-document.json +++ b/packages/api/src/api-document.json @@ -767,7 +767,7 @@ "type": "string" }, "jobId": { - "type": "string" + "type": ["string", "null"] }, "state": { "type": "string" diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 6c230bc6..a8d4b590 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions"; -export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"]); +export const scopeSchema = z.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"]); export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), @@ -9,6 +9,7 @@ export const matchRuleSchema = z.object({ }); export const listRunsSchema = z.object({ projectId: z.union([z.guid(), z.array(z.guid()).min(1).max(100)]).optional(), jobId: z.union([z.guid(), z.array(z.guid()).min(1).max(100)]).optional(), state: z.union([runStateSchema, z.array(runStateSchema).min(1).max(10)]).optional(), + launchSkillId: z.union([z.guid(), z.literal("none")]).optional(), contextQuery: z.string().min(1).max(50_000).optional(), sort: z.enum(["job", "run", "status", "created", "agent"]).optional(), direction: z.enum(["asc", "desc"]).optional(), @@ -75,6 +76,7 @@ export const jobInputSchema = z.object({ model: z.string().trim().max(120).optional(), effort: z.string().trim().max(40).optional(), triggers: z.array(triggerSchema).max(50).default([]), + launchSkillId: z.guid().nullable().optional(), skillIds: z.array(z.guid()).max(50).optional(), portableIntegrationIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "Portable integrations must be unique").optional(), modelAccess: z.enum(["native", "portable"]).optional(), @@ -112,3 +114,23 @@ export const jobConditionsTestSchema = z.object({ export type JobInput = z.infer; 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()), + skill: z.string().min(1).max(64).optional(), + name: z.string().trim().min(1).max(120).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(); +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, + tags: jobInputSchema.shape.tags, modelAccountId: jobInputSchema.shape.modelAccountId, + portableIntegrationIds: jobInputSchema.shape.portableIntegrationIds, githubInstallationIds: jobInputSchema.shape.githubInstallationIds, + linearConnectionId: jobInputSchema.shape.linearConnectionId, xConnectionIds: jobInputSchema.shape.xConnectionIds, + runScopes: jobInputSchema.shape.runScopes, capacity: z.number().int().min(1).max(50).default(4), +}).strict(); + +export const storedRunDefaults = projectRunDefaults.extend({vmImage:z.string().optional()}); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 6610cf1b..30354fd3 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,6 @@ +import { submitRun } from "./postgres/run-submission"; +import type { DatabaseClient } from "./postgres/database"; +import { startRunInput,projectRunDefaults } from "./flow-schemas"; import { grantVm, revokeVmGrant } from "./vm-grants"; import { AgentApiService, listAgentPolicies } from "./agent-api"; import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; @@ -69,7 +72,7 @@ export function publicValue(schema: T, value: unknown): z.o return result.data; } -type Scope = "projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write"; +type Scope = "runs:start" | "projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write"; export class ApiService { authorizationDuration = 0; @@ -102,33 +105,147 @@ export class ApiService { return { targetId: id, connectionId: id, workspace: "", cwd: "", agentKind: "codex", tags: [], image: fly.image, region: fly.region, size: fly.size, executionProvider: "fly" as const }; } - private async portableSelections(config: Awaited>, executionType: "agent" | "code", input: JobInput, current?: Job) { - if (config.executionProvider === "docker" && executionType !== "code") throw new ServiceError(400, "invalid_request", "Docker test execution supports code jobs only."); - const portableIntegrationIds = input.portableIntegrationIds ?? current?.portableIntegrationIds ?? current?.executionConfig.portableIntegrationIds ?? []; - const githubInstallationIds = input.githubInstallationIds ?? current?.githubInstallationIds ?? current?.executionConfig.githubInstallationIds ?? []; - const linearConnectionId = input.linearConnectionId !== undefined ? input.linearConnectionId : current?.linearConnectionId ?? current?.executionConfig.linearConnectionId; - const xConnectionIds = input.xConnectionIds ?? current?.xConnectionIds ?? current?.executionConfig.xConnectionIds ?? []; - if (executionType === "code" && input.modelAccess === "portable") throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access."); - const modelAccess = executionType === "code" ? "native" : input.modelAccess ?? current?.modelAccess ?? current?.executionConfig.modelAccess ?? (config.executionProvider === "fly" ? "portable" : "native"); - if (modelAccess === "portable" && config.agentKind !== "codex") throw new ServiceError(400,"invalid_request","Managed model accounts support Codex jobs."); - if (modelAccess === "native" && input.modelAccountId) throw new ServiceError(400, "invalid_request", "Native model access cannot select a portable model account."); - const modelAccountId = modelAccess === "portable" ? input.modelAccountId ?? current?.modelAccountId ?? current?.executionConfig.modelAccountId : undefined; - if (executionType === "code" && modelAccountId) throw new ServiceError(400, "invalid_request", "Code jobs cannot select a model account."); - if (config.executionProvider === "fly" && executionType === "agent" && config.agentKind === "codex" && (!modelAccountId || modelAccess !== "portable")) throw new ServiceError(400, "invalid_request", "Fly Codex jobs require a portable model account."); - const records = await new CredentialRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).metadata(); - const byId = new Map(records.map(record => [record.id, record])); - if (new Set(portableIntegrationIds).size !== portableIntegrationIds.length || portableIntegrationIds.some(id => byId.get(id)?.kind !== "bearer")) throw new ServiceError(400, "invalid_request", "One or more selected portable integrations are unavailable."); - const installations = await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations(); - const activeInstallationIds = new Set(installations.filter(item => item.state === "active").map(item => Number(item.installationId))); - if (new Set(githubInstallationIds).size !== githubInstallationIds.length || githubInstallationIds.some(id => !activeInstallationIds.has(id))) throw new ServiceError(400, "invalid_request", "One or more selected GitHub installations are unavailable."); - if (linearConnectionId && (!await this.connections().get("linear"))) throw new ServiceError(400, "invalid_request", "The selected Linear connection is unavailable."); - const xConnections = await new XConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).list(); - if (new Set(xConnectionIds).size !== xConnectionIds.length || xConnectionIds.some(id => !xConnections.some(connection => connection.id === id && connection.status === "connected"))) throw new ServiceError(400, "invalid_request", "One or more selected X connections are unavailable. Connect them or remove the selections."); - if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") throw new ServiceError(400, "invalid_request", "The selected model account is unavailable."); - if (modelAccountId && !modelCredentialConfigured((await this.credentials().managedCredential(modelAccountId,"model"))?.payload??"")) throw new ServiceError(400,"invalid_request","Connect the selected model account before using it in a job."); - for (const id of portableIntegrationIds) if (!await this.credentials().managedCredential(id,"bearer")) throw new ServiceError(400,"invalid_request","Re-enter the selected bearer credential before using it in a job."); - if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) throw new ServiceError(400, "invalid_request", "Portable model access requires a model account."); - return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), xConnectionIds, modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; + private async portableSelections( + config: Awaited>, + executionType: "agent" | "code", + input: Pick< + JobInput, + | "portableIntegrationIds" + | "githubInstallationIds" + | "linearConnectionId" + | "xConnectionIds" + | "modelAccess" + | "modelAccountId" + >, + current?: Job, + ) { + if (config.executionProvider === "docker" && executionType !== "code") + throw new ServiceError(400, "invalid_request", "Docker test execution supports code jobs only."); + const portableIntegrationIds = + input.portableIntegrationIds ?? + current?.portableIntegrationIds ?? + current?.executionConfig.portableIntegrationIds ?? + []; + const githubInstallationIds = + input.githubInstallationIds ?? + current?.githubInstallationIds ?? + current?.executionConfig.githubInstallationIds ?? + []; + const linearConnectionId = + input.linearConnectionId !== undefined + ? input.linearConnectionId + : (current?.linearConnectionId ?? current?.executionConfig.linearConnectionId); + const xConnectionIds = + input.xConnectionIds ?? current?.xConnectionIds ?? current?.executionConfig.xConnectionIds ?? []; + if (executionType === "code" && input.modelAccess === "portable") + throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access."); + const modelAccess = + executionType === "code" + ? "native" + : (input.modelAccess ?? + current?.modelAccess ?? + current?.executionConfig.modelAccess ?? + (config.executionProvider === "fly" ? "portable" : "native")); + if (modelAccess === "portable" && config.agentKind !== "codex") + throw new ServiceError(400, "invalid_request", "Managed model accounts support Codex jobs."); + if (modelAccess === "native" && input.modelAccountId) + throw new ServiceError( + 400, + "invalid_request", + "Native model access cannot select a portable model account.", + ); + const modelAccountId = + modelAccess === "portable" + ? (input.modelAccountId ?? current?.modelAccountId ?? current?.executionConfig.modelAccountId) + : undefined; + if (executionType === "code" && modelAccountId) + throw new ServiceError(400, "invalid_request", "Code jobs cannot select a model account."); + if ( + config.executionProvider === "fly" && + executionType === "agent" && + config.agentKind === "codex" && + (!modelAccountId || modelAccess !== "portable") + ) + throw new ServiceError(400, "invalid_request", "Fly Codex jobs require a portable model account."); + const records = await new CredentialRepository( + databaseFor(this.env), + this.auth.tenantId, + this.env.CREDENTIAL_ENCRYPTION_KEY, + ).metadata(); + const byId = new Map(records.map((record) => [record.id, record])); + if ( + new Set(portableIntegrationIds).size !== portableIntegrationIds.length || + portableIntegrationIds.some((id) => byId.get(id)?.kind !== "bearer") + ) + throw new ServiceError( + 400, + "invalid_request", + "One or more selected portable integrations are unavailable.", + ); + const installations = await new GitHubRepository( + databaseFor(this.env), + this.auth.tenantId, + ).installations(); + const activeInstallationIds = new Set( + installations.filter((item) => item.state === "active").map((item) => Number(item.installationId)), + ); + if ( + new Set(githubInstallationIds).size !== githubInstallationIds.length || + githubInstallationIds.some((id) => !activeInstallationIds.has(id)) + ) + throw new ServiceError( + 400, + "invalid_request", + "One or more selected GitHub installations are unavailable.", + ); + if (linearConnectionId && !(await this.connections().get("linear"))) + throw new ServiceError(400, "invalid_request", "The selected Linear connection is unavailable."); + const xConnections = await new XConnectionRepository( + databaseFor(this.env), + this.auth.tenantId, + this.env.CREDENTIAL_ENCRYPTION_KEY, + ).list(); + if ( + new Set(xConnectionIds).size !== xConnectionIds.length || + xConnectionIds.some( + (id) => !xConnections.some((connection) => connection.id === id && connection.status === "connected"), + ) + ) + throw new ServiceError( + 400, + "invalid_request", + "One or more selected X connections are unavailable. Connect them or remove the selections.", + ); + if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") + throw new ServiceError(400, "invalid_request", "The selected model account is unavailable."); + if ( + modelAccountId && + !modelCredentialConfigured( + (await this.credentials().managedCredential(modelAccountId, "model"))?.payload ?? "", + ) + ) + throw new ServiceError( + 400, + "invalid_request", + "Connect the selected model account before using it in a job.", + ); + for (const id of portableIntegrationIds) + if (!(await this.credentials().managedCredential(id, "bearer"))) + throw new ServiceError( + 400, + "invalid_request", + "Re-enter the selected bearer credential before using it in a job.", + ); + if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) + throw new ServiceError(400, "invalid_request", "Portable model access requires a model account."); + return { + portableIntegrationIds, + githubInstallationIds, + ...(linearConnectionId ? { linearConnectionId } : {}), + xConnectionIds, + modelAccess, + ...(modelAccountId ? { modelAccountId } : {}), + }; } private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) { @@ -189,7 +306,42 @@ 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, runScopes: job.runScopes ?? [...DEFAULT_RUN_SCOPES], 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 }); + return publicValue(jobResponse, { + ...job, + launchSkillId: job.executionConfig.launchSkillId ?? null, + runScopes: job.runScopes ?? [...DEFAULT_RUN_SCOPES], + 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); } @@ -343,33 +495,139 @@ export class ApiService { const run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); - delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, source_job_id: run.invocation_source_job_id ?? null, source_run_id: run.invocation_source_run_id ?? null, created_at: run.invocation_created_at }; + delete run.encrypted_prompt; + run.prompt = prompt; + run.capabilities = run.execution_capabilities; + run.backend_kind = run.execution_backend_kind; + run.invocation = { + id: run.invocation_id, + source: run.invocation_source, + claim_key: run.invocation_claim_key, + trigger_id: run.invocation_trigger_id, + template_job_id: run.template_job_id, + context: run.context, + occurrence: run.occurrence, + source_job_id: run.invocation_source_job_id ?? null, + source_run_id: run.invocation_source_run_id ?? null, + created_at: run.invocation_created_at, + }; const [activity, projection, cursor, artifacts] = await Promise.all([ repository.activity(runId), - databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]), - databaseFor(this.env).pool.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]), + databaseFor(this.env).pool.query( + "SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", + [this.auth.tenantId, runId], + ), + databaseFor(this.env).pool.query( + "SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", + [this.auth.tenantId, runId], + ), new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId), ]); - run.activity = activity; run.execution_diagnostics ??= null; run.trace_sources ??= null; - run.trace_projection = projection.rows[0] ?? null; run.trace_generation = cursor.rows[0]?.generation ?? null; - run.harness_log = artifacts.find(item => item.kind === "terminal_log") ?? null; + run.activity = activity; + run.execution_diagnostics ??= null; + run.trace_sources ??= null; + run.trace_projection = projection.rows[0] ?? null; + run.trace_generation = cursor.rows[0]?.generation ?? null; + run.harness_log = artifacts.find((item) => item.kind === "terminal_log") ?? null; // Enumerate public fields rather than publishing future database columns. - const agentError = run.agent_error_reason ? { reason: run.agent_error_reason, reported_at: run.agent_error_reported_at, reporter: { user_id: run.agent_error_reporter_user_id, kind: run.agent_error_reporter_kind, id: run.agent_error_reporter_id } } : null; - 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, execution_type: run.execution_type ?? run.execution_config?.executionType ?? "agent", - state: run.state, failure_source: run.failure_source ?? null, failure: run.failure_code && run.failure_reason ? { source: run.failure_source === "agent" ? "run" : "system", code: run.failure_code, reason: run.failure_reason } : 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, 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, - activity: run.activity, execution_diagnostics: run.execution_diagnostics, trace_sources: run.trace_sources, - trace_projection: run.trace_projection, trace_generation: run.trace_generation, harness_log: run.harness_log, - job_result: run.job_result ?? null, - run_artifacts: artifacts.filter(item => !["execution_stream", "native_session"].includes(item.kind)).map(item => ({ id: item.id, kind: item.kind, provider: String(item.provider ?? ""), format: String(item.format ?? ""), byte_size: Number(item.byte_size), sha256: String(item.sha256 ?? ""), state: String(item.state ?? ""), media_type: item.media_type ?? null, created_at: item.created_at instanceof Date ? item.created_at.toISOString() : String(item.created_at ?? "") })), }))); + const agentError = run.agent_error_reason + ? { + reason: run.agent_error_reason, + reported_at: run.agent_error_reported_at, + reporter: { + user_id: run.agent_error_reporter_user_id, + kind: run.agent_error_reporter_kind, + id: run.agent_error_reporter_id, + }, + } + : null; + return publicValue( + fullRunResponse, + JSON.parse( + JSON.stringify({ + id: run.id, + tenant_id: run.tenant_id, + job_id: run.job_id, + project_id: run.project_id, + launch_skill_id: run.launch_skill_id, + launch_skill_key: run.launch_skill_key, + launch_skill_revision: run.launch_skill_revision, + 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, + execution_type: run.execution_type ?? run.execution_config?.executionType ?? "agent", + state: run.state, + failure_source: run.failure_source ?? null, + failure: + run.failure_code && run.failure_reason + ? { + source: run.failure_source === "agent" ? "run" : "system", + code: run.failure_code, + reason: run.failure_reason, + } + : 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, + 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, + activity: run.activity, + execution_diagnostics: run.execution_diagnostics, + trace_sources: run.trace_sources, + trace_projection: run.trace_projection, + trace_generation: run.trace_generation, + harness_log: run.harness_log, + job_result: run.job_result ?? null, + run_artifacts: artifacts + .filter((item) => !["execution_stream", "native_session"].includes(item.kind)) + .map((item) => ({ + id: item.id, + kind: item.kind, + provider: String(item.provider ?? ""), + format: String(item.format ?? ""), + byte_size: Number(item.byte_size), + sha256: String(item.sha256 ?? ""), + state: String(item.state ?? ""), + media_type: item.media_type ?? null, + created_at: + item.created_at instanceof Date + ? item.created_at.toISOString() + : String(item.created_at ?? ""), + })), + }), + ), + ); } async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); } async downloadRunArtifact(runId: string, artifactId: string): Promise { @@ -457,36 +715,152 @@ export class ApiService { } async createProject(input: { name: string; description?: string }) { await this.authorize("projects:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } } async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("projects:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; } - async deleteProject(projectId: string) { await this.authorize("projects:write"); const result = await this.projects().remove(projectId); if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); if (result === "nonempty") throw new ServiceError(409, "conflict", "Move or delete the project's jobs before deleting it"); return { id: projectId, deleted: true }; } + async deleteProject(projectId: string) { + await this.authorize("projects:write"); + const result = await this.projects().remove(projectId); + if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); + if (result === "nonempty") + throw new ServiceError(409, "conflict", "The project contains jobs or retained runs"); + return { id: projectId, deleted: true }; + } async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } async testJobConditions(input: unknown) { await this.authorize("jobs:write"); const parsed = jobConditionsTestSchema.parse(input); return evaluateWebhookConditions(parsed.conditions, parsed.webhook); } async createJob(input: JobInput) { - await this.authorize("jobs:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); + await this.authorize("jobs:write"); + const timestamp = new Date().toISOString(), + id = crypto.randomUUID(); const vmImage = input.vmImage ? canonicalizeVmImage(input.vmImage) : input.vmImage; 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 ?? []); + 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 executionConfig = await this.executionConfig(input.executionConfigId); const portable = await this.portableSelections(executionConfig, executionType, input); - const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); - const projectId = input.projectId ?? await this.projects().defaultProjectId(); - const selectedSkills = executionType === "code" ? [] : input.skillIds ? await this.skillSelections(input.skillIds) : []; - const job: Job = { id, projectId, runScopes: input.runScopes ?? [...DEFAULT_RUN_SCOPES], name: input.name, description: input.description ?? "", slug: input.slug, promptTemplate: input.promptTemplate ?? "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...portable, ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...executionConfig, ...portable, 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; } + const triggers = this.normalizedTriggers(input.triggers).map((trigger) => ({ ...trigger, jobId: id })); + const projectId = input.projectId ?? (await this.projects().defaultProjectId()); + const selectedSkills = executionType === "code" ? [] : await this.skillSelections(input.skillIds ?? []); + const launchSkill = + executionType === "agent" && input.launchSkillId + ? (await this.skillSelections([input.launchSkillId]))[0] + : undefined; + const job: Job = { + id, + projectId, + runScopes: input.runScopes ?? [...DEFAULT_RUN_SCOPES], + name: input.name, + description: input.description ?? "", + slug: input.slug, + promptTemplate: input.promptTemplate ?? "", + executionType, + script: executionType === "code" ? input.script : undefined, + runNameTemplate: input.runNameTemplate ?? "", + tags: input.tags ?? [], + model: input.model ?? "", + ...portable, + ...(input.effort ? { effort: input.effort } : {}), + executionConfig: { + ...executionConfig, + launchSkillId: executionType === "agent" ? (input.launchSkillId ?? undefined) : undefined, + ...portable, + executionType, + ...(input.script ? { script: input.script } : {}), + ...(vmImage ? { image: vmImage } : {}), + }, + concurrencyLimit: input.concurrencyLimit, + enabled: true, + triggers, + launchSkill, + 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"); + 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; 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 ?? []); + 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 executionConfig = await this.executionConfig(input.executionConfigId); const portable = await this.portableSelections(executionConfig, executionType, input, current); - const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); - const selectedSkills = executionType === "code" ? [] : input.skillIds === undefined ? current.selectedSkills : await this.skillSelections(input.skillIds); - const updated = await repository.update({ ...current, ...portable, runScopes: input.runScopes ?? current.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: input.projectId ?? current.projectId, name: input.name, description: input.description ?? current.description ?? "", 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: { ...executionConfig, ...portable, 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; }); + const triggers = this.normalizedTriggers(input.triggers, current.triggers).map((trigger) => ({ + ...trigger, + jobId, + })); + const launchSkillId = + input.launchSkillId === undefined ? current.executionConfig.launchSkillId : input.launchSkillId; + const skillIds = input.skillIds ?? (current.selectedSkills ?? []).map((skill) => skill.id); + const selectedSkills = executionType === "code" ? [] : await this.skillSelections(skillIds); + const launchSkill = + executionType === "agent" && launchSkillId + ? (await this.skillSelections([launchSkillId]))[0] + : undefined; + const updated = await repository + .update( + { + ...current, + ...portable, + runScopes: input.runScopes ?? current.runScopes ?? [...DEFAULT_RUN_SCOPES], + projectId: input.projectId ?? current.projectId, + name: input.name, + description: input.description ?? current.description ?? "", + 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: { + ...executionConfig, + launchSkillId: executionType === "agent" ? (launchSkillId ?? undefined) : undefined, + ...portable, + executionType, + ...(input.script ? { script: input.script } : {}), + ...(vmImage ? { image: vmImage } : {}), + }, + concurrencyLimit: input.concurrencyLimit, + triggers, + launchSkill, + 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); } @@ -527,21 +901,210 @@ export class ApiService { async moveJob(jobId: string, projectId: string, expectedUpdatedAt?: string) { await this.authorize("projects:write"); try { return this.presentJob(await this.jobs().move(jobId, projectId, expectedUpdatedAt)); } catch (error) { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload it before moving it."); if (error instanceof Error && error.message === "Project not found") throw new ServiceError(404, "not_found", "Project not found"); if (error instanceof Error && error.message === "Job not found") throw new ServiceError(404, "not_found", "Job not found"); throw error; } } async deleteJob(jobId: string) { await this.authorize("jobs:write"); - const database = databaseFor(this.env), repository = this.jobs(); - if (!await repository.getJob(jobId)) throw new ServiceError(404, "not_found", "Job not found"); - const objectKeys = await new ArtifactRepository(database, this.auth.tenantId).keysForJob(jobId); - if (objectKeys.length && !this.env.RUN_ARTIFACTS) throw new ServiceError(503, "operation_failed", "Artifact storage is unavailable"); - // R2 is outside the PostgreSQL transaction. Delete the objects first and - // retain the database aggregate if object deletion fails so the operation - // can be retried without losing the authoritative object-key inventory. - for (let offset = 0; offset < objectKeys.length; offset += 1_000) await this.env.RUN_ARTIFACTS!.delete(objectKeys.slice(offset, offset + 1_000)); - if (!await repository.delete(jobId)) throw new ServiceError(404, "not_found", "Job not found"); + if (!(await this.jobs().delete(jobId))) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, deleted: true }; } private async wakeScheduler() { if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); } async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } + async setRunDefaults(projectId: string, input: z.infer) { + await this.authorizeOwnerSession("projects:write"); + await this.resolveRunDefaults(input); + const result = await databaseFor(this.env).pool.query( + "UPDATE app.projects SET run_defaults=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING id", + [this.auth.tenantId, projectId, input], + ); + if (!result.rowCount) throw new ServiceError(404, "not_found", "Project not found"); + return input; + } + + private async resolveRunDefaults(input: z.infer) { + await this.validateExecutionOptions( + input.executionConfigId, + input.model ?? "", + input.effort ?? "", + input.tags ?? [], + ); + 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", { + ...input, + modelAccess: input.modelAccountId ? "portable" : undefined, + }); + return { + ...config, + ...portable, + executionType: "agent", + model: input.model ?? "", + effort: input.effort, + tags: input.tags ?? [], + ...(input.vmImage ? { image: input.vmImage } : {}), + runScopes: input.runScopes ?? [], + }; + } + + async startRun(input: z.infer) { + await this.authorize("runs:start"); + const db = databaseFor(this.env), + auth = this.auth; + let projectId = input.projectId; + if (auth.runId) { + const parent = ( + await db.pool.query( + "SELECT project_id FROM app.runs WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked')", + [auth.tenantId, auth.runId], + ) + ).rows[0]; + if (!parent || (projectId && projectId !== parent.project_id)) + throw new ServiceError(403, "forbidden", "Delegation requires an active parent in the same project."); + projectId = parent.project_id; + } + if (!projectId) { + const projects = await this.projects().list({ limit: 2 }); + if (projects.length !== 1) + throw new ServiceError(400, "project_required", "Select a project to start this run."); + projectId = projects[0].id; + } + const caller = [ + auth.authMethod ?? "oauth", + auth.runId ?? auth.vmGrantId ?? auth.accessTokenId ?? auth.oauthGrantId ?? auth.userId, + ].join(":"); + const claim = projectId + ":" + (input.idempotencyKey ?? crypto.randomUUID()); + const digest = ( + await db.pool.query("SELECT encode(sha256(convert_to($1::jsonb::text,'UTF8')),'hex') hash", [ + JSON.stringify({ ...input, projectId }), + ]) + ).rows[0].hash; + const receipt = (runId: string, duplicate: boolean) => ({ + runId, + url: new URL("/job-runs/" + runId, this.env.APP_ORIGIN).href, + outcomeUri: `factorize://runs/${runId}/outcome`, + duplicate, + }); + const existing = async (client: DatabaseClient) => { + const row = ( + await client.query( + `SELECT r.id,i.request_hash FROM app.invocations i JOIN app.runs r ON r.tenant_id=i.tenant_id AND r.invocation_id=i.id + WHERE i.tenant_id=$1 AND i.source='direct' AND i.caller=$2 AND i.claim_key=$3`, + [auth.tenantId, caller, claim], + ) + ).rows[0]; + if (!row) return null; + if (row.request_hash !== digest) + throw new ServiceError( + 409, + "idempotency_conflict", + "This key already identifies a different launch request.", + ); + return receipt(row.id, true); + }; + const prior = await existing(db.pool); + if (prior) return prior; + const project = await this.projects().get(projectId); + if (!project) throw new ServiceError(404, "not_found", "Project not found"); + if (!project.runDefaults) + throw new ServiceError(409, "run_defaults_required", "Configure this project's VM run defaults first."); + const config = await this.resolveRunDefaults(project.runDefaults); + const skill = input.skill ? await this.skills().get(input.skill) : null; + if (input.skill && !skill) throw new ServiceError(404, "not_found", "Launch skill not found"); + const text = + input.inputs && Object.keys(input.inputs).length + ? input.prompt + "\n\nInputs (JSON)\n" + JSON.stringify(input.inputs) + : input.prompt; + const prompt = composePrompt(skill ? [{ body: skill.body! }] : [], text); + const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); + const encryptedSkills = skill + ? await encrypt( + JSON.stringify([ + { id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order: 0 }, + ]), + this.env.CREDENTIAL_ENCRYPTION_KEY, + ) + : 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 duplicate = await existing(client); + if (duplicate) return duplicate; + if (!locked.rows[0]?.matches) + throw new ServiceError( + 409, + "configuration_changed", + "Project configuration 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", + [auth.tenantId, auth.runId, projectId], + ); + if (!active.rowCount) throw new ServiceError(403, "forbidden", "The parent run is no longer active."); + } + const id = crypto.randomUUID(), + invocationId = crypto.randomUUID(), + inputs = input.inputs ?? {}; + await client.query( + `INSERT INTO app.invocations(tenant_id,id,source,claim_key,caller,request_hash,context,source_run_id,source_job_id) + VALUES ($1,$2,'direct',$3,$4,$5,$6,$7,$8)`, + [auth.tenantId, invocationId, claim, caller, digest, inputs, auth.runId, auth.runJobId], + ); + await submitRun(client, auth.tenantId, { + id, + invocationId, + projectId: project.id, + jobId: null, + name: input.name ?? (skill ? `/${skill.key} run` : "Direct run"), + source: "direct", + claim, + encryptedPrompt, + encryptedSkills, + skill: skill ?? undefined, + config: { ...config, inputContext: inputs }, + workspaceName: "", + createdAt: new Date().toISOString(), + }); + await client.query( + "INSERT INTO app.run_authorizations(tenant_id,run_id,user_id,session_version,scopes) VALUES ($1,$2,$3,$4,$5::jsonb)", + [auth.tenantId, id, auth.userId, auth.sessionVersion, JSON.stringify(config.runScopes)], + ); + return receipt(id, false); + }); + await this.wakeScheduler(); + return result; + } + + async outcomeStates(ids: string[]) { + await this.authorize("runs:read"); + const { rows } = await databaseFor(this.env).pool.query<{ id: string; outcome_id: string | null }>( + "SELECT id,outcome_id FROM app.runs WHERE tenant_id=$1 AND id=ANY($2::uuid[])", + [this.auth.tenantId, ids], + ); + if (rows.length !== ids.length) throw new ServiceError(404, "not_found", "Run not found"); + return rows; + } + async runOutcome(runId: string) { + await this.authorize("runs:read"); + const db = databaseFor(this.env); + const result = await db.pool.query( + `SELECT id AS "runId",state,outcome_id AS "eventId",job_result AS result, + CASE WHEN failure_code IS NOT NULL THEN json_build_object('code',failure_code,'reason',failure_reason,'source',CASE WHEN failure_source='agent' THEN 'run' ELSE 'system' END) END failure + FROM app.runs WHERE tenant_id=$1 AND id=$2`, + [this.auth.tenantId, runId], + ); + if (!result.rowCount) throw new ServiceError(404, "not_found", "Run not found"); + const outcome = result.rows[0]; + const artifacts = outcome.eventId ? await new ArtifactRepository(db, this.auth.tenantId).list(runId) : []; + return { + ...outcome, + url: new URL("/job-runs/" + runId, this.env.APP_ORIGIN).href, + artifacts: artifacts + .filter((item) => item.kind === "job_file") + .map((item) => ({ id: item.id, format: item.format })), + }; + } async invokeJob(jobId: string, input: ManualInvocationInput) { await this.authorize("runs:invoke"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); if (this.auth.authMethod === "vendor_identity") { diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 5282f836..54965c02 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -48,6 +48,7 @@ export const jobResponse = z.object({ portableIntegrationIds: z.array(z.guid()).optional(), modelAccess: z.enum(["native", "portable"]).optional(), modelAccountId: z.guid().optional(), githubInstallationIds: z.array(z.number().int().positive()).optional(), linearConnectionId: z.literal("linear").nullable().optional(), xConnectionIds: z.array(z.guid()).optional(), + launchSkillId: z.guid().nullable().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 8ced6e81..9b7c2454 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -7,6 +7,7 @@ export type JobRunState = "queued" | "reserved" | "running" | "succeeded" | "fai export interface ExecutionConfig { executionType?: "agent" | "code"; + launchSkillId?: string; targetId?: string; connectionId: string; workspace: string; @@ -37,6 +38,8 @@ export interface Trigger { updatedAt: string; } +export interface JobSkill { id: string; key: string; revision: number; body: string; position: number } + export interface Job { id: string; projectId?: string; @@ -57,7 +60,8 @@ export interface Job { triggers: Trigger[]; createdAt: string; updatedAt: string; - selectedSkills?: { id: string; key: string; revision: number; body: string; position: number }[]; + launchSkill?: JobSkill; + selectedSkills?: JobSkill[]; portableIntegrationIds?: string[]; modelAccess?: "native" | "portable"; modelAccountId?: string; @@ -99,6 +103,7 @@ export interface JobRun { state: JobRunState; /** Persisted form is encrypted; repositories decrypt only at an authorized read boundary. */ encryptedPrompt: string; + launchSkill?: { id: string; key: string; revision: number }; encryptedSkillSnapshot?: string; runName?: string; createdAt: string; @@ -121,11 +126,16 @@ export class InvocationError extends Error { constructor(public code: "queue_full" | "job_not_found" | "job_disabled" | "invalid_invocation" | "invalid_template", message: string) { super(message); } } -export function renderJobPrompt(job: Pick, context: Record): string { +function promptSkills(job: Pick): JobSkill[] { + const ordered = [...(job.selectedSkills ?? [])].sort((a,b) => a.position-b.position); + return job.launchSkill ? [job.launchSkill, ...ordered.filter(skill => skill.id !== job.launchSkill!.id)] : ordered; +} + +export function renderJobPrompt(job: Pick, context: Record): string { try { Mustache.parse(job.promptTemplate); const rendered = renderTextTemplate(job.promptTemplate, context); - return [...(job.selectedSkills ?? []).sort((a, b) => a.position - b.position).map(skill => skill.body), rendered].join("\n\n"); + return [...promptSkills(job).map(skill => skill.body), rendered].join("\n\n"); } catch (error) { if (error instanceof InvocationError) throw error; throw new InvocationError("invalid_template", "The job prompt is not valid Mustache."); @@ -166,8 +176,8 @@ export class InvocationService { if (!input.triggerId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A trigger and structured context are required."); const createdAt = this.clock(); const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.sourceJobId ? { sourceJobId: input.sourceJobId } : {}), ...(input.sourceRunId ? { sourceRunId: input.sourceRunId } : {}), ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; - const selectedSkills = (job.selectedSkills ?? []).sort((a, b) => a.position - b.position); - const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order: skill.position })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; + const selectedSkills = promptSkills(job); + const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", launchSkill: job.launchSkill, encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map((skill,order) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { const winner = await this.repository.findInvocation(jobId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 09af8e99..2c608a6b 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -1,5 +1,6 @@ import { DEFAULT_RUN_SCOPES } from "../run-scopes"; -import { lockJobQueue, reserveExecutionSlot } from "./queue-admission"; +import { submitRun } from "./run-submission"; +import { lockJobQueue } from "./queue-admission"; import type { Invocation, Job, JobRepository, JobRun, Trigger } from "../job-domain"; import type { Database, DatabaseClient } from "./database"; import { nextOccurrence, validateScheduleConfig } from "../schedule"; @@ -28,13 +29,17 @@ export class PostgresJobRepository implements JobRepository { if (db === this.database.orm) { [triggerRows, skillRows] = await Promise.all([ loadedTriggers ?? db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id), - loadedSkills?.filter(skill => skill.job_id === row.id) ?? 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]).then(result => result.rows), + loadedSkills?.filter(skill => skill.job_id === row.id) ?? this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,js.position,js.context_skill 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]).then(result => result.rows), ]); } else { triggerRows = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); - skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (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; + skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position,js.context_skill 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, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", 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, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, xConnectionIds: row.executionConfig.xConnectionIds ?? [], 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() }; + const skills = await Promise.all(skillRows.map(async skill => ({ + id:skill.id, key:skill.key, revision:skill.revision, position:skill.position, body:await this.decrypt(skill.encrypted_body), + }))); + const launchSkill = skills.find(skill=>skill.id === row.executionConfig.launchSkillId); + return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", 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, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, xConnectionIds: row.executionConfig.xConnectionIds ?? [], concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), launchSkill, selectedSkills: skills.filter((_,index)=>skillRows[index].context_skill !== false), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { @@ -140,7 +145,8 @@ export class PostgresJobRepository implements JobRepository { } } private async reconcileSkills(tx: any, job: Job, _existing: unknown[]): Promise { - const selected = job.selectedSkills ?? []; + const context = job.selectedSkills ?? []; + const selected = job.launchSkill && !context.some(skill => skill.id === job.launchSkill!.id) ? [...context,job.launchSkill] : context; const ids = selected.map(skill => skill.id); if (new Set(ids).size !== ids.length) throw new Error("A skill may only be selected once per job"); if (ids.length) { @@ -148,19 +154,11 @@ export class PostgresJobRepository implements JobRepository { if (found.rows.length !== ids.length) throw new Error("One or more selected skills are unavailable"); } await tx.execute(sql`DELETE FROM app.job_skills WHERE tenant_id=${this.tenantId}::uuid AND job_id=${job.id}::uuid`); - for (const [position, skill] of selected.entries()) await tx.execute(sql`INSERT INTO app.job_skills(tenant_id,job_id,skill_id,position) VALUES(${this.tenantId}::uuid,${job.id}::uuid,${skill.id}::uuid,${position})`); + for (const [position, skill] of selected.entries()) await tx.execute(sql`INSERT INTO app.job_skills(tenant_id,job_id,skill_id,position,context_skill) VALUES(${this.tenantId}::uuid,${job.id}::uuid,${skill.id}::uuid,${position},${position < context.length})`); } async delete(id: string): Promise { return this.database.transaction(async client => { - // Preserve provider cleanup ownership before job deletion cascades through - // runs. This durable queue has no FK to the job or tenant by design. - await client.query(`INSERT INTO app.deleted_job_provider_cleanup - (tenant_id,run_id,execution_config,execution_backend_kind,execution_handle,started_at) - SELECT x.tenant_id,x.id,x.execution_config,x.execution_backend_kind,x.execution_handle,jr.started_at - FROM app.runs x JOIN app.job_runs jr ON jr.tenant_id=x.tenant_id AND jr.id=x.id - WHERE x.tenant_id=$1 AND x.job_id=$2 AND NOT x.vm_cleanup_complete - ON CONFLICT (tenant_id,run_id) DO NOTHING`, [this.tenantId, id]); const result = await client.query("DELETE FROM app.jobs WHERE tenant_id=$1 AND id=$2 RETURNING id", [this.tenantId, id]); return result.rowCount === 1; }); @@ -176,16 +174,13 @@ export class PostgresJobRepository implements JobRepository { const concurrencyLimit = await lockJobQueue(client, this.tenantId, invocation.jobId); const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,source_job_id,source_run_id,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.sourceJobId ?? null, invocation.sourceRunId ?? null, invocation.createdAt]); if (!inserted.rowCount) return false; - await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); - await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,encrypted_skill_snapshot,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.encryptedSkillSnapshot ?? null, run.runName ?? "", run.createdAt, run.updatedAt]); - 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->>'executionProvider'='docker' THEN 'docker' 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,'inputContext',i.context,'runScopes',j.run_scopes), - CASE WHEN j.execution_config->>'agentKind'='Amp' THEN '["stop"]'::jsonb ELSE '["recovery","stop"]'::jsonb END,1,$9,$10 - 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()"); + const job = (await client.query("SELECT project_id, slug, execution_config, model, effort, tags, run_scopes FROM app.jobs WHERE tenant_id=$1 AND id=$2", [this.tenantId, invocation.jobId])).rows[0]; + run.state = await submitRun(client, this.tenantId, { + id: run.id, jobId: invocation.jobId, projectId: job.project_id, invocationId: invocation.id, name: run.runName ?? "", + source: invocation.source, claim: invocation.claimKey, encryptedPrompt: run.encryptedPrompt, encryptedSkills: run.encryptedSkillSnapshot, + skill: run.launchSkill, workspaceName: job.slug, jobLimit: concurrencyLimit, createdAt: run.createdAt, + config: {...job.execution_config, model: job.model, effort: job.effort, tags: job.tags, inputContext: invocation.context, runScopes: job.run_scopes}, + }); return true; }); } diff --git a/packages/api/src/postgres/project-repository.ts b/packages/api/src/postgres/project-repository.ts index cc7c28dc..503af3d9 100644 --- a/packages/api/src/postgres/project-repository.ts +++ b/packages/api/src/postgres/project-repository.ts @@ -1,13 +1,15 @@ +import type { z } from "zod"; +import type { projectRunDefaults } from "../flow-schemas"; import type { Database } from "./database"; -export interface Project { id: string; name: string; description?: string; createdAt: string; updatedAt: string; jobCount: number; } +export interface Project { runDefaults?: z.infer; id: string; name: string; description?: string; createdAt: string; updatedAt: string; jobCount: number; } export class ProjectRepository { constructor(private database: Database, private tenantId: string) {} - private map(row: any): Project { return { id: row.id, name: row.name, ...(row.description ? { description: row.description } : {}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), jobCount: Number(row.job_count ?? 0) }; } + private map(row: any): Project { return { ...(row.run_defaults ? {runDefaults:row.run_defaults} : {}), id: row.id, name: row.name, ...(row.description ? { description: row.description } : {}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), jobCount: Number(row.job_count ?? 0) }; } async list(options: { limit?: number; sort?: "name" | "updated" } = {}) { const limit = Math.max(1, Math.min(100, options.limit ?? 100)); const order = options.sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.name,p.id"; const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 GROUP BY p.tenant_id,p.id ORDER BY ${order} LIMIT $2`, [this.tenantId, limit]); return result.rows.map(row => this.map(row)); } async get(id: string) { const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 AND p.id=$2 GROUP BY p.tenant_id,p.id`, [this.tenantId,id]); return result.rows[0] ? this.map(result.rows[0]) : null; } async defaultProjectId() { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,md5(($1::uuid)::text || ':default')::uuid,'Default','Jobs created by legacy clients') ON CONFLICT (tenant_id,name) DO UPDATE SET updated_at=app.projects.updated_at RETURNING id`, [this.tenantId]); return result.rows[0].id as string; } async create(name: string, description?: string) { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,gen_random_uuid(),$2,$3) RETURNING *`, [this.tenantId,name.trim(),description?.trim() || null]); return this.map({ ...result.rows[0], job_count: 0 }); } async update(id: string, name: string, description?: string) { const result = await this.database.pool.query(`UPDATE app.projects SET name=$3,description=$4,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING *`, [this.tenantId,id,name.trim(),description?.trim() || null]); return result.rows[0] ? this.map({ ...result.rows[0], job_count: 0 }) : null; } - async remove(id: string) { return this.database.transaction(async client => { const project = await client.query(`SELECT id FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE`, [this.tenantId,id]); if (!project.rows.length) return "missing" as const; const jobs = await client.query(`SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND project_id=$2 LIMIT 1`, [this.tenantId,id]); if (jobs.rows.length) return "nonempty" as const; await client.query(`DELETE FROM app.projects WHERE tenant_id=$1 AND id=$2`, [this.tenantId,id]); return "deleted" as const; }); } + async remove(id: string) { return this.database.transaction(async client => { const project = await client.query(`SELECT id FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE`, [this.tenantId,id]); if (!project.rows.length) return "missing" as const; const jobs = await client.query(`SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND project_id=$2 UNION ALL SELECT 1 FROM app.runs WHERE tenant_id=$1 AND project_id=$2 LIMIT 1`, [this.tenantId,id]); if (jobs.rows.length) return "nonempty" as const; await client.query(`DELETE FROM app.projects WHERE tenant_id=$1 AND id=$2`, [this.tenantId,id]); return "deleted" as const; }); } } diff --git a/packages/api/src/postgres/queue-admission.ts b/packages/api/src/postgres/queue-admission.ts index 13178f33..19fcba1b 100644 --- a/packages/api/src/postgres/queue-admission.ts +++ b/packages/api/src/postgres/queue-admission.ts @@ -8,19 +8,21 @@ export async function lockJobQueue(client: DatabaseClient, tenantId: string, job } /** Check after claiming the occurrence so duplicate retries still return their original run. */ -export async function reserveExecutionSlot(client: DatabaseClient, tenantId: string, jobId: string, run: { state: string }, concurrencyLimit: number): Promise { +export async function reserveExecutionSlot(client: DatabaseClient, tenantId: string, jobId: string, run: { state: string }, concurrencyLimit: number, available = Number.POSITIVE_INFINITY): Promise { const activeStates = "('reserved','starting','running','blocked','stopping')"; // A newly free slot belongs to the oldest waiter before it belongs to a new arrival. - while (true) { + while (available > 0) { const active = await client.query<{ count: string }>(`SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ${activeStates}`, [tenantId, jobId]); if (Number(active.rows[0]?.count ?? 0) >= concurrencyLimit) break; const promoted = await client.query(`UPDATE app.job_runs SET state='reserved',updated_at=now() WHERE tenant_id=$1 AND id=(SELECT id FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state='queued' ORDER BY created_at,id FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING id`, [tenantId, jobId]); if (!promoted.rowCount) break; + await client.query("UPDATE app.runs SET state='reserved',updated_at=now() WHERE tenant_id=$1 AND id=$2", [tenantId,promoted.rows[0].id]); + available--; } const active = await client.query<{ count: string }>(`SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ${activeStates}`, [tenantId, jobId]); - if (Number(active.rows[0]?.count ?? 0) < concurrencyLimit) { + if (available > 0 && Number(active.rows[0]?.count ?? 0) < concurrencyLimit) { run.state = "reserved"; return; } diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 69012032..8dad1104 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -5,7 +5,7 @@ const encodeCursor = (value: unknown[]) => btoa(JSON.stringify(value)).replaceAl const decodeCursor = (value?: string | null): unknown[] | null => { if (!value) return null; try { const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4), parsed = JSON.parse(atob(padded)); return Array.isArray(parsed) ? parsed : null; } catch { return null; } }; const sortExpressions = { - job: "j.name", + job: "COALESCE(j.name,r.source_job_name)", run: "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run')", status: "r.state", created: "r.created_at", @@ -20,9 +20,12 @@ export class RunQueryRepository { async list(query: URLSearchParams) { const limit = Math.max(1, Math.min(100, Number(query.get("limit") ?? 50))), cursor = decodeCursor(query.get("cursor")), sortParam = query.get("sort"), sort = sortParam && Object.hasOwn(sortExpressions, sortParam) ? sortParam as RunSort : null, direction = sort ? (query.get("direction") === "desc" ? "DESC" : "ASC") : "DESC", values: unknown[] = [this.tenantId], clauses = ["r.tenant_id=$1"]; const projectIds = query.getAll("projectId"); - if (projectIds.length) { values.push(projectIds); clauses.push(`j.project_id=ANY($${values.length}::uuid[])`); } + if (projectIds.length) { values.push(projectIds); clauses.push(`r.project_id=ANY($${values.length}::uuid[])`); } const jobIds = query.getAll("jobId"); if (jobIds.length) { values.push(jobIds); clauses.push(`r.job_id=ANY($${values.length}::uuid[])`); } + const skill = query.get("launchSkillId"); + if (skill === "none") clauses.push("r.launch_skill_id IS NULL"); + else if (skill) { values.push(skill); clauses.push(`r.launch_skill_id=$${values.length}::uuid`); } const states = query.getAll("state"); if (states.length) { values.push(states.flatMap(state => state === "done" ? ["done", "succeeded"] : [state])); clauses.push(`r.state=ANY($${values.length}::text[])`); } if (query.get("contextQuery")) { values.push(`%${query.get("contextQuery")}%`); clauses.push(`i.context::text ILIKE $${values.length}`); } @@ -40,13 +43,13 @@ 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}` : `${runPrioritySql} ASC,r.created_at DESC,r.id DESC`; - const selectedOrder = sort ? order.replaceAll("r.", "selected.").replaceAll("j.name", "selected.job_name") : "selected.priority ASC,selected.created_at DESC,selected.id DESC"; + const selectedOrder = sort ? order.replaceAll(sortExpressions.job, "selected.job_name").replaceAll("r.", "selected.") : "selected.priority ASC,selected.created_at DESC,selected.id DESC"; const result = await this.database.pool.query(`WITH selected AS MATERIALIZED ( - 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,${runPrioritySql} priority,r.failure_source,r.failure_code,r.failure_reason, + SELECT r.id,r.job_id,r.launch_skill_id,r.launch_skill_key,r.launch_skill_revision,r.project_id,COALESCE(j.name,r.source_job_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,${runPrioritySql} priority,r.failure_source,r.failure_code,r.failure_reason, CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure, 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,jr.updated_at job_run_updated_at - FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_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 + FROM app.runs r LEFT JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=r.tenant_id AND p.id=r.project_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 ${clauses.join(" AND ")} ORDER BY ${order} LIMIT $${values.length} ), page AS MATERIALIZED ( SELECT id,job_id,state,started_at,job_run_updated_at FROM selected ORDER BY ${selectedOrder} LIMIT ($${values.length} - 1) @@ -60,7 +63,7 @@ export class RunQueryRepository { AND completed.started_at IS NOT NULL AND completed.updated_at>=completed.started_at GROUP BY completed.job_id ) - SELECT selected.id,selected.job_id,selected.project_id,selected.job_name,selected.project_name,selected.issue_id,selected.issue_url,selected.issue_title,selected.run_name,selected.agent_name,selected.workspace_name,selected.agent_kind,selected.execution_type,selected.state,selected.failure_source,selected.failure_code,selected.failure_reason,selected.failure,selected.agent_error, + SELECT selected.id,selected.job_id,selected.launch_skill_id,selected.launch_skill_key,selected.launch_skill_revision,selected.project_id,selected.job_name,selected.project_name,selected.issue_id,selected.issue_url,selected.issue_title,selected.run_name,selected.agent_name,selected.workspace_name,selected.agent_kind,selected.execution_type,selected.state,selected.failure_source,selected.failure_code,selected.failure_reason,selected.failure,selected.agent_error, selected.provider,selected.backend_kind,selected.capabilities,selected.destination_url,selected.artifact_state,selected.artifact_error,selected.created_at,selected.updated_at,selected.started_at, CASE WHEN selected.state IN ('succeeded','failed','stopped') AND selected.started_at IS NOT NULL AND selected.job_run_updated_at>=selected.started_at THEN json_build_object('duration',round(EXTRACT(EPOCH FROM (selected.job_run_updated_at-selected.started_at)))) @@ -77,17 +80,17 @@ export class RunQueryRepository { return { items: rows, nextCursor }; } async get(runId: string) { - 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; + return (await this.database.pool.query(`SELECT r.*,coalesce(r.execution_config->>'executionType','agent') execution_type,COALESCE(j.name,r.source_job_name) job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.origin_trigger_id invocation_trigger_id,i.template_job_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 LEFT 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,r.failure_code,r.failure_reason,CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure,coalesce(r.execution_config->>'executionType','agent') execution_type, + const row = (await this.database.pool.query(`SELECT r.id,r.job_id,r.launch_skill_id,r.launch_skill_key,r.launch_skill_revision,r.project_id,pr.name project_name,jr.state,r.run_name,COALESCE(j.name,r.source_job_name) job_name,r.destination_url,r.failure_source,r.failure_code,r.failure_reason,CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure,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, ${traceRevisionSql} trace_revision - FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id - JOIN app.projects pr ON pr.tenant_id=j.tenant_id AND pr.id=j.project_id + FROM app.runs r LEFT JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id + JOIN app.projects pr ON pr.tenant_id=r.tenant_id AND pr.id=r.project_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id LEFT JOIN app.run_trace_cursors c ON c.tenant_id=r.tenant_id AND c.run_id=r.id LEFT JOIN app.run_trace_projections p ON p.tenant_id=r.tenant_id AND p.run_id=r.id diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index b6b2b71a..93ae2e8e 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -6,7 +6,7 @@ import type { Database, DatabaseClient } from "./database"; import type { JobResult } from "../job-result"; export interface PersistedRun { - tenantId: string; id: string; jobId: string; invocationId: string; state: ExecutionState; + tenantId: string; id: string; jobId: string | null; invocationId: string; state: ExecutionState; encryptedPrompt: string; executionConfig: Record; executionHandle: RunHandle | null; traceSources?: TraceSources | null; executionDiagnostics?: ExecutionDiagnostics | null; finalizationAttempt?: number; failureCode?: string | null; failureReason?: string | null; @@ -15,7 +15,7 @@ export interface PersistedRun { export interface RunFailure { source: "run" | "system"; code: string; reason: string } interface RunRow { - tenant_id: string; id: string; job_id: string; invocation_id: string; state: ExecutionState; encrypted_prompt: string; + tenant_id: string; id: string; job_id: string | null; invocation_id: string; state: ExecutionState; encrypted_prompt: string; execution_config: Record; execution_handle: RunHandle | null; execution_backend_kind: string; failure_code?: string | null; failure_reason?: string | null; trace_sources: TraceSources | null; execution_diagnostics: ExecutionDiagnostics | null; vm_cleanup_attempt: number; @@ -44,17 +44,25 @@ export class RunRepository { return this.database.transaction(async client => { // Retry expired launches in their existing active slot. Requeuing them // would compete with the single waiting run and could overflow the queue. - const result = await client.query(`WITH candidate AS ( - SELECT r.tenant_id,r.id FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id - WHERE j.enabled AND ((r.state='starting' AND r.launch_lease_expires_at>'capacity')::int) + AND (r.job_id IS NULL OR (SELECT count(*) FROM app.job_runs active WHERE active.tenant_id=r.tenant_id AND active.job_id=r.job_id AND active.state IN ('reserved','starting','running','blocked','stopping')) < j.concurrency_limit)))`; + const candidate = (await client.query(`SELECT p.tenant_id,p.id ${eligible} + ORDER BY r.created_at,r.id FOR UPDATE OF p SKIP LOCKED LIMIT 1`)).rows[0]; + if (!candidate) return null; + const result = await client.query(`WITH candidate AS ( + SELECT r.tenant_id,r.id ${eligible} AND p.tenant_id=$1 AND p.id=$2 + ORDER BY r.created_at,r.id FOR UPDATE OF r SKIP LOCKED LIMIT 1 ), claimed AS ( UPDATE app.job_runs r SET state='starting',launch_lease_expires_at=now()+interval '5 minutes',updated_at=now() FROM candidate c WHERE r.tenant_id=c.tenant_id AND r.id=c.id RETURNING r.* ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at - FROM claimed c JOIN app.jobs j ON j.tenant_id=c.tenant_id AND j.id=c.job_id JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, []); + FROM claimed c JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, [candidate.tenant_id,candidate.id]); const row = result.rows[0]; if (!row) return null; await client.query("UPDATE app.runs SET state='starting',updated_at=now() WHERE tenant_id=$1 AND id=$2", [row.tenant_id, row.id]); @@ -64,7 +72,7 @@ export class RunRepository { async dueForPoll(limit = 40): Promise { const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,r.created_at,r.updated_at - FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.runs x ON x.tenant_id=r.tenant_id AND x.id=r.id + FROM app.job_runs r JOIN app.runs x ON x.tenant_id=r.tenant_id AND x.id=r.id WHERE r.state IN ('running','blocked','stopping') AND x.execution_handle IS NOT NULL AND (r.next_poll_at IS NULL OR r.next_poll_at<=now()) ORDER BY r.next_poll_at NULLS FIRST,r.updated_at LIMIT $1`, [limit]); return result.rows.map(mapped); } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index df570c9c..c92c1de8 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -163,7 +163,7 @@ export class RunScheduler { const app = `factorize-run-${run.tenantId.replaceAll("-", "")}`; const machines = createFlyMachinesClient({ token: connection }); return new FlyJobExecutionBackend({ - app, organizationSlug: connectionDetails.organizationSlug, image: configuration.image, region: configuration.region, size: configuration.size, + app, organizationSlug: connectionDetails.organizationSlug, image: run.executionConfig.image ?? configuration.image, region: run.executionConfig.region ?? configuration.region, size: run.executionConfig.size ?? configuration.size, machines, guest: machine => flyJobGuest({ app, machine: machine.id, token: connection }), prepare: () => machines.ensureRunApp(app, connectionDetails.organizationSlug), vendorIdentityAudience: runId => `factorize://runs/${runId}`, diff --git a/packages/api/src/postgres/run-submission.ts b/packages/api/src/postgres/run-submission.ts new file mode 100644 index 00000000..d9bdf46d --- /dev/null +++ b/packages/api/src/postgres/run-submission.ts @@ -0,0 +1,99 @@ +import type { DatabaseClient } from "./database"; +import { reserveExecutionSlot } from "./queue-admission"; +import { InvocationError } from "../job-domain"; + +export interface SubmittedRun { + id: string; + invocationId: string; + jobId: string | null; + projectId: string; + name: string; + source: string; + claim: string; + encryptedPrompt: string; + encryptedSkills?: string; + skill?: { id: string; key: string; revision: number }; + config: Record; + workspaceName: string; + createdAt: string; + jobLimit?: number; +} + +/** The invocation claim, capacity decision, paired execution rows, authorization + * and scheduler wake all commit in the caller's admission transaction. */ +export async function submitRun(client: DatabaseClient, tenant: string, run: SubmittedRun) { + const project = ( + await client.query("SELECT run_defaults FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [ + tenant, + run.projectId, + ]) + ).rows[0]; + if (!project) throw new Error("Run project is unavailable"); + const capacity = project.run_defaults?.capacity; + let available = Number.POSITIVE_INFINITY; + if (capacity) { + const { rows } = await client.query( + `SELECT count(*) FILTER (WHERE jr.state IN ('reserved','starting','running','blocked','stopping'))::int active, + count(*) FILTER (WHERE jr.state='queued')::int waiting FROM app.runs r JOIN app.job_runs jr USING (tenant_id,id) + WHERE r.tenant_id=$1 AND r.project_id=$2`, + [tenant, run.projectId], + ); + available = Math.max(0, capacity - rows[0].active); + if (!available && rows[0].waiting >= capacity) + throw new InvocationError("queue_full", "The project's run queue is full."); + } + const reservation = { state: available ? "reserved" : "queued" }; + if (run.jobId) + await reserveExecutionSlot(client, tenant, run.jobId, reservation, run.jobLimit ?? 1, available); + await client.query( + `INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,encrypted_skill_snapshot,run_name,created_at,updated_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$9)`, + [ + tenant, + run.id, + run.jobId, + run.invocationId, + reservation.state, + run.encryptedPrompt, + run.encryptedSkills ?? null, + run.name, + run.createdAt, + ], + ); + const provider = run.config.executionProvider; + const backend = + provider === "fly" || provider === "docker" + ? provider + : run.config.agentKind === "Amp" + ? "amp" + : "exe-vm"; + await client.query( + `INSERT INTO app.runs(tenant_id,id,project_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,launch_skill_id,launch_skill_key,launch_skill_revision,created_at,updated_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'',$9,$10,$11,$12,$13,$14,1,$15,$16,$17,$18,$18)`, + [ + tenant, + run.id, + run.projectId, + run.jobId, + run.invocationId, + run.source, + run.claim, + run.name, + run.workspaceName, + run.config.agentKind, + reservation.state, + backend, + run.config, + JSON.stringify(backend === "amp" ? ["stop"] : ["recovery", "stop"]), + run.skill?.id, + run.skill?.key, + run.skill?.revision, + run.createdAt, + ], + ); + 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)", + ); + return reservation.state as "queued" | "reserved"; +} diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 6a4fa537..92a866ba 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -94,7 +94,7 @@ export const modelDeviceAuthorizations = app.table("model_device_authorizations" export const linearWorkspaces = app.table("linear_workspaces", { organizationId: uuid("organization_id").primaryKey(), tenantId: uuid("tenant_id").notNull().unique().references(() => tenants.id, { onDelete: "cascade" }) }); 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", { 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 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 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(), @@ -105,7 +105,7 @@ export const vmImageVerifications = app.table("vm_image_verifications", { export const skills = app.table("skills", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), encryptedBody: text("encrypted_body").notNull(), revision: integer("revision").notNull().default(1), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.key)]); -export const jobSkills = app.table("job_skills", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.skillId] }), unique().on(t.tenantId, t.jobId, t.position), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); +export const jobSkills = app.table("job_skills", { contextSkill:boolean("context_skill").notNull().default(true), tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.skillId] }), unique().on(t.tenantId, t.jobId, t.position), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle','jobIdle')`)]); @@ -114,18 +114,20 @@ export const webhookConditionsCutover = app.table("webhook_conditions_cutover", tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), wasEnabled: boolean("was_enabled").notNull(), conditions: jsonb("conditions").$type>().notNull(), restoredAt: timestamp("restored_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade")]); export const invocations = app.table("invocations", { - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), source: text("source").$type().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), sourceJobId: uuid("source_job_id"), sourceRunId: uuid("source_run_id"), createdAt: createdAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle','jobIdle')`), index("invocations_source_run").on(t.tenantId, t.sourceRunId).where(sql`${t.sourceRunId} is not null`)]); + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id"), source: text("source").$type().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id"), templateJobId:uuid("template_job_id"),originTriggerId:uuid("origin_trigger_id"),caller:text("caller"), requestHash:text("request_hash"), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), sourceJobId: uuid("source_job_id"), sourceRunId: uuid("source_run_id"), createdAt: createdAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("set null"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("set null"), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle','jobIdle','direct')`), index("invocations_source_run").on(t.tenantId, t.sourceRunId).where(sql`${t.sourceRunId} is not null`)]); export const manualInvocationPermissions = app.table("manual_invocation_permissions", { tenantId: uuid("tenant_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), destinationJobId: uuid("destination_job_id").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.sourceJobId, t.destinationJobId] }), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.destinationJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("manual_invocation_permissions_destination").on(t.tenantId, t.destinationJobId)]); export const jobRuns = app.table("job_runs", { - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), state: text("state").$type<"queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped">().notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`), index("job_runs_by_job_history").on(t.tenantId, t.jobId, t.createdAt.desc(), t.id.desc(), t.state), index("job_runs_active_by_job").on(t.tenantId, t.jobId).where(sql`${t.state} in ('reserved','starting','running','blocked','stopping')`)]); + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id"), invocationId: uuid("invocation_id").notNull(), state: text("state").$type<"queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped">().notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("set null"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`), index("job_runs_by_job_history").on(t.tenantId, t.jobId, t.createdAt.desc(), t.id.desc(), t.state), index("job_runs_active_by_job").on(t.tenantId, t.jobId).where(sql`${t.state} in ('reserved','starting','running','blocked','stopping')`)]); export const runs = app.table("runs", { + projectId: uuid("project_id").notNull(), sourceJobName:text("source_job_name"), outcomeId:uuid("outcome_id"), + launchSkillId:uuid("launch_skill_id"), launchSkillKey:text("launch_skill_key"), launchSkillRevision:integer("launch_skill_revision"), encryptedLaunchPayload: text("encrypted_launch_payload"), executionConfig: jsonb("execution_config").$type().notNull(), - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), failureCode: text("failure_code"), failureReason: text("failure_reason"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), providerCleanupAttempt: integer("provider_cleanup_attempt").notNull().default(0), providerCleanupNextAt: timestamp("provider_cleanup_next_at", { withTimezone: true }), providerCleanupError: text("provider_cleanup_error"), createdAt: createdAt(), updatedAt: updatedAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_priority_order").on(t.tenantId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_priority_job_order").on(t.tenantId, t.jobId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id"), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), failureCode: text("failure_code"), failureReason: text("failure_reason"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), providerCleanupAttempt: integer("provider_cleanup_attempt").notNull().default(0), providerCleanupNextAt: timestamp("provider_cleanup_next_at", { withTimezone: true }), providerCleanupError: text("provider_cleanup_error"), createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("set null"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_priority_order").on(t.tenantId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_priority_job_order").on(t.tenantId, t.jobId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); export const runArtifacts = app.table("run_artifacts", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), sourceGeneration: text("source_generation"), sourcePath: text("source_path"), mediaType: text("media_type"), harnessVersion: text("harness_version"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.objectKey), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_artifacts_by_run").on(t.tenantId, t.runId, t.createdAt, t.id)]); diff --git a/packages/api/src/project-contracts.ts b/packages/api/src/project-contracts.ts index 3a35d95a..c78aeaca 100644 --- a/packages/api/src/project-contracts.ts +++ b/packages/api/src/project-contracts.ts @@ -1,5 +1,6 @@ import { z } from "zod"; -export const projectResponse = z.object({ id: z.guid(), name: z.string(), description: z.string().optional(), createdAt: z.string(), updatedAt: z.string(), jobCount: z.number().int() }); +import { storedRunDefaults } from "./flow-schemas"; +export const projectResponse = z.object({ id: z.guid(), name: z.string(), description: z.string().optional(), createdAt: z.string(), updatedAt: z.string(), runDefaults:storedRunDefaults.optional(), jobCount: z.number().int() }); export const projectListQuery = z.object({ limit: z.coerce.number().int().min(1).max(100).default(100), sort: z.enum(["name", "updated"]).default("name"), diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 043dd4c0..04c09b01 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,5 @@ +import { listenForOutcomes, outcomeRunId } from "./run-outcome-subscription"; +import { authenticateVendorRunRequest } from "./vendor-run-auth"; import { Hono } from "hono"; import { AgentApiError } from "./agent-api"; import { grantVmInput, revokeVmInput } from "./agent-api-contracts"; @@ -6,11 +8,11 @@ import { queryOf } from "./query-params"; import { jobUpdateInput } from "./job-contracts"; import { InvocationError } from "./job-domain"; import { WorkerEntrypoint } from "cloudflare:workers"; -import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"; +import { createMcpHandler, McpServer, ResourceTemplate } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; -import { jobConditionsTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, renameRunSchema, reportRunErrorSchema, runIdSchema } from "./flow-schemas"; +import { startRunInput,jobConditionsTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, renameRunSchema, reportRunErrorSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; import { executeAuth, validBrowserOrigin } from "./auth-api"; import { matchApiOperation } from "./api-contract"; @@ -72,6 +74,17 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP let body: any; try { body = await new Response(limited).json(); } catch(error) { if(error instanceof ServiceError) throw error; throw new ServiceError(400,"invalid_request","Request body must be valid JSON."); } mcpBodies.set(request,body); + if (body?.method === "subscriptions/listen" && body.params?.notifications?.resourceSubscriptions) { + const credentialActive = async () => { + if (auth.authMethod === "vendor_identity") return !!await authenticateVendorRunRequest(request,env); + if (auth.oauthGrantId) { + const token = await env.OAUTH_PROVIDER?.unwrapToken(request.headers.get("Authorization")?.slice(7) ?? ""); + return token?.grantId === auth.oauthGrantId && token.expiresAt > Date.now()/1000 && normalizeScopes(token.scope).includes("runs:read"); + } + return true; // outcomeStates rechecks API key and owner membership. + }; + listeners.set(request,() => listenForOutcomes(request,body,mcpService,()=>createMcpServer(mcpService),credentialActive,ctx).catch(error => errorResponse(error,env.APP_ORIGIN))); + } } return await mcp(request, mcpService, env, ctx); } @@ -113,12 +126,17 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP } catch (error) { return timed(errorResponse(error, env.APP_ORIGIN)); } } +const listeners = new WeakMapPromise>(); const mcpBodies = new WeakMap(); const mcpServices = new WeakMap(); -function createMcpServer(service: ApiService): McpServer { - const server = new McpServer({ name: "factorize", version: "1.0.0" }); +function createMcpServer(service: ApiService, subscriptions = true): McpServer { + const server = new McpServer({ name: "factorize", version: "1.0.0" }, {capabilities:{resources:{subscribe:subscriptions}}}); + server.registerResource("run-outcome",new ResourceTemplate("factorize://runs/{runId}/outcome",{list:undefined}), + {mimeType:"application/json",description:"Pending or terminal outcome of an authorized run"},async uri=>({ + contents:[{uri:uri.href,mimeType:"application/json",text:JSON.stringify(await service.runOutcome(outcomeRunId(uri.href)))}], + })); const tool = (name: string, description: string, schema: any, action: (input: T) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T) => { try { return structured(await action(input)); } catch (error) { const response = errorResponse(error), detail = await response.json() as any; throw new Error(`${detail.error?.code ?? "operation_failed"}: ${detail.error?.message ?? "Operation failed"}`); } @@ -153,9 +171,10 @@ function createMcpServer(service: ApiService): McpServer { tool("create_job", "Create a job using a saved execution integration ID. Credentials are never accepted or returned.", jobInputSchema, (input: any) => service.createJob(input)); tool("update_job", "Replace a job configuration. Credentials are never accepted or returned.", jobUpdateInput.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.updateJob(jobId, input)); tool("move_job", "Move a job between tenant projects without changing its execution configuration", z.object({ jobId: z.string().min(1), projectId: z.string().min(1), expectedUpdatedAt: z.string().optional() }), ({ jobId, projectId, expectedUpdatedAt }: any) => service.moveJob(jobId, projectId, expectedUpdatedAt)); - tool("delete_job", "Delete a job and its queued invocation history", jobIdSchema, ({ jobId }: any) => service.deleteJob(jobId)); + 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("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)); @@ -171,10 +190,10 @@ function createMcpServer(service: ApiService): McpServer { // The SDK owns the request-scoped transport/server lifecycle. The factory only // resolves the service for the request being served, so tenant context cannot // leak between concurrent MCP calls. -const mcpHandler = createMcpHandler(({ requestInfo }) => { +const mcpHandler = createMcpHandler(({ requestInfo, era }) => { const service = requestInfo && mcpServices.get(requestInfo); if (!service) throw new Error("MCP request context is unavailable"); - return createMcpServer(service); + return createMcpServer(service,era === "modern"); }); const mcpApps = new Map(); @@ -182,7 +201,7 @@ function mcpAppFor(hostname: string) { let app = mcpApps.get(hostname); if (!app) { const protocol = createMcpHonoApp({ host: hostname, allowedHosts: [hostname], allowedOrigins: [hostname] }); - protocol.all("/mcp", c => mcpHandler.fetch(c.req.raw, { parsedBody: (c as any).get("parsedBody") })); + protocol.all("/mcp", c => listeners.get(c.req.raw)?.() ?? mcpHandler.fetch(c.req.raw, { parsedBody: (c as any).get("parsedBody") })); app = new Hono(); app.use("*",async(c,next)=> { if(mcpBodies.has(c.req.raw)) (c as any).set("parsedBody",mcpBodies.get(c.req.raw)); await next(); }); app.route("/",protocol); diff --git a/packages/api/src/run-outcome-subscription.ts b/packages/api/src/run-outcome-subscription.ts new file mode 100644 index 00000000..82235f88 --- /dev/null +++ b/packages/api/src/run-outcome-subscription.ts @@ -0,0 +1,50 @@ +import { createMcpHandler, type McpServer } from "@modelcontextprotocol/server"; +import { z } from "zod"; +import { ApiService, ServiceError } from "./flow-service"; + +const uriPrefix = "factorize://runs/"; +export function outcomeRunId(uri: string) { + const id = uri.slice(uriPrefix.length, -"/outcome".length); + if (!z.guid().safeParse(id).success || uri !== uriPrefix + id + "/outcome") + throw new ServiceError(400, "invalid_resource", "Expected a run outcome URI."); + return id; +} + +// One SDK listen stream belongs to one authenticated request. Read the +// committed outcome IDs from PostgreSQL so a scheduler in any isolate can +// wake this stream, including when the run finished before the listener opened. +export async function listenForOutcomes( + request: Request, + body: any, + service: ApiService, + server: () => McpServer, + credentialActive: () => Promise, + ctx: ExecutionContext, +) { + const uris = z.array(z.string()).min(1).max(32).parse(body.params?.notifications?.resourceSubscriptions); + const pending = new Map(uris.map((uri) => [outcomeRunId(uri), uri])); + await service.outcomeStates([...pending.keys()]); + const handler = createMcpHandler(server, { legacy: "reject" }); + const response = await handler.fetch(request, { parsedBody: body }); + if (!response.ok || !response.headers.get("content-type")?.startsWith("text/event-stream")) return response; + const watch = async () => { + // Close periodically so the next listen passes through the full HTTP authentication boundary. + const deadline = Date.now() + 60_000; + try { + while (pending.size && !request.signal.aborted && Date.now() < deadline) { + const states = await service.outcomeStates([...pending.keys()]); + for (const row of states) { + if (!row.outcome_id) continue; + if (!(await credentialActive())) return; + handler.notify.resourceUpdated(pending.get(row.id)!); + pending.delete(row.id); + } + if (pending.size) await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } finally { + await handler.close(); + } + }; + ctx.waitUntil(watch()); + return response; +} diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index c176eed9..380c2c01 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -18,9 +18,9 @@ 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", "run_token"]), id: z.string() }) }); export const runFailureResponse = z.object({ source: z.enum(["run", "system"]), code: z.string(), reason: 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, + id: z.string(), job_id: z.string().nullable(), launch_skill_id: z.guid().nullable().optional(), launch_skill_key: z.string().nullable().optional(), launch_skill_revision: z.number().int().nullable().optional(), 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(), + run_name: z.string(), job_name: z.string().nullable(), 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"]), finalizing: z.boolean(), trace_revision: z.string(), failure_source: z.enum(["system", "agent"]).nullable(), failure: runFailureResponse.nullable().optional(), agent_error: agentErrorResponse.nullable(), @@ -35,7 +35,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(), 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(), + id: z.string(), job_id: z.string().nullable(), launch_skill_id: z.guid().nullable().optional(), launch_skill_key: z.string().nullable().optional(), launch_skill_revision: z.number().int().nullable().optional(), project_id: z.string().optional(), project_name: z.string().optional(), job_name: z.string().nullable(), 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(), failure: runFailureResponse.nullable().optional(), agent_error: agentErrorResponse.nullable(), elapsed_time: z.union([ z.object({ duration: z.number() }), @@ -54,8 +54,8 @@ export const fullRunResponse = runSummaryResponse.extend({ 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(), 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() }), + job_name: z.string().nullable(), prompt: z.string(), context: record, occurrence: record.nullable(), + invocation: z.object({ id: z.string(), source: z.string(), claim_key: z.string(), template_job_id:z.guid().nullable().optional(), 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(), activity: z.array(z.object({ action: z.string(), detail: z.string(), created_at: z.string() })), execution_diagnostics: record.nullable(), trace_sources: z.object({ primary: traceSource, nativeSession: traceSource.optional() }).nullable(), trace_projection: record.nullable(), trace_generation: z.string().nullable(), harness_log: record.nullable(), diff --git a/packages/api/src/vendor-run-auth.ts b/packages/api/src/vendor-run-auth.ts index 0d8ee734..c5ce8e4a 100644 --- a/packages/api/src/vendor-run-auth.ts +++ b/packages/api/src/vendor-run-auth.ts @@ -11,7 +11,7 @@ export const RUN_IDENTITY_HEADER = "X-Factorize-Run-Id"; const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; type RunAuthorization = { - tenant_id: string; run_id: string; job_id: string; user_id: string; session_version: number; + tenant_id: string; run_id: string; job_id: string | null; user_id: string; session_version: number; scopes: string[]; provider: VendorIdentityProvider; vm_id: string; issuer: string; subject: string; audience: string; execution_config: Record; execution_handle: { id?: string; vendorIdentityIntegrationName?: string } | null; @@ -65,7 +65,7 @@ export async function authenticateVendorRunRequest(request: Request, env: Env, o issuer: row.issuer, subject: row.subject, audience: row.audience, exeAttachment, } }); return { tenantId: row.tenant_id, userId: row.user_id, sessionVersion: row.session_version, - scopes: normalizeScopes(row.scopes), authMethod: "vendor_identity", runId, runJobId: row.job_id, + scopes: normalizeScopes(row.scopes), authMethod: "vendor_identity", runId, runJobId: row.job_id ?? undefined, runIdentityProvider: row.provider }; } catch { // Never surface provider response text, JWTs, or decrypted credentials. diff --git a/packages/api/test/fixtures/agent-api-runtime-worker.ts b/packages/api/test/fixtures/agent-api-runtime-worker.ts index 1df44dd7..31d62e24 100644 --- a/packages/api/test/fixtures/agent-api-runtime-worker.ts +++ b/packages/api/test/fixtures/agent-api-runtime-worker.ts @@ -1,3 +1,6 @@ +import { RunScheduler } from "../../src/postgres/run-scheduler"; +import { databaseFor } from "../../src/postgres/database"; +import type {ExecutionBackend, JobResultReader} from "../../src/execution"; import { cleanupVmGrants } from "../../src/vm-grants"; import { WorkerEntrypoint } from "cloudflare:workers"; import worker from "../../src/worker"; @@ -18,5 +21,21 @@ export default { // A test-only entrypoint drives the exact production heartbeat cleanup against // real PostgreSQL/R2, without adding a deployment endpoint or waiting 24 hours. export class AgentApiMaintenance extends WorkerEntrypoint { - async fetch() { await cleanupAgentResponses(this.env); await cleanupVmGrants(this.env); return new Response("done"); } + async fetch(request:Request) { + if (new URL(request.url).pathname === "/run-tick") { + const launches:string[]=[]; + const backend:ExecutionBackend & JobResultReader={ + kind:"exe-vm", capabilities:["stop"], + async launch(request) { + launches.push(request.runId); + if (request.prompt.startsWith("Simulate a launch failure")) throw new Error("Fixture VM unavailable"); + return {handle:{backendKind:"exe-vm",id:request.runId},destinationUrl:"https://fixture.invalid/",capabilities:["stop"],observation:{state:"running"}}; + }, + async inspect(){return {state:"succeeded"};}, async stop(){return {state:"stopped"};}, + async readJobResult(){return JSON.stringify({status:"succeeded",summary:"Review complete"});} + }; + await new RunScheduler(databaseFor(this.env),this.env,()=>backend).process(); + return Response.json(launches); + } + await cleanupAgentResponses(this.env); await cleanupVmGrants(this.env); return new Response("done"); } } diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index 51a67566..a67a9cd4 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -264,7 +264,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po expect(edges.rowCount).toBe(0); }); - it("commits provider cleanup ownership with job deletion and rolls both back on failure", async () => { + it("retains the running VM and its cleanup ownership after deleting its job", async () => { const a = await tenant(), source = await job(a); const run = await start(a, source); const handle = { backendKind: "exe-vm", id: `factorize-${run.id}` }; @@ -286,13 +286,11 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po } expect(await repository(a).delete(source.id)).toBe(true); - expect((await database.pool.query("SELECT execution_config,execution_backend_kind,execution_handle,started_at FROM app.deleted_job_provider_cleanup WHERE tenant_id=$1 AND run_id=$2", [a, run.id])).rows[0]).toMatchObject({ - execution_config: expect.objectContaining({ connectionId: "test" }), - execution_backend_kind: "exe-vm", - execution_handle: handle, - started_at: expect.any(Date), - }); - expect((await database.pool.query("SELECT 1 FROM app.runs WHERE tenant_id=$1 AND id=$2", [a, run.id])).rowCount).toBe(0); + const retained = await database.pool.query("SELECT job_id,execution_handle,state,source_job_name FROM app.runs WHERE tenant_id=$1 AND id=$2",[a,run.id]); + expect(retained.rows[0]).toMatchObject({job_id:null,execution_handle:handle,state:"running",source_job_name:"Job"}); + await database.pool.query("UPDATE app.job_runs SET next_poll_at=now() WHERE tenant_id=$1 AND id=$2",[a,run.id]); + expect((await runs.dueForPoll()).some(item=>item.id===run.id)).toBe(true); + expect((await new RunQueryRepository(database,a).get(run.id))?.job_name).toBe("Job"); }); it("stores and revokes an explicit self-invocation permission", async () => { diff --git a/packages/api/test/pages-smoke.e2e.test.ts b/packages/api/test/pages-smoke.e2e.test.ts index c523a154..fff1ea89 100644 --- a/packages/api/test/pages-smoke.e2e.test.ts +++ b/packages/api/test/pages-smoke.e2e.test.ts @@ -69,7 +69,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("every page E2E smoke", () "job context": { path: () => job() + "/settings/context", ready: label("Prompt template") }, "job permissions": { path: () => job() + "/settings/permissions", ready: heading("Manual invocation permissions") }, "job triggers": { path: () => job() + "/settings/triggers", ready: heading("Triggers") }, - "runs": { path: () => "/job-runs", ready: heading("Job Runs") }, + "runs": { path: () => "/job-runs", ready: heading("Runs") }, "run": { path: run, ready: heading("Trace") }, "full trace": { path: () => run() + "/trace", ready: heading("Full trace") }, "run info": { path: () => run() + "/info", ready: info }, diff --git a/packages/api/test/postgres-run-query-repository.test.ts b/packages/api/test/postgres-run-query-repository.test.ts index 1e01af14..b41dba07 100644 --- a/packages/api/test/postgres-run-query-repository.test.ts +++ b/packages/api/test/postgres-run-query-repository.test.ts @@ -44,8 +44,8 @@ describe("run timing queries", () => { }); it.each([ - ["job", "asc", "j.name ASC"], - ["job", "desc", "j.name DESC"], + ["job", "asc", "COALESCE(j.name,r.source_job_name) ASC"], + ["job", "desc", "COALESCE(j.name,r.source_job_name) DESC"], ["run", "asc", "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run') ASC"], ["run", "desc", "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run') DESC"], ["status", "asc", "r.state ASC"], @@ -87,7 +87,7 @@ describe("run timing queries", () => { const query = vi.fn(async () => ({ rows: [] })); await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams([['projectId', 'project-a'], ['projectId', 'project-b'], ['jobId', 'job-a'], ['jobId', 'job-b'], ['limit', '10']])); const [sql, values] = query.mock.calls[0] as unknown as [string, unknown[]]; - expect(sql).toContain("j.project_id=ANY($2::uuid[])"); + expect(sql).toContain("r.project_id=ANY($2::uuid[])"); expect(sql).toContain("r.job_id=ANY($3::uuid[])"); expect(values).toEqual(["tenant", ["project-a", "project-b"], ["job-a", "job-b"], 11]); }); diff --git a/packages/api/test/postgres-run-repository.test.ts b/packages/api/test/postgres-run-repository.test.ts index ba085ec9..338238e7 100644 --- a/packages/api/test/postgres-run-repository.test.ts +++ b/packages/api/test/postgres-run-repository.test.ts @@ -27,7 +27,7 @@ describe("RunRepository", () => { const query = vi.fn(async (sql: string) => ({ rows: sql.includes("WITH candidate") ? [] : [], rowCount: 0 })); const database = { transaction: (work: any) => work({ query }), pool: { query } } as any; await expect(new RunRepository(database).claimNext()).resolves.toBeNull(); - expect(query.mock.calls[0][0]).toContain("FOR UPDATE OF r SKIP LOCKED"); + expect(query.mock.calls[0][0]).toContain("FOR UPDATE OF p SKIP LOCKED"); expect(query.mock.calls[0][0]).toContain("concurrency_limit"); }); }); diff --git a/packages/api/test/scope-redesign.test.ts b/packages/api/test/scope-redesign.test.ts index c1c3c6f9..015f6308 100644 --- a/packages/api/test/scope-redesign.test.ts +++ b/packages/api/test/scope-redesign.test.ts @@ -5,7 +5,7 @@ import { API_ROUTES } from "../src/api-contract"; describe("GEN-2418 permission boundaries", () => { it("exposes independently issuable skill scopes and maps legacy grants without issuing them", () => { - expect(ACCESS_SCOPES).toEqual(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"]); + expect(ACCESS_SCOPES).toEqual(["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"]); expect(normalizeScopes(["flows:read", "runs:write"])).toEqual(["projects:read", "jobs:read", "integrations:read", "runs:read", "runs:invoke", "runs:cancel", "runs:write"]); expect(ACCESS_SCOPES).not.toContain("flows:read" as never); }); diff --git a/packages/app/src/features/auth/consent.tsx b/packages/app/src/features/auth/consent.tsx index f33341c7..977fd43e 100644 --- a/packages/app/src/features/auth/consent.tsx +++ b/packages/app/src/features/auth/consent.tsx @@ -9,6 +9,6 @@ export function ConsentScreen() { const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes: selected ?? preview.data.scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } }); const scopes = selected ?? preview.data?.scopes ?? []; return

Authorize {preview.data?.clientName ?? "a client"}

{preview.isPending &&

Validating authorization request…

}{preview.error &&

{preview.error.message}

} - {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Job writes may cause future schedule/webhook/lifecycle execution, and deleting a job may remove run history and artifacts. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

} + {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Job writes may cause future schedule/webhook/lifecycle execution. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

}
; } diff --git a/packages/app/src/features/jobs/delete.tsx b/packages/app/src/features/jobs/delete.tsx index 019b9560..a9b00db9 100644 --- a/packages/app/src/features/jobs/delete.tsx +++ b/packages/app/src/features/jobs/delete.tsx @@ -6,5 +6,5 @@ import { messageOf } from "../auth/session"; export function DeleteJob({ jobId, name, disabled = false, onDeleted }: { jobId: string; name: string; disabled?: boolean; onDeleted?: () => void }) { const cache = useQueryClient(), navigate = useNavigate(); const remove = useMutation({ retry: false, mutationFn: async () => { const { error } = await api.DELETE("/api/v1/jobs/{jobId}", { params: { path: { jobId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: async () => { onDeleted?.(); await cache.invalidateQueries({ queryKey: ["jobs"] }); await cache.invalidateQueries({ queryKey: ["runs"] }); void navigate({ to: "/jobs", search: { q: "" } }); } }); - return

Delete this job

Permanently remove this job, its execution history, and artifacts.

{remove.error &&

{remove.error.message}

}
; + return

Delete this job

Remove this template and its triggers. Existing runs follow their usual retention period.

{remove.error &&

{remove.error.message}

}
; } diff --git a/packages/app/src/features/jobs/editor-state.ts b/packages/app/src/features/jobs/editor-state.ts index 7595f49f..6087b234 100644 --- a/packages/app/src/features/jobs/editor-state.ts +++ b/packages/app/src/features/jobs/editor-state.ts @@ -10,7 +10,7 @@ export function canonicalizeVmImage(value: string): string { return `${name.toLowerCase()}${tag}${digest}`; } export function editableJob(job: Job): JobInput { - return { modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, githubInstallationIds: job.githubInstallationIds, linearConnectionId: job.linearConnectionId, xConnectionIds: job.xConnectionIds ?? [], runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", 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 => { + return { launchSkillId:job.launchSkillId, modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, githubInstallationIds: job.githubInstallationIds, linearConnectionId: job.linearConnectionId, xConnectionIds: job.xConnectionIds ?? [], runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", 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; diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index ebeb75ca..942cdf4e 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -140,7 +140,7 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) { } {(draft.executionType ?? "agent") === "code" &&