From bb6e173c5105dcd40d9f2410152d1aedfa4a0c27 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 18:14:04 +0000 Subject: [PATCH] GEN-2152 generate and verify OpenAPI from executable route contracts --- .github/workflows/ci.yml | 4 + package-lock.json | 85 +- package.json | 4 +- packages/app/package.json | 11 +- packages/app/scripts/check-api-boundaries.mjs | 3 - packages/app/scripts/generate-openapi.ts | 19 + packages/app/src/api-contract.ts | 1097 +++++- packages/app/src/api-document.json | 673 ++++ packages/app/src/flow-schemas.ts | 2 +- packages/app/src/protected-api.ts | 89 +- packages/app/src/trace-replay-schemas.ts | 18 + packages/app/src/trace-replay.ts | 4 +- packages/app/test/api-boundary.test.ts | 332 ++ packages/app/test/api-contract.test.ts | 119 +- packages/app/test/manual-invocation.test.ts | 2 +- .../app/test/run-diagnostics-contract.test.ts | 21 +- packages/app/tsconfig.json | 3 +- packages/docs/README.md | 6 +- packages/docs/api/openapi.mdx | 12 +- packages/docs/api/reference.mdx | 60 +- packages/docs/docs.json | 57 +- packages/docs/llms-full.txt | 4 +- packages/docs/llms.txt | 3 +- packages/docs/openapi.yaml | 3507 ++++++++++++++++- packages/docs/scripts/validate.mjs | 10 +- 25 files changed, 5745 insertions(+), 400 deletions(-) create mode 100644 packages/app/scripts/generate-openapi.ts create mode 100644 packages/app/src/api-document.json create mode 100644 packages/app/src/trace-replay-schemas.ts create mode 100644 packages/app/test/api-boundary.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e1993da..fd47528f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,5 +42,9 @@ jobs: node-version: 24 cache: npm - run: npm ci + - name: Verify generated API contract + run: | + npm run generate:openapi + git diff --exit-code -- packages/docs/openapi.yaml - run: npm run build:css - run: npm run check diff --git a/package-lock.json b/package-lock.json index 35ef2193..9d141423 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4216,6 +4216,23 @@ "node": ">=0.4.0" } }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -5196,6 +5213,30 @@ "resolved": "packages/tail-relay", "link": true }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -5354,6 +5395,13 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", @@ -5974,6 +6022,16 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -6305,9 +6363,9 @@ "optional": true }, "node_modules/tsx": { - "version": "4.23.13", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.13.tgz", - "integrity": "sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw==", + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", "dev": true, "license": "MIT", "dependencies": { @@ -7134,6 +7192,22 @@ "node": ">=0.4" } }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/youch": { "version": "4.1.0-beta.10", "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", @@ -7189,12 +7263,15 @@ "@types/mustache": "^4.2.6", "@types/node": "^26.5.1", "@types/pg": "^8.15.5", + "ajv": "^8.20.0", "drizzle-kit": "^0.31.10", "happy-dom": "^20.14.5", "tailwindcss": "^4.1.14", + "tsx": "^4.23.15", "typescript": "^5.9.3", "vitest": "^3.2.4", - "wrangler": "^4.44.0" + "wrangler": "^4.44.0", + "yaml": "^2.9.1" } }, "packages/docs": { diff --git a/package.json b/package.json index 2cea1b06..38a46344 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,8 @@ "deploy": "npm run deploy:marketing && npm run deploy:app && npm run deploy:tail-relay", "deploy:marketing": "npm run deploy --workspace=factorize-marketing", "deploy:app": "npm run deploy --workspace=factorize", - "deploy:tail-relay": "npm run deploy --workspace=factorize-tail-relay" + "deploy:tail-relay": "npm run deploy --workspace=factorize-tail-relay", + "generate:openapi": "npm run generate:openapi --workspace=factorize", + "check:openapi": "npm run check:openapi --workspace=factorize" } } diff --git a/packages/app/package.json b/packages/app/package.json index 4634c176..c416cebb 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -6,14 +6,16 @@ "scripts": { "dev": "npm run build:css && wrangler dev", "build:css": "tailwindcss -i ./src/tailwind.css -o ./public/styles.css --minify", - "check": "npm run check:api-boundaries && node --test scripts/validate-auth-email.check.mjs && tsc --noEmit && vitest run && wrangler deploy --dry-run", + "check": "npm run check:openapi && npm run check:api-boundaries && node --test scripts/validate-auth-email.check.mjs && tsc --noEmit && vitest run && wrangler deploy --dry-run", "check:api-boundaries": "node scripts/check-api-boundaries.mjs", "test": "vitest run", "deploy": "wrangler deploy", "db:migrate": "node scripts/migrate.mjs", "db:verify": "node scripts/verify-schema.mjs", "db:studio": "drizzle-kit studio --config drizzle.config.ts", - "auth:validate-email": "node scripts/validate-auth-email.mjs" + "auth:validate-email": "node scripts/validate-auth-email.mjs", + "generate:openapi": "tsx scripts/generate-openapi.ts", + "check:openapi": "tsx scripts/generate-openapi.ts --check" }, "dependencies": { "@cloudflare/workers-oauth-provider": "^0.10.3", @@ -33,11 +35,14 @@ "@types/mustache": "^4.2.6", "@types/node": "^26.5.1", "@types/pg": "^8.15.5", + "ajv": "^8.20.0", "drizzle-kit": "^0.31.10", "happy-dom": "^20.14.5", "tailwindcss": "^4.1.14", + "tsx": "^4.23.15", "typescript": "^5.9.3", "vitest": "^3.2.4", - "wrangler": "^4.44.0" + "wrangler": "^4.44.0", + "yaml": "^2.9.1" } } diff --git a/packages/app/scripts/check-api-boundaries.mjs b/packages/app/scripts/check-api-boundaries.mjs index 1c41b6f5..31f5e71d 100644 --- a/packages/app/scripts/check-api-boundaries.mjs +++ b/packages/app/scripts/check-api-boundaries.mjs @@ -8,8 +8,5 @@ for (const file of files) { for (const match of source.matchAll(/["'`]\/api\/(?!v1(?:\/|["'`]))[^"'`]*/g)) failures.push(`${file}: unversioned API reference ${match[0]}`); if (file !== "src/protected-api.ts" && /app\.(?:get|post|put|patch|delete|all)\(["'`]\/api\//.test(source)) failures.push(`${file}: API routes may only be registered in src/protected-api.ts`); } -const contract = readFileSync(new URL("../src/api-contract.ts", import.meta.url), "utf8"); -const openapi = readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"); -for (const [, path] of contract.matchAll(/\["(?:GET|POST|PUT|PATCH|DELETE)", "([^"]+)"\]/g)) if (!openapi.includes(` ${path}:`)) failures.push(`OpenAPI is missing ${path}`); if (failures.length) { console.error(failures.join("\n")); process.exit(1); } console.log(`API boundaries verified across ${files.length} source and test files.`); diff --git a/packages/app/scripts/generate-openapi.ts b/packages/app/scripts/generate-openapi.ts new file mode 100644 index 00000000..22ec9d75 --- /dev/null +++ b/packages/app/scripts/generate-openapi.ts @@ -0,0 +1,19 @@ +import { readFileSync, writeFileSync } from "node:fs"; +import { stringify } from "yaml"; +import { generateOpenApi } from "../src/api-contract"; + +const target = new URL("../../docs/openapi.yaml", import.meta.url); +export const generated = + "# Generated by npm run generate:openapi. Edit packages/app/src/api-contract.ts.\n" + + stringify(generateOpenApi(), { lineWidth: 0, aliasDuplicateObjects: false }); +if (process.argv.includes("--check")) { + if (readFileSync(target, "utf8") !== generated) { + console.error( + "OpenAPI is stale. Run npm run generate:openapi and commit packages/docs/openapi.yaml.", + ); + process.exitCode = 1; + } else console.log("Generated OpenAPI is current."); +} else { + writeFileSync(target, generated); + console.log("Generated packages/docs/openapi.yaml."); +} diff --git a/packages/app/src/api-contract.ts b/packages/app/src/api-contract.ts index cb6d7fa6..e02e1562 100644 --- a/packages/app/src/api-contract.ts +++ b/packages/app/src/api-contract.ts @@ -1,26 +1,1071 @@ -export const API_OPERATIONS = [ - ["GET", "/api/v1/exe-connections"], ["GET", "/api/v1/github-installations"], - ["GET", "/api/v1/execution-targets"], ["GET", "/api/v1/job-trigger-availability"], - ["POST", "/api/v1/schedules/preview"], ["GET", "/api/v1/integrations"], - ["GET", "/api/v1/integrations/cloudflare-tail"], ["POST", "/api/v1/integrations/cloudflare-tail"], - ["PUT", "/api/v1/integrations/cloudflare-tail/{integrationId}"], ["DELETE", "/api/v1/integrations/cloudflare-tail/{integrationId}"], - ["POST", "/api/v1/integrations/cloudflare-tail/{integrationId}/test"], - ["PUT", "/api/v1/integrations/exe"], ["POST", "/api/v1/integrations/exe/test"], ["DELETE", "/api/v1/integrations/exe/{connectionId}"], - ["POST", "/api/v1/integrations/exe/{connectionId}/diagnostics"], - ["PUT", "/api/v1/integrations/amp"], ["POST", "/api/v1/integrations/amp/test"], ["DELETE", "/api/v1/integrations/amp/{connectionId}"], - ["GET", "/api/v1/providers/linear/projects"], ["GET", "/api/v1/providers/linear/options"], - ["GET", "/api/v1/providers/clickup/lists"], ["GET", "/api/v1/providers/clickup/options"], - ["GET", "/api/v1/providers/github/installations"], ["DELETE", "/api/v1/providers/github/installations/{installationId}"], - ["GET", "/api/v1/providers/github/installations/{installationId}/repositories"], - ["GET", "/api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options"], - ["GET", "/api/v1/access/authorized-clients"], ["DELETE", "/api/v1/access/authorized-clients/{clientId}"], - ["GET", "/api/v1/access-tokens"], ["POST", "/api/v1/access-tokens"], ["DELETE", "/api/v1/access-tokens/{tokenId}"], - ["GET", "/api/v1/jobs"], ["POST", "/api/v1/jobs"], ["GET", "/api/v1/jobs/{jobId}"], ["PUT", "/api/v1/jobs/{jobId}"], ["DELETE", "/api/v1/jobs/{jobId}"], - ["POST", "/api/v1/jobs/{jobId}/enable"], ["POST", "/api/v1/jobs/{jobId}/disable"], ["POST", "/api/v1/jobs/{jobId}/invocations"], ["GET", "/api/v1/jobs/{jobId}/events"], - ["POST", "/api/v1/job-handlers/test"], ["GET", "/api/v1/runs"], ["GET", "/api/v1/runs/{runId}"], ["GET", "/api/v1/runs/{runId}/trace"], - ["POST", "/api/v1/runs/{runId}/trace/replay"], ["GET", "/api/v1/runs/{runId}/diagnostics"], ["POST", "/api/v1/runs/{runId}/stop"], ["POST", "/api/v1/runs/{runId}/kill"], ["GET", "/api/v1/search"], - ["GET", "/api/v1/webhooks/deliveries"], ["GET", "/api/v1/webhooks/deliveries/{deliveryId}"], -] as const; - -const matchers = API_OPERATIONS.map(([method, template]) => [method, new RegExp(`^${template.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`)] as const); -export function isDeclaredApiOperation(method: string, path: string): boolean { return matchers.some(([candidate, pattern]) => candidate === method && pattern.test(path)); } +import { z } from "zod"; +import type { ApiService } from "./flow-service"; +import { + jobInputSchema, + manualInvocationSchema, + jobHandlerTestSchema, + listRunsSchema, + scopeSchema, +} from "./flow-schemas"; +import { traceReplaySchema } from "./trace-replay-schemas"; +import document from "./api-document.json"; + +type JsonSchema = Record; +export interface RouteContract { + method: string; + path: string; + scope: z.infer; + ownerSession: boolean; + body?: z.ZodType; + query?: z.ZodObject; + parameters: z.ZodObject; + status: number; + documentation: Record; + execute: ( + service: ApiService, + input: { params: Record; body: any; query: any; url: URL }, + ) => Promise; +} + +function queryOf(value: Record): URLSearchParams { + const query = new URLSearchParams(); + for (const [key, item] of Object.entries(value)) + if (item !== undefined) query.set(key, String(item)); + return query; +} + +const exeBody = z.object({ + connectionId: z.string().min(1).optional(), + apiToken: z.string().min(1).meta({ writeOnly: true }), + agentKind: z.enum(["codex", "claude", "pi"]), + tags: z + .array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)) + .max(20) + .optional(), +}); +const exeTestBody = exeBody + .partial() + .refine((value) => Boolean(value.connectionId || value.apiToken), { + message: "Supply a saved connectionId or apiToken", + }); +const ampBody = z.object({ + connectionId: z.string().min(1).optional(), + accessToken: z.string().min(1).meta({ writeOnly: true }), + project: z.string().min(1), + apiBaseUrl: z.url().optional(), +}); +const ampTestBody = ampBody + .partial() + .refine( + (value) => + Boolean(value.connectionId || (value.accessToken && value.project)), + { message: "Supply a saved connectionId or accessToken and project" }, + ); +const tailBody = z.object({ + integrationId: z.string().min(1).optional(), + name: z.string().trim().min(1).max(120), + signingSecret: z + .union([z.literal(""), z.string().min(16)]) + .optional() + .meta({ writeOnly: true }), + generateSecret: z.boolean().optional(), +}); +const deliveryQuery = z.object({ + provider: z.string().optional(), + deliveryId: z.string().optional(), + event: z.string().optional(), + action: z.string().optional(), + outcome: z.string().optional(), + jobId: z.string().optional(), + q: z.string().optional(), + cursor: z.string().optional(), + limit: z.coerce.number().int().min(1).max(100).default(50), +}); +const eventQuery = z.object({ + limit: z.coerce.number().int().min(1).max(100).default(50), +}); +const traceQuery = z.object({ + after: z.coerce.number().int().min(0).default(0), + limit: z.coerce.number().int().min(1).max(200).default(100), +}); +const searchQuery = z.object({ q: z.string().default("") }); +const clickUpQuery = z.object({ listId: z.string().default("") }); +const scheduleBody = z + .object({ + cron: z.string().trim().min(1), + timezone: z.string().trim().min(1), + }) + .strict(); +const accessTokenBody = z.object({ + name: z.string().trim().min(1).max(100), + scopes: z.array(scopeSchema).min(1), + expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]), +}); + +function route( + method: string, + path: string, + scope: RouteContract["scope"], + documentation: RouteContract["documentation"], + execute: RouteContract["execute"], + options: Partial< + Pick + > = {}, +): RouteContract { + const keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]); + const parameters = z.object( + Object.fromEntries( + keys.map((key) => [ + key, + key === "installationId" || key === "repositoryId" + ? z.string().regex(/^[0-9]+$/) + : z.string().min(1), + ]), + ), + ); + const status = Number( + Object.keys(documentation.responses).find((code) => code.startsWith("2")), + ); + return { + method, + path, + scope, + parameters, + status, + ownerSession: false, + documentation, + execute, + ...options, + }; +} + +/** The executable API catalog: change an operation here, then run generate:openapi. + * Service methods retain tenant/identity authorization for both REST and MCP. + */ +export const API_ROUTES: RouteContract[] = [ + route( + "GET", + "/api/v1/exe-connections", + "flows:read", + { + summary: "List exe connections", + responses: { + "200": { + description: "Safe metadata", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listExeConnections(), + ), + route( + "GET", + "/api/v1/github-installations", + "flows:read", + { + summary: "List GitHub installations", + responses: { + "200": { + description: "Installations", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listGitHubInstallations(), + ), + route( + "GET", + "/api/v1/execution-targets", + "flows:read", + { + summary: "List execution targets", + responses: { + "200": { + description: "Targets", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listExecutionTargets(), + ), + route( + "GET", + "/api/v1/job-trigger-availability", + "flows:read", + { + summary: "List available trigger kinds", + responses: { "200": { description: "Availability" } }, + }, + (service) => service.listJobTriggerAvailability(), + ), + route( + "POST", + "/api/v1/schedules/preview", + "flows:read", + { + summary: "Preview schedule", + responses: { + "200": { + description: "Next occurrence", + content: { + "application/json": { + schema: { + type: "object", + required: ["nextRunAt"], + properties: { + nextRunAt: { type: "string", format: "date-time" }, + }, + }, + }, + }, + }, + }, + }, + (service, { body }) => service.previewSchedule(body), + { body: scheduleBody }, + ), + route( + "GET", + "/api/v1/integrations/cloudflare-tail", + "flows:read", + { + summary: "List Tail integrations", + responses: { + "200": { + description: "Integrations", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listTailIntegrations(), + ), + route( + "GET", + "/api/v1/integrations", + "flows:read", + { + summary: "List installed integrations", + responses: { + "200": { description: "Credential-safe integration status" }, + }, + }, + (service) => service.integrationStatus(), + ), + route( + "PUT", + "/api/v1/integrations/exe", + "flows:write", + { + summary: "Create an exe.dev integration", + responses: { "200": { description: "Saved" } }, + }, + (service, { body }) => service.saveExeIntegration(body), + { body: exeBody }, + ), + route( + "POST", + "/api/v1/integrations/exe/test", + "flows:write", + { + summary: "Test exe.dev credentials", + responses: { "200": { description: "Test result" } }, + }, + (service, { body }) => service.testExeIntegration(body), + { body: exeTestBody }, + ), + route( + "PUT", + "/api/v1/integrations/amp", + "flows:write", + { + summary: "Create an Amp integration", + responses: { "200": { description: "Saved" } }, + }, + (service, { body }) => service.saveAmpIntegration(body), + { body: ampBody }, + ), + route( + "POST", + "/api/v1/integrations/amp/test", + "flows:write", + { + summary: "Test Amp credentials", + responses: { "200": { description: "Test result" } }, + }, + (service, { body }) => service.testAmpIntegration(body), + { body: ampTestBody }, + ), + route( + "POST", + "/api/v1/integrations/cloudflare-tail", + "flows:write", + { + summary: "Create a Tail integration", + responses: { "201": { description: "Created" } }, + }, + (service, { body }) => service.saveTailIntegration(body), + { body: tailBody }, + ), + route( + "GET", + "/api/v1/providers/linear/projects", + "flows:read", + { + summary: "List Linear projects", + responses: { + "200": { + description: "Projects", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.linearProjects(), + ), + route( + "GET", + "/api/v1/providers/linear/options", + "flows:read", + { + summary: "List Linear trigger options", + responses: { "200": { description: "Options" } }, + }, + (service) => service.linearOptions(), + ), + route( + "GET", + "/api/v1/providers/clickup/lists", + "flows:read", + { + summary: "List ClickUp lists", + responses: { + "200": { + description: "Lists", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.clickUpLists(), + ), + route( + "GET", + "/api/v1/providers/clickup/options", + "flows:read", + { + summary: "List ClickUp trigger options", + responses: { "200": { description: "Options" } }, + }, + (service, { query }) => service.clickUpOptions(query.listId), + { query: clickUpQuery }, + ), + route( + "GET", + "/api/v1/providers/github/installations", + "flows:read", + { + summary: "List GitHub installations for provider setup", + responses: { + "200": { + description: "Installations", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listGitHubInstallations(), + ), + route( + "GET", + "/api/v1/access/authorized-clients", + "flows:read", + { + summary: "List authorized OAuth clients", + responses: { + "200": { + description: "Clients", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listAuthorizedClients(), + { ownerSession: true }, + ), + route( + "GET", + "/api/v1/access-tokens", + "flows:read", + { + summary: "List access tokens", + responses: { + "200": { + description: "Token metadata", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listAccessTokens(), + { ownerSession: true }, + ), + route( + "POST", + "/api/v1/access-tokens", + "flows:write", + { + summary: "Create an access token", + responses: { "201": { description: "Created token" } }, + }, + (service, { body }) => service.createAccessToken(body), + { body: accessTokenBody, ownerSession: true }, + ), + route( + "DELETE", + "/api/v1/access-tokens/{tokenId}", + "flows:write", + { + summary: "Revoke an access token", + responses: { "200": { description: "Revoked" } }, + }, + (service, { params }) => service.revokeAccessToken(params.tokenId), + { ownerSession: true }, + ), + route( + "DELETE", + "/api/v1/access/authorized-clients/{clientId}", + "flows:write", + { + summary: "Revoke an authorized OAuth client", + responses: { "200": { description: "Revoked grants" } }, + }, + (service, { params }) => service.revokeAuthorizedClient(params.clientId), + { ownerSession: true }, + ), + route( + "DELETE", + "/api/v1/integrations/exe/{connectionId}", + "flows:write", + { + summary: "Remove an exe.dev integration", + responses: { "200": { description: "Removed" } }, + }, + (service, { params }) => + service.removeIntegration("exe", params.connectionId), + ), + route( + "DELETE", + "/api/v1/integrations/amp/{connectionId}", + "flows:write", + { + summary: "Remove an Amp integration", + responses: { "200": { description: "Removed" } }, + }, + (service, { params }) => + service.removeIntegration("amp", params.connectionId), + ), + route( + "PUT", + "/api/v1/integrations/cloudflare-tail/{integrationId}", + "flows:write", + { + summary: "Update a Tail integration", + responses: { "200": { description: "Updated" } }, + }, + (service, { params, body }) => + service.saveTailIntegration({ + ...body, + integrationId: params.integrationId, + }), + { body: tailBody }, + ), + route( + "DELETE", + "/api/v1/integrations/cloudflare-tail/{integrationId}", + "flows:write", + { + summary: "Remove a Tail integration", + responses: { "200": { description: "Removed" } }, + }, + (service, { params }) => + service.removeTailIntegration(params.integrationId), + ), + route( + "POST", + "/api/v1/integrations/cloudflare-tail/{integrationId}/test", + "flows:write", + { + summary: "Test a Tail integration", + responses: { "200": { description: "Test result" } }, + }, + (service, { params }) => service.testTailIntegration(params.integrationId), + ), + route( + "GET", + "/api/v1/providers/github/installations/{installationId}/repositories", + "flows:read", + { + summary: "List installation repositories", + responses: { + "200": { + description: "Repositories", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service, { params }) => + service.githubRepositories(Number(params.installationId)), + ), + route( + "GET", + "/api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options", + "flows:read", + { + summary: "List GitHub issue trigger options", + responses: { "200": { description: "Options" } }, + }, + (service, { params }) => + service.githubIssueOptions( + Number(params.installationId), + Number(params.repositoryId), + ), + ), + route( + "DELETE", + "/api/v1/providers/github/installations/{installationId}", + "flows:write", + { + summary: "Disconnect a GitHub installation", + responses: { "200": { description: "Disconnected" } }, + }, + (service, { params }) => + service.removeGitHubInstallation(Number(params.installationId)), + ), + route( + "POST", + "/api/v1/integrations/exe/{connectionId}/diagnostics", + "flows:write", + { + summary: + "Probe exe.dev permissions and a disposable VM's agent/model integration", + responses: { + "200": { description: "Credential-safe diagnostic result" }, + }, + }, + (service, { params }) => + service.diagnoseExeIntegration(params.connectionId), + ), + route( + "GET", + "/api/v1/jobs", + "flows:read", + { + summary: "List jobs", + responses: { + "200": { + description: "Jobs", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service) => service.listJobs(), + ), + route( + "POST", + "/api/v1/jobs", + "flows:write", + { summary: "Create job", responses: { "201": { description: "Created" } } }, + (service, { body }) => service.createJob(body), + { body: jobInputSchema }, + ), + route( + "POST", + "/api/v1/job-handlers/test", + "flows:write", + { + summary: "Test webhook handler", + responses: { "200": { description: "Decision" } }, + }, + (service, { body }) => service.testJobHandler(body), + { body: jobHandlerTestSchema }, + ), + route( + "POST", + "/api/v1/jobs/{jobId}/invocations", + "runs:write", + { + summary: "Invoke job", + responses: { + "202": { + description: "Accepted", + content: { + "application/json": { + schema: { + type: "object", + required: ["invocationId", "runId", "state", "duplicate"], + properties: { + invocationId: { type: "string" }, + runId: { type: "string" }, + state: { type: "string" }, + duplicate: { type: "boolean" }, + }, + }, + }, + }, + }, + "409": { + description: + "queue_full \u2014 this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run.", + }, + }, + }, + (service, { params, body }) => service.invokeJob(params.jobId, body), + { body: manualInvocationSchema }, + ), + route( + "GET", + "/api/v1/jobs/{jobId}/events", + "runs:read", + { + summary: "List webhook activity", + responses: { + "200": { + description: "Activity", + content: { + "application/json": { + schema: { type: "array", items: { type: "object" } }, + }, + }, + }, + }, + }, + (service, { params, query }) => + service.listJobEvents(params.jobId, query.limit), + { query: eventQuery }, + ), + route( + "POST", + "/api/v1/jobs/{jobId}/enable", + "flows:write", + { summary: "Enable job", responses: { "200": { description: "Enabled" } } }, + (service, { params }) => service.setJobEnabled(params.jobId, true), + ), + route( + "POST", + "/api/v1/jobs/{jobId}/disable", + "flows:write", + { + summary: "Disable job", + responses: { "200": { description: "Disabled" } }, + }, + (service, { params }) => service.setJobEnabled(params.jobId, false), + ), + route( + "GET", + "/api/v1/jobs/{jobId}", + "flows:read", + { summary: "Get job", responses: { "200": { description: "Job" } } }, + (service, { params }) => service.getJob(params.jobId), + ), + route( + "PUT", + "/api/v1/jobs/{jobId}", + "flows:write", + { + summary: "Replace job", + responses: { "200": { description: "Updated" } }, + }, + (service, { params, body }) => service.updateJob(params.jobId, body), + { body: jobInputSchema }, + ), + route( + "DELETE", + "/api/v1/jobs/{jobId}", + "flows:write", + { summary: "Delete job", responses: { "200": { description: "Deleted" } } }, + (service, { params }) => service.deleteJob(params.jobId), + ), + route( + "GET", + "/api/v1/runs", + "runs:read", + { + summary: "List runs", + responses: { + "200": { + description: "Paginated runs", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/RunPage" }, + }, + }, + }, + }, + }, + (service, { query }) => service.listRuns(queryOf(query)), + { query: listRunsSchema }, + ), + route( + "GET", + "/api/v1/search", + "runs:read", + { + summary: "Search jobs and runs", + responses: { "200": { description: "Search results" } }, + }, + (service, { query }) => service.search(query.q), + { query: searchQuery }, + ), + route( + "GET", + "/api/v1/webhooks/deliveries", + "runs:read", + { + summary: "Search webhook deliveries", + responses: { + "200": { description: "Cursor-paginated safe delivery records" }, + }, + }, + (service, { query }) => service.listWebhookDeliveries(queryOf(query)), + { query: deliveryQuery }, + ), + route( + "GET", + "/api/v1/webhooks/deliveries/{deliveryId}", + "runs:read", + { + summary: "Get webhook delivery detail and processing timeline", + responses: { "200": { description: "Safe delivery detail" } }, + }, + (service, { params }) => service.getWebhookDelivery(params.deliveryId), + ), + route( + "GET", + "/api/v1/runs/{runId}", + "runs:read", + { + summary: "Get run", + responses: { + "200": { + description: + "Run including durable execution diagnostics and harness artifact location", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/RunDetail" }, + }, + }, + }, + }, + }, + (service, { params }) => service.getRun(params.runId), + ), + route( + "GET", + "/api/v1/runs/{runId}/trace", + "runs:read", + { + summary: "Get paginated run trace events", + responses: { + "200": { + description: "Trace page", + content: { + "application/json": { + schema: { + type: "object", + required: ["items", "nextCursor"], + properties: { + items: { type: "array", items: { type: "object" } }, + nextCursor: { type: ["integer", "null"] }, + }, + }, + }, + }, + }, + }, + }, + (service, { params, query }) => + service.getRunTrace(params.runId, query.after, query.limit), + { query: traceQuery }, + ), + route( + "POST", + "/api/v1/runs/{runId}/trace/replay", + "runs:write", + { + summary: + "Replay a retained trace artifact or restore a native-session projection", + description: + "Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run.", + responses: { + "200": { + description: "Durable replay result", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/TraceReplayResult" }, + }, + }, + }, + "400": { description: "Invalid request" }, + "401": { description: "Invalid owner session" }, + "403": { + description: "Missing runs:write scope or interactive owner session", + }, + "404": { description: "Run not found within the tenant" }, + "409": { + description: + "Request ID conflict or artifact ownership/checksum mismatch", + }, + "429": { + description: + "Tenant rate limit reached; wait one minute before retrying", + }, + "503": { description: "Artifact storage unavailable" }, + }, + }, + (service, { params, body }) => service.replayRunTrace(params.runId, body), + { + body: traceReplaySchema, + ownerSession: true, + parameters: z.object({ runId: z.uuid() }), + }, + ), + route( + "GET", + "/api/v1/runs/{runId}/diagnostics", + "runs:read", + { + summary: "Get credential-safe run lifecycle diagnostics", + responses: { + "200": { + description: + "Credential-safe execution metadata and durable harness artifact location", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/RunDiagnostics" }, + }, + }, + }, + }, + }, + (service, { params }) => service.getRunDiagnostics(params.runId), + ), + route( + "POST", + "/api/v1/runs/{runId}/stop", + "runs:write", + { summary: "Stop run", responses: { "200": { description: "Stopped" } } }, + (service, { params }) => service.stopRun(params.runId), + ), + route( + "POST", + "/api/v1/runs/{runId}/kill", + "runs:write", + { + summary: "Kill run and immediately release its concurrency slot", + responses: { "200": { description: "Killed" } }, + }, + (service, { params }) => service.killRun(params.runId), + ), +]; + +export const API_OPERATIONS = API_ROUTES.map( + (route) => [route.method, route.path] as const, +); + +const matchers = API_ROUTES.map((route) => ({ + route, + keys: [...route.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]), + pattern: new RegExp( + `^${route.path + .split(/(\{[^}]+\})/) + .map((part) => + part.startsWith("{") + ? "([^/]+)" + : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), + ) + .join("")}$`, + ), +})); + +export function matchApiOperation(method: string, path: string) { + for (const { route, keys, pattern } of matchers) { + if (route.method !== method) continue; + const match = pattern.exec(path); + if (match) + return { + route, + params: Object.fromEntries( + keys.map((key, index) => [key, decodeURIComponent(match[index + 1])]), + ), + }; + } + return undefined; +} +export function isDeclaredApiOperation(method: string, path: string): boolean { + return matchApiOperation(method, path) !== undefined; +} + +function jsonSchema( + schema: z.ZodType, + io: "input" | "output" = "input", +): JsonSchema { + const { $schema, ...result } = z.toJSONSchema(schema, { + io, + unrepresentable: "any", + }); + return result; +} +const errorContent = { + "application/json": { schema: { $ref: "#/components/schemas/Error" } }, +}; + +export function generateOpenApi() { + const errors: Record = { + "400": "Invalid request", + "401": "Invalid or revoked credentials", + "403": "Missing scope or required owner session", + "404": "Resource not found", + "409": "Operation conflict", + "415": "Unsupported media type; use application/json", + "429": "Rate limit exceeded", + "500": "Internal error", + "503": "Service unavailable", + }; + const errorResponses = Object.fromEntries( + Object.entries(errors).map(([status, description]) => [ + `Error${status}`, + { description, content: errorContent }, + ]), + ); + const namedBodies: Record = { + JobInput: jobInputSchema, + ManualInvocation: manualInvocationSchema, + JobHandlerTest: jobHandlerTestSchema, + TraceReplayRequest: traceReplaySchema, + }; + const schemas = { + ...document.components.schemas, + ...Object.fromEntries( + Object.entries(namedBodies).map(([name, schema]) => [ + name, + jsonSchema(schema), + ]), + ), + }; + const bodySchema = (schema: z.ZodType) => { + const name = Object.keys(namedBodies).find( + (name) => namedBodies[name] === schema, + ); + return name ? { $ref: `#/components/schemas/${name}` } : jsonSchema(schema); + }; + const paths: Record> = {}; + for (const route of API_ROUTES) { + const parameters = [ + ...Object.entries(route.parameters.shape).map(([name, schema]) => ({ + name, + in: "path", + required: true, + schema: jsonSchema(schema), + })), + ...Object.entries(route.query?.shape ?? {}).map(([name, schema]) => ({ + name, + in: "query", + required: !schema.isOptional(), + schema: jsonSchema(schema, "output"), + })), + ]; + const responses: Record = {}; + for (const status of Object.keys(errors)) { + if (status === "415" && !route.body) continue; + responses[status] = { $ref: `#/components/responses/Error${status}` }; + } + for (const [status, response] of Object.entries( + route.documentation.responses, + ) as [string, any][]) { + responses[status] = status.startsWith("2") + ? { + ...response, + content: response.content ?? { + "application/json": { schema: { type: "object" } }, + }, + } + : { + $ref: `#/components/responses/Error${status}`, + description: response.description, + }; + } + (paths[route.path] ??= {})[route.method.toLowerCase()] = { + ...route.documentation, + description: [ + route.documentation.description, + `Requires the ${route.scope} scope.`, + route.ownerSession + ? "An interactive owner session is required; bearer tokens cannot call this operation." + : "Accepts a scoped bearer token or interactive owner session.", + ] + .filter(Boolean) + .join("\n\n"), + operationId: `${route.method.toLowerCase()}_${route.path.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_|_$/g, "")}`, + tags: [route.path.split("/")[3]], + security: [{ bearerAuth: [] }], + "x-required-scope": route.scope, + "x-owner-session-required": route.ownerSession, + ...(parameters.length ? { parameters } : {}), + ...(route.body + ? { + requestBody: { + required: true, + content: { + "application/json": { schema: bodySchema(route.body) }, + }, + }, + } + : {}), + responses, + }; + } + return { + ...document, + components: { ...document.components, schemas, responses: errorResponses }, + paths, + }; +} diff --git a/packages/app/src/api-document.json b/packages/app/src/api-document.json new file mode 100644 index 00000000..ba2328ec --- /dev/null +++ b/packages/app/src/api-document.json @@ -0,0 +1,673 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Factorize API", + "version": "1.0.0", + "description": "Versioned Factorize REST API. See the hosted docs for examples and OAuth discovery.", + "x-dashboard-auth": "Access-token and authorized-client management and trace replay operations require an interactive owner session; all other operations accept a suitably scoped bearer token or owner session." + }, + "servers": [ + { + "url": "https://app.factorize.sh" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "OAuth2" + } + }, + "schemas": { + "Error": { + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + } + }, + "Run": { + "type": "object", + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "description": "Time the run was created and queued." + }, + "started_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "Time execution launch succeeded. Null until started or when unknown. Runtime starts here; the difference from created_at is queue time including launch preparation." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "Last run update; used as the elapsed runtime endpoint for terminal runs." + } + } + }, + "RunPage": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Run" + } + }, + "nextCursor": { + "type": [ + "string", + "null" + ] + } + } + }, + "ExecutionDiagnostics": { + "type": [ + "object", + "null" + ], + "description": "First terminal backend observation, retained independently of collection and cleanup errors. Null for older or nonterminal runs. Commands and raw backend responses are never included.", + "required": [ + "state", + "detail", + "systemd" + ], + "properties": { + "state": { + "type": "string", + "enum": [ + "succeeded", + "failed", + "stopped" + ] + }, + "detail": { + "type": [ + "string", + "null" + ], + "maxLength": 2048, + "description": "Bounded credential-redacted backend observation detail" + }, + "systemd": { + "type": [ + "object", + "null" + ], + "required": [ + "loadState", + "activeState", + "subState", + "result", + "execMainCode", + "execMainStatus" + ], + "properties": { + "loadState": { + "type": "string", + "maxLength": 64 + }, + "activeState": { + "type": "string", + "maxLength": 64 + }, + "subState": { + "type": "string", + "maxLength": 64 + }, + "result": { + "type": "string", + "maxLength": 64 + }, + "execMainCode": { + "type": [ + "integer", + "null" + ], + "description": "systemd ExecMainCode (for example 1 for exit and 2 for signal)" + }, + "execMainStatus": { + "type": [ + "integer", + "null" + ], + "description": "systemd exit status or signal number; null if unavailable" + } + } + } + } + }, + "HarnessLog": { + "type": [ + "object", + "null" + ], + "description": "Stored redacted harness stderr artifact, or null if unavailable. Uses the combined log for older VMs. Retains at most the first 64 KiB, drops a truncated final line, and redacts recognizable credentials before storage. The object key is a storage locator, not a public or signed URL. This artifact remains available after VM deletion.", + "required": [ + "id", + "kind", + "object_key", + "provider", + "format", + "byte_size", + "sha256", + "state", + "created_at" + ], + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string", + "const": "terminal_log" + }, + "object_key": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "format": { + "type": "string", + "const": "text" + }, + "format_version": { + "type": [ + "string", + "null" + ] + }, + "cli_version": { + "type": [ + "string", + "null" + ] + }, + "source_generation": { + "type": [ + "string", + "null" + ], + "description": "Live source generation bound to the terminal snapshot; unknown for historical receipts." + }, + "native_session_id": { + "type": [ + "string", + "null" + ] + }, + "byte_size": { + "type": [ + "integer", + "string" + ], + "description": "Byte count (PostgreSQL bigint may serialize as a decimal string)", + "maximum": 65536 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "state": { + "type": "string", + "enum": [ + "stored" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + } + } + }, + "TraceSource": { + "type": "object", + "required": [ + "kind", + "path", + "mediaType", + "provider" + ], + "properties": { + "kind": { + "type": "string", + "enum": [ + "execution_stream", + "native_session" + ] + }, + "path": { + "type": "string", + "description": "Guest source path; historical native sources may use a discovery root" + }, + "mediaType": { + "type": "string", + "const": "application/x-ndjson" + }, + "provider": { + "type": "string", + "enum": [ + "codex", + "claude", + "pi" + ] + }, + "formatVersion": { + "type": "string" + }, + "cliVersion": { + "type": "string" + }, + "harnessVersion": { + "type": "string" + }, + "discoverCommand": { + "type": "string", + "description": "Native session discovery only" + } + } + }, + "TraceSources": { + "type": [ + "object", + "null" + ], + "properties": { + "primary": { + "$ref": "#/components/schemas/TraceSource" + }, + "nativeSession": { + "$ref": "#/components/schemas/TraceSource" + } + } + }, + "TraceProjection": { + "type": [ + "object", + "null" + ], + "description": "Committed projection receipt. Null means no durable reconciliation evidence; it does not mean complete.", + "properties": { + "source_kind": { + "type": "string", + "enum": [ + "execution_stream", + "native_session" + ] + }, + "artifact_sha256": { + "type": "string" + }, + "parser_version": { + "type": "string" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "reconciliation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "matched", + "mismatch", + "no_live_cursor", + "reprojected" + ] + }, + "events": { + "type": "integer" + }, + "liveEvents": { + "type": "integer" + }, + "mismatches": { + "type": "integer" + }, + "liveOffset": { + "type": [ + "integer", + "null" + ] + }, + "artifactBytes": { + "type": "integer" + }, + "generation": { + "type": [ + "string", + "null" + ] + }, + "codexCompletion": { + "type": "string", + "enum": [ + "turn.completed", + "missing_turn_completed" + ], + "description": "Completion evidence from the exact retained canonical Codex bytes." + } + } + } + } + }, + "TraceDiagnostics": { + "type": "object", + "required": [ + "provider", + "primarySource", + "sourceVersion", + "projection", + "liveCursor", + "counts", + "artifacts", + "nativeArtifactState", + "fallbackUsed", + "lastReplay" + ], + "properties": { + "provider": { + "type": [ + "string", + "null" + ], + "description": "Agent trace provider; the outer diagnostics provider remains the trigger provider." + }, + "primarySource": { + "type": "string", + "enum": [ + "execution_stream", + "native_session" + ] + }, + "sourceVersion": { + "type": [ + "string", + "null" + ] + }, + "projection": { + "$ref": "#/components/schemas/TraceProjection" + }, + "liveCursor": { + "type": [ + "object", + "null" + ], + "properties": { + "generation": { + "type": "string" + }, + "committed_offset": { + "type": [ + "integer", + "string" + ] + }, + "pending_bytes": { + "type": "integer" + }, + "updated_at": { + "type": "string", + "format": "date-time" + } + } + }, + "counts": { + "type": "object", + "properties": { + "events": { + "type": "integer" + }, + "parse_warnings": { + "type": "integer" + }, + "unknown_events": { + "type": "integer" + }, + "unknownEventRate": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "artifacts": { + "type": "array", + "description": "Tenant/run-scoped receipts; storage keys are locators, never public download URLs. Includes kind, provider, source_path, source_generation, format and source/CLI/harness versions, byte size, checksum and storage state.", + "items": { + "type": "object" + } + }, + "nativeArtifactState": { + "type": "string", + "enum": [ + "stored", + "missing", + "not_applicable" + ], + "description": "Canonical Codex runs do not capture native sessions. Historical native receipts remain readable." + }, + "fallbackUsed": { + "type": "boolean", + "description": "Native projection selected for a run originally declared with an execution stream primary." + }, + "lastReplay": { + "type": [ + "object", + "null" + ], + "description": "Latest completed replay request ID", + "source": null, + "result": null, + "and timestamp; failed requests are retryable and logged.": null + } + } + }, + "TraceReplayResult": { + "type": "object", + "required": [ + "requestId", + "runId", + "status" + ], + "properties": { + "requestId": { + "type": "string", + "format": "uuid" + }, + "runId": { + "type": "string", + "format": "uuid" + }, + "status": { + "type": "string", + "enum": [ + "projected", + "already_projected", + "skipped", + "unrecoverable" + ] + }, + "reason": { + "type": "string", + "enum": [ + "run_active", + "ambiguous_artifacts", + "missing_artifact", + "unsupported_artifact", + "artifact_not_retained" + ] + }, + "sourceKind": { + "type": "string", + "enum": [ + "execution_stream", + "native_session" + ] + }, + "sha256": { + "type": "string" + }, + "parserVersion": { + "type": "string" + }, + "reconciliation": { + "type": "object" + } + } + }, + "RunDetail": { + "allOf": [ + { + "$ref": "#/components/schemas/Run" + } + ], + "type": "object", + "required": [ + "id", + "state", + "execution_diagnostics", + "harness_log" + ], + "properties": { + "id": { + "type": "string" + }, + "state": { + "type": "string" + }, + "trace_generation": { + "type": [ + "string", + "null" + ], + "description": "Live file generation; clients reset trace pagination when it changes." + }, + "trace_projection": { + "$ref": "#/components/schemas/TraceProjection" + }, + "trace_sources": { + "$ref": "#/components/schemas/TraceSources" + }, + "execution_diagnostics": { + "$ref": "#/components/schemas/ExecutionDiagnostics" + }, + "harness_log": { + "$ref": "#/components/schemas/HarnessLog" + }, + "artifact_error": { + "type": [ + "string", + "null" + ], + "description": "Secondary artifact or cleanup error; does not replace execution_diagnostics" + } + } + }, + "RunDiagnostics": { + "type": "object", + "required": [ + "runId", + "jobId", + "state", + "execution", + "harnessLog", + "artifact", + "activity" + ], + "properties": { + "runId": { + "type": "string" + }, + "jobId": { + "type": "string" + }, + "state": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "backendKind": { + "type": "string" + }, + "trace": { + "$ref": "#/components/schemas/TraceDiagnostics" + }, + "traceSources": { + "$ref": "#/components/schemas/TraceSources" + }, + "execution": { + "$ref": "#/components/schemas/ExecutionDiagnostics" + }, + "harnessLog": { + "$ref": "#/components/schemas/HarnessLog" + }, + "artifact": { + "type": "object", + "properties": { + "state": { + "type": "string" + }, + "error": { + "type": [ + "string", + "null" + ], + "description": "Secondary collection or cleanup error. Collection is retried up to three times before cleanup proceeds with partial artifacts. Cleanup failures remain retryable." + } + } + }, + "activity": { + "type": "array", + "items": { + "type": "object" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + } + } + } + } +} diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index c10c4117..6a98b8a5 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -46,7 +46,7 @@ export const manualInvocationSchema = z.object({ prompt: z.string().max(50_000).default(""), data: z.record(z.string(), z.unknown()).optional(), name: z.string().trim().min(1).max(120).optional(), - idempotencyKey: z.string().trim().min(1).max(200).refine(key => !key.startsWith("manual:"), { + idempotencyKey: z.string().trim().min(1).max(200).regex(/^(?!manual:)/, { message: "idempotencyKey must not include the reserved manual: claim-key prefix", }).optional(), }).strict(); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 49a824f7..86957528 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -6,9 +6,10 @@ import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; import { jobHandlerTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; -import { isDeclaredApiOperation } from "./api-contract"; +import { matchApiOperation } from "./api-contract"; function errorResponse(error: unknown): Response { + if (error instanceof URIError) return Response.json({ error: { code: "invalid_request", message: "Invalid path encoding" } }, { status: 400 }); if (error instanceof InvocationError && error.code === "queue_full") return Response.json({ error: { code: error.code, message: error.message } }, { status: 409 }); if (error instanceof z.ZodError) return Response.json({ error: { code: "invalid_request", message: "Request validation failed", details: error.issues } }, { status: 400 }); if (error instanceof ServiceError) { @@ -40,78 +41,20 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP try { const url = new URL(request.url), path = url.pathname, service = new ApiService(env, auth); if (path === "/mcp") return mcp(request, service, env, ctx); - if (!path.startsWith("/api/v1")) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); - if (!isDeclaredApiOperation(request.method, path)) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); - if (request.method === "GET" && path === "/api/v1/exe-connections") return Response.json(await service.listExeConnections()); - if (request.method === "GET" && path === "/api/v1/github-installations") return Response.json(await service.listGitHubInstallations()); - if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets()); - if (request.method === "GET" && path === "/api/v1/job-trigger-availability") return Response.json(await service.listJobTriggerAvailability()); - if (request.method === "POST" && path === "/api/v1/schedules/preview") return Response.json(await service.previewSchedule(await request.json())); - if (request.method === "GET" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.listTailIntegrations()); - if (request.method === "GET" && path === "/api/v1/integrations") return Response.json(await service.integrationStatus()); - if (request.method === "PUT" && path === "/api/v1/integrations/exe") return Response.json(await service.saveExeIntegration(await request.json())); - if (request.method === "POST" && path === "/api/v1/integrations/exe/test") return Response.json(await service.testExeIntegration(await request.json())); - if (request.method === "PUT" && path === "/api/v1/integrations/amp") return Response.json(await service.saveAmpIntegration(await request.json())); - if (request.method === "POST" && path === "/api/v1/integrations/amp/test") return Response.json(await service.testAmpIntegration(await request.json())); - if (request.method === "POST" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.saveTailIntegration(await request.json()), { status: 201 }); - if (request.method === "GET" && path === "/api/v1/providers/linear/projects") return Response.json(await service.linearProjects()); - if (request.method === "GET" && path === "/api/v1/providers/linear/options") return Response.json(await service.linearOptions()); - if (request.method === "GET" && path === "/api/v1/providers/clickup/lists") return Response.json(await service.clickUpLists()); - if (request.method === "GET" && path === "/api/v1/providers/clickup/options") return Response.json(await service.clickUpOptions(url.searchParams.get("listId") ?? "")); - if (request.method === "GET" && path === "/api/v1/providers/github/installations") return Response.json(await service.listGitHubInstallations()); - if (request.method === "GET" && path === "/api/v1/access/authorized-clients") return Response.json(await service.listAuthorizedClients()); - if (request.method === "GET" && path === "/api/v1/access-tokens") return Response.json(await service.listAccessTokens()); - if (request.method === "POST" && path === "/api/v1/access-tokens") return Response.json(await service.createAccessToken(await request.json()), { status: 201 }); - const accessTokenMatch = path.match(/^\/api\/v1\/access-tokens\/([^/]+)$/); - if (accessTokenMatch && request.method === "DELETE") return Response.json(await service.revokeAccessToken(decodeURIComponent(accessTokenMatch[1]))); - const authorizedClientMatch = path.match(/^\/api\/v1\/access\/authorized-clients\/([^/]+)$/); - if (authorizedClientMatch && request.method === "DELETE") return Response.json(await service.revokeAuthorizedClient(decodeURIComponent(authorizedClientMatch[1]))); - const integrationMatch = path.match(/^\/api\/v1\/integrations\/(exe|amp)\/([^/]+)$/); - if (integrationMatch && request.method === "DELETE") return Response.json(await service.removeIntegration(integrationMatch[1] as "exe" | "amp", decodeURIComponent(integrationMatch[2]))); - const tailMatch = path.match(/^\/api\/v1\/integrations\/cloudflare-tail\/([^/]+)$/); - if (tailMatch && request.method === "PUT") return Response.json(await service.saveTailIntegration({ ...await request.json() as any, integrationId: decodeURIComponent(tailMatch[1]) })); - if (tailMatch && request.method === "DELETE") return Response.json(await service.removeTailIntegration(decodeURIComponent(tailMatch[1]))); - const tailTestMatch = path.match(/^\/api\/v1\/integrations\/cloudflare-tail\/([^/]+)\/test$/); - if (tailTestMatch && request.method === "POST") return Response.json(await service.testTailIntegration(decodeURIComponent(tailTestMatch[1]))); - const githubRepositoriesMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)\/repositories$/); - if (githubRepositoriesMatch && request.method === "GET") return Response.json(await service.githubRepositories(Number(githubRepositoriesMatch[1]))); - const githubOptionsMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)\/repositories\/(\d+)\/issue-options$/); - if (githubOptionsMatch && request.method === "GET") return Response.json(await service.githubIssueOptions(Number(githubOptionsMatch[1]), Number(githubOptionsMatch[2]))); - const githubInstallationMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)$/); - if (githubInstallationMatch && request.method === "DELETE") return Response.json(await service.removeGitHubInstallation(Number(githubInstallationMatch[1]))); - const exeDiagnosticMatch = path.match(/^\/api\/v1\/integrations\/exe\/([^/]+)\/diagnostics$/); - if (exeDiagnosticMatch && request.method === "POST") return Response.json(await service.diagnoseExeIntegration(decodeURIComponent(exeDiagnosticMatch[1]))); - if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs()); - if (request.method === "POST" && path === "/api/v1/jobs") return Response.json(await service.createJob(jobInputSchema.parse(await request.json())), { status: 201 }); - if (request.method === "POST" && path === "/api/v1/job-handlers/test") return Response.json(await service.testJobHandler(jobHandlerTestSchema.parse(await request.json()))); - const invocationMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/invocations$/); - if (invocationMatch && request.method === "POST") return Response.json(await service.invokeJob(decodeURIComponent(invocationMatch[1]), manualInvocationSchema.parse(await request.json())), { status: 202 }); - const jobEventsMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/events$/); - if (jobEventsMatch && request.method === "GET") return Response.json(await service.listJobEvents(decodeURIComponent(jobEventsMatch[1]), z.coerce.number().int().min(1).max(100).default(50).parse(url.searchParams.get("limit") ?? 50))); - const enabledMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/(enable|disable)$/); - if (enabledMatch && request.method === "POST") return Response.json(await service.setJobEnabled(decodeURIComponent(enabledMatch[1]), enabledMatch[2] === "enable")); - const jobMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)$/); - if (jobMatch && request.method === "GET") return Response.json(await service.getJob(decodeURIComponent(jobMatch[1]))); - if (jobMatch && request.method === "PUT") return Response.json(await service.updateJob(decodeURIComponent(jobMatch[1]), jobInputSchema.parse(await request.json()))); - if (jobMatch && request.method === "DELETE") return Response.json(await service.deleteJob(decodeURIComponent(jobMatch[1]))); - if (request.method === "GET" && path === "/api/v1/runs") { const q = listRunsSchema.parse(queryInput(url)); return Response.json(await service.listRuns(queryOf(q))); } - if (request.method === "GET" && path === "/api/v1/search") return Response.json(await service.search(url.searchParams.get("q") ?? "")); - if (request.method === "GET" && path === "/api/v1/webhooks/deliveries") return Response.json(await service.listWebhookDeliveries(url.searchParams)); - const webhookDeliveryMatch = path.match(/^\/api\/v1\/webhooks\/deliveries\/([^/]+)$/); - if (webhookDeliveryMatch && request.method === "GET") return Response.json(await service.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1]))); - const runMatch = path.match(/^\/api\/v1\/runs\/([^/]+)$/); - if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); - const traceMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/trace$/); - if (traceMatch && request.method === "GET") return Response.json(await service.getRunTrace(decodeURIComponent(traceMatch[1]), Math.max(0, Number(url.searchParams.get("after") ?? 0)), Math.max(1, Math.min(200, Number(url.searchParams.get("limit") ?? 100))))); - const replayMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/trace\/replay$/); - if (replayMatch && request.method === "POST") return Response.json(await service.replayRunTrace(decodeURIComponent(replayMatch[1]), await request.json())); - const runDiagnosticMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/diagnostics$/); - if (runDiagnosticMatch && request.method === "GET") return Response.json(await service.getRunDiagnostics(decodeURIComponent(runDiagnosticMatch[1]))); - const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); - if (stopMatch && request.method === "POST") return Response.json(await service.stopRun(decodeURIComponent(stopMatch[1]))); - const killMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/kill$/); - if (killMatch && request.method === "POST") return Response.json(await service.killRun(decodeURIComponent(killMatch[1]))); - return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); + const matched = matchApiOperation(request.method, path); + if (!matched) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); + const { route, params } = matched; + if (!auth.scopes.includes(route.scope)) throw new ServiceError(403, "insufficient_scope", `The ${route.scope} scope is required.`); + if (route.ownerSession && auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); + let body: unknown; + if (route.body) { + if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") throw new ServiceError(415, "unsupported_media_type", "Content-Type must be application/json."); + try { body = await request.json(); } + catch { throw new ServiceError(400, "invalid_request", "Request body must be valid JSON."); } + body = route.body.parse(body); + } + const query = route.query?.parse(queryInput(url)); + return Response.json(await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }), { status: route.status }); } catch (error) { return errorResponse(error); } } diff --git a/packages/app/src/trace-replay-schemas.ts b/packages/app/src/trace-replay-schemas.ts new file mode 100644 index 00000000..571b1e56 --- /dev/null +++ b/packages/app/src/trace-replay-schemas.ts @@ -0,0 +1,18 @@ +import { z } from "zod"; + +export const traceReplayRunIdSchema = z.uuid(); +export const traceReplaySchema = z + .object({ + requestId: z + .uuid() + .describe( + "Tenant-scoped idempotency key; preserve it when retrying. Use a new key to reconsider a previously skipped or unrecoverable run.", + ), + source: z + .enum(["primary", "native_session"]) + .default("primary") + .describe( + "Primary replays the persisted source declaration (native for historical runs); native_session selects retained native bytes for other providers or historical native-only Codex runs. Canonical Codex runs reject native replay.", + ), + }) + .strict(); diff --git a/packages/app/src/trace-replay.ts b/packages/app/src/trace-replay.ts index a252439b..953b591a 100644 --- a/packages/app/src/trace-replay.ts +++ b/packages/app/src/trace-replay.ts @@ -6,8 +6,8 @@ import { ArtifactRepository } from "./postgres/artifact-repository"; import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./postgres/trace-projection-repository"; import { traceMetric } from "./trace-observability"; -export const traceReplayRunIdSchema = z.uuid(); -export const traceReplaySchema = z.object({ requestId: z.uuid(), source: z.enum(["primary", "native_session"]).default("primary") }).strict(); +import { traceReplayRunIdSchema, traceReplaySchema } from "./trace-replay-schemas"; +export { traceReplayRunIdSchema, traceReplaySchema } from "./trace-replay-schemas"; export class TraceReplayError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } } /** One run per request bounds work; clients checkpoint request IDs while paging runs. diff --git a/packages/app/test/api-boundary.test.ts b/packages/app/test/api-boundary.test.ts new file mode 100644 index 00000000..6386141d --- /dev/null +++ b/packages/app/test/api-boundary.test.ts @@ -0,0 +1,332 @@ +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { parse } from "yaml"; +import Ajv2020 from "ajv/dist/2020"; +import { ProtectedApiHandler } from "../src/protected-api"; +import { ApiService, ServiceError } from "../src/flow-service"; +import { InvocationError } from "../src/job-domain"; +import type { Env, OAuthProps } from "../src/types"; + +vi.mock("cloudflare:workers", () => ({ + WorkerEntrypoint: class { + constructor( + public ctx: ExecutionContext, + public env: Env, + ) {} + }, +})); + +afterEach(() => vi.restoreAllMocks()); +const openapi = parse( + readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"), +); +const auth = { + tenantId: "tenant-1", + userId: "user-1", + sessionVersion: 1, + authMethod: "session", + scopes: ["flows:read", "flows:write", "runs:read", "runs:write"], +} as OAuthProps; + +function request( + method: string, + path: string, + body?: unknown, + options: { raw?: string; mediaType?: string; auth?: OAuthProps } = {}, +) { + const worker = new ProtectedApiHandler( + { props: options.auth ?? auth } as ExecutionContext, + {} as Env, + ); + return worker.fetch( + new Request("https://example.com" + path, { + method, + ...(body !== undefined || options.raw !== undefined + ? { + body: options.raw ?? JSON.stringify(body), + headers: { + "Content-Type": options.mediaType ?? "application/json", + }, + } + : {}), + }), + ); +} + +async function assertResponse( + response: Response, + method: string, + template: string, + status: number, +) { + expect(response.status).toBe(status); + const mediaType = response.headers.get("content-type")?.split(";")[0]; + const reference = + openapi.paths[template][method.toLowerCase()].responses[String(status)]; + expect(reference).toBeDefined(); + const documented = reference.$ref + ? openapi.components.responses[reference.$ref.split("/").at(-1)] + : reference; + const schema = documented.content[mediaType!].schema; + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema({ + $id: "https://factorize.test/contract", + components: openapi.components, + }); + const validate = ajv.compile({ + $id: "https://factorize.test/contract/response", + components: openapi.components, + ...schema, + }); + const body = await response.json(); + expect(validate(body), JSON.stringify(validate.errors)).toBe(true); + return body as any; +} + +const jobInput = { + name: "Job", + slug: "job", + promptTemplate: "Do work", + executionTargetId: "exe-1", +}; + +describe("Worker OpenAPI request/response boundaries", () => { + it("returns a documented JSON array for a read", async () => { + vi.spyOn(ApiService.prototype, "listJobs").mockResolvedValue([]); + expect( + await assertResponse( + await request("GET", "/api/v1/jobs"), + "GET", + "/api/v1/jobs", + 200, + ), + ).toEqual([]); + }); + + it("validates and normalizes job input and uses the catalog's 201 status", async () => { + const create = vi + .spyOn(ApiService.prototype, "createJob") + .mockResolvedValue({ id: "job-1", ...jobInput } as any); + await assertResponse( + await request("POST", "/api/v1/jobs", jobInput), + "POST", + "/api/v1/jobs", + 201, + ); + expect(create).toHaveBeenCalledWith({ + ...jobInput, + concurrencyLimit: 1, + triggers: [], + }); + for (const body of [ + {}, + { ...jobInput, concurrencyLimit: 51 }, + { ...jobInput, unexpected: true }, + ]) { + const result = await assertResponse( + await request("POST", "/api/v1/jobs", body), + "POST", + "/api/v1/jobs", + 400, + ); + expect(result.error.code).toBe("invalid_request"); + } + expect(create).toHaveBeenCalledTimes(1); + }); + + it("validates parsed method/path parameters and executes the existing service", async () => { + vi.spyOn(ApiService.prototype as any, "authorize").mockResolvedValue( + undefined, + ); + const setEnabled = vi.fn().mockResolvedValue(true); + vi.spyOn(ApiService.prototype as any, "jobs").mockReturnValue({ + setEnabled, + }); + const result = await assertResponse( + await request("POST", "/api/v1/jobs/job%20one/disable"), + "POST", + "/api/v1/jobs/{jobId}/disable", + 200, + ); + expect(result).toEqual({ id: "job one", enabled: false }); + expect(setEnabled).toHaveBeenCalledWith( + "job one", + false, + expect.any(String), + ); + await assertResponse( + await request( + "GET", + "/api/v1/providers/github/installations/not-a-number/repositories", + ), + "GET", + "/api/v1/providers/github/installations/{installationId}/repositories", + 400, + ); + await assertResponse( + await request("GET", "/api/v1/jobs/%ZZ"), + "GET", + "/api/v1/jobs/{jobId}", + 400, + ); + }); + + it("returns documented 202 invocation bodies and 409 queue errors", async () => { + const invoke = vi + .spyOn(ApiService.prototype, "invokeJob") + .mockResolvedValue({ + invocationId: "inv-1", + runId: "run-1", + state: "queued", + duplicate: false, + }); + await assertResponse( + await request("POST", "/api/v1/jobs/job-1/invocations", { + data: { issue: "GEN-2152" }, + }), + "POST", + "/api/v1/jobs/{jobId}/invocations", + 202, + ); + expect(invoke).toHaveBeenCalledWith("job-1", { + prompt: "", + data: { issue: "GEN-2152" }, + }); + invoke.mockRejectedValue( + new InvocationError("queue_full", "Queue is full"), + ); + const result = await assertResponse( + await request("POST", "/api/v1/jobs/job-1/invocations", {}), + "POST", + "/api/v1/jobs/{jobId}/invocations", + 409, + ); + expect(result.error.code).toBe("queue_full"); + await assertResponse( + await request("POST", "/api/v1/jobs/job-1/invocations", { + idempotencyKey: "manual:reserved", + }), + "POST", + "/api/v1/jobs/{jobId}/invocations", + 400, + ); + }); + + it("rejects malformed JSON and unsupported media types before invoking the service", async () => { + const create = vi.spyOn(ApiService.prototype, "createJob"); + const malformed = await assertResponse( + await request("POST", "/api/v1/jobs", undefined, { raw: "{" }), + "POST", + "/api/v1/jobs", + 400, + ); + expect(malformed.error.code).toBe("invalid_request"); + await assertResponse( + await request("POST", "/api/v1/jobs", jobInput, { + mediaType: "text/plain", + }), + "POST", + "/api/v1/jobs", + 415, + ); + await assertResponse( + await request("POST", "/api/v1/jobs", null), + "POST", + "/api/v1/jobs", + 400, + ); + expect(create).not.toHaveBeenCalled(); + }); + + it("enforces scope and interactive-session metadata and preserves service identity errors", async () => { + const list = vi.spyOn(ApiService.prototype, "listJobs"); + const denied = await request("GET", "/api/v1/jobs", undefined, { + auth: { ...auth, scopes: [] }, + }); + expect(denied.headers.get("www-authenticate")).toContain( + "insufficient_scope", + ); + await assertResponse(denied, "GET", "/api/v1/jobs", 403); + expect(list).not.toHaveBeenCalled(); + list.mockRejectedValue( + new ServiceError(401, "invalid_token", "Session revoked"), + ); + await assertResponse( + await request("GET", "/api/v1/jobs"), + "GET", + "/api/v1/jobs", + 401, + ); + await assertResponse( + await request("GET", "/api/v1/access-tokens", undefined, { + auth: { ...auth, authMethod: "access_token" }, + }), + "GET", + "/api/v1/access-tokens", + 403, + ); + await assertResponse( + await request( + "POST", + "/api/v1/runs/11111111-1111-4111-8111-111111111111/trace/replay", + { requestId: "11111111-1111-4111-8111-111111111111" }, + { auth: { ...auth, authMethod: "access_token" } }, + ), + "POST", + "/api/v1/runs/{runId}/trace/replay", + 403, + ); + }); + + it("validates pagination and trace query limits and returns documented page schemas", async () => { + const list = vi + .spyOn(ApiService.prototype, "listRuns") + .mockResolvedValue({ items: [], nextCursor: null }); + await assertResponse( + await request("GET", "/api/v1/runs?limit=100"), + "GET", + "/api/v1/runs", + 200, + ); + expect(list.mock.calls[0][0].get("limit")).toBe("100"); + for (const query of ["limit=0", "limit=101", "limit=NaN", "state=invalid"]) + await assertResponse( + await request("GET", "/api/v1/runs?" + query), + "GET", + "/api/v1/runs", + 400, + ); + const trace = vi + .spyOn(ApiService.prototype, "getRunTrace") + .mockResolvedValue({ items: [], nextCursor: null }); + await assertResponse( + await request("GET", "/api/v1/runs/run-1/trace?after=0&limit=200"), + "GET", + "/api/v1/runs/{runId}/trace", + 200, + ); + expect(trace).toHaveBeenCalledWith("run-1", 0, 200); + for (const query of ["after=-1", "after=NaN", "limit=201"]) + await assertResponse( + await request("GET", "/api/v1/runs/run-1/trace?" + query), + "GET", + "/api/v1/runs/{runId}/trace", + 400, + ); + }); + + it("rejects undeclared methods and paths at the Worker boundary", async () => { + expect((await request("PATCH", "/api/v1/jobs")).status).toBe(404); + expect((await request("GET", "/api/v1/unknown")).status).toBe(404); + const missing = vi + .spyOn(ApiService.prototype, "getJob") + .mockRejectedValue(new ServiceError(404, "not_found", "Job not found")); + await assertResponse( + await request("GET", "/api/v1/jobs/missing"), + "GET", + "/api/v1/jobs/{jobId}", + 404, + ); + expect(missing).toHaveBeenCalledWith("missing"); + }); +}); diff --git a/packages/app/test/api-contract.test.ts b/packages/app/test/api-contract.test.ts index 13cba510..4357e2b1 100644 --- a/packages/app/test/api-contract.test.ts +++ b/packages/app/test/api-contract.test.ts @@ -1,16 +1,119 @@ +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { API_OPERATIONS, isDeclaredApiOperation } from "../src/api-contract"; +import { parse } from "yaml"; +import Ajv2020 from "ajv/dist/2020"; +import { + API_ROUTES, + generateOpenApi, + isDeclaredApiOperation, + matchApiOperation, +} from "../src/api-contract"; + +export const openapi = parse( + readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"), +); +const methods = new Set([ + "get", + "post", + "put", + "patch", + "delete", + "head", + "options", + "trace", +]); describe("versioned API contract", () => { - it("declares only versioned application endpoints", () => { - expect(API_OPERATIONS.length).toBeGreaterThan(40); - expect(API_OPERATIONS.every(([, path]) => path.startsWith("/api/v1/"))).toBe(true); + it("has full bidirectional method/path equality with the executable catalog", () => { + const documented = Object.entries(openapi.paths).flatMap(([path, item]) => + Object.keys(item as object) + .filter((method) => methods.has(method)) + .map((method) => `${method.toUpperCase()} ${path}`), + ); + const executable = API_ROUTES.map( + (route) => `${route.method} ${route.path}`, + ); + expect(new Set(executable).size).toBe(executable.length); + expect(documented.sort()).toEqual(executable.sort()); + expect(API_ROUTES.every((route) => route.path.startsWith("/api/v1/"))).toBe( + true, + ); + expect(openapi).toEqual(generateOpenApi()); }); - it("matches declared parameterized routes and rejects legacy routes", () => { - expect(isDeclaredApiOperation("GET", "/api/v1/providers/github/installations/42/repositories")).toBe(true); - expect(isDeclaredApiOperation("POST", "/api/v1/integrations/cloudflare-tail/tail-1/test")).toBe(true); - expect(isDeclaredApiOperation("GET", "/api" + "/connections/status")).toBe(false); + it("matches every catalog operation and decodes parameters without a second route list", () => { + for (const route of API_ROUTES) { + const path = route.path.replace(/\{[^}]+\}/g, "42"); + expect(matchApiOperation(route.method, path)?.route).toBe(route); + expect(isDeclaredApiOperation("PATCH", path)).toBe(false); + expect( + isDeclaredApiOperation(route.method, path + "/extra/extra/extra"), + ).toBe(false); + } + expect(matchApiOperation("GET", "/api/v1/jobs/job%20one")?.params).toEqual({ + jobId: "job one", + }); + expect(isDeclaredApiOperation("GET", "/api" + "/connections/status")).toBe( + false, + ); expect(isDeclaredApiOperation("GET", "/api/v1/not-declared")).toBe(false); }); + + it("documents validation, authorization, media types, and resolvable response schemas for every operation", () => { + for (const route of API_ROUTES) { + const operation = openapi.paths[route.path][route.method.toLowerCase()]; + expect(operation["x-required-scope"]).toBe(route.scope); + expect(operation["x-owner-session-required"]).toBe(route.ownerSession); + expect( + operation.parameters + ?.filter((p: any) => p.in === "path") + .map((p: any) => p.name) + .sort() ?? [], + ).toEqual(Object.keys(route.parameters.shape).sort()); + expect(Boolean(operation.requestBody)).toBe(Boolean(route.body)); + expect(operation.responses[route.status]).toBeDefined(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema({ + $id: "https://factorize.test/contract", + components: openapi.components, + }); + for (const parameter of operation.parameters ?? []) + ajv.compile({ components: openapi.components, ...parameter.schema }); + if (operation.requestBody) + ajv.compile({ + components: openapi.components, + ...operation.requestBody.content["application/json"].schema, + }); + for (const [status, response] of Object.entries(operation.responses) as [ + string, + any, + ][]) { + const resolved = response.$ref + ? openapi.components.responses[response.$ref.split("/").at(-1)] + : response; + expect(resolved.content["application/json"].schema).toBeDefined(); + // Resolve every local reference, including nested references in trace diagnostics. + ajv.compile({ + $id: `https://factorize.test/contract/${operation.operationId}/${status}`, + components: openapi.components, + ...resolved.content["application/json"].schema, + }); + } + } + }); + + it("configures Mintlify to render the exact committed artifact", () => { + const docs = JSON.parse( + readFileSync(new URL("../../docs/docs.json", import.meta.url), "utf8"), + ); + expect( + docs.navigation.tabs.find((tab: any) => tab.tab === "API Reference") + .openapi, + ).toBe("/openapi.yaml"); + const reference = readFileSync( + new URL("../../docs/api/reference.mdx", import.meta.url), + "utf8", + ); + expect(reference).not.toMatch(/^\|/m); + }); }); diff --git a/packages/app/test/manual-invocation.test.ts b/packages/app/test/manual-invocation.test.ts index 8ef10434..73ccce07 100644 --- a/packages/app/test/manual-invocation.test.ts +++ b/packages/app/test/manual-invocation.test.ts @@ -31,7 +31,7 @@ describe("manual invocation API and shared service", () => { const response = await protectedApiFetch(new Request("https://example.com" + (transport === "REST" ? "/api/v1/jobs/job-1/invocations" : "/mcp"), { method: "POST", headers: { Host: "example.com", "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(transport === "REST" ? body : { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "invoke_job", arguments: { jobId: "job-1", ...body } } }), - }), env, {} as any, {} as any); + }), env, { scopes: ["runs:write"], authMethod: "session" } as any, {} as any); if (transport === "REST") return response; expect(response.status).toBe(200); const text = await response.text(); diff --git a/packages/app/test/run-diagnostics-contract.test.ts b/packages/app/test/run-diagnostics-contract.test.ts index ffa272e2..61c0417f 100644 --- a/packages/app/test/run-diagnostics-contract.test.ts +++ b/packages/app/test/run-diagnostics-contract.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { parse } from "yaml"; import { readFileSync } from "node:fs"; import { ApiService } from "../src/flow-service"; import { IdentityRepository } from "../src/postgres/identity-repository"; @@ -60,10 +61,20 @@ describe("run diagnostics API boundary", () => { await expect(service.replayRunTrace(crypto.randomUUID(), { requestId: crypto.randomUUID() })).rejects.toMatchObject({ status: 401 }); }); it("documents the externally visible fields and schema references", () => { - const spec = readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"); - for (const field of ["TraceReplayRequest:", "TraceReplayResult:", "TraceDiagnostics:", "trace_generation:", "trace_projection:", "traceSources:", "trace_sources:", "harnessVersion:", "cliVersion:", "execution_diagnostics", "harness_log", "execution:", "harnessLog:", "execMainCode", "execMainStatus", "activeState", "subState", "object_key"]) - expect(spec).toContain(field); - expect(spec).toContain("$ref: '#/components/schemas/RunDetail'"); - expect(spec).toContain("$ref: '#/components/schemas/RunDiagnostics'"); + const spec = parse(readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8")); + const schemas = spec.components.schemas; + for (const [name, fields] of Object.entries({ + RunDetail: ["trace_generation", "trace_projection", "trace_sources", "execution_diagnostics", "harness_log"], + RunDiagnostics: ["traceSources", "execution", "harnessLog"], + TraceSource: ["harnessVersion", "cliVersion"], + TraceReplayRequest: ["requestId", "source"], + TraceReplayResult: ["requestId", "runId", "status"], + HarnessLog: ["object_key", "source_generation"], + })) for (const field of fields) expect(schemas[name].properties[field]).toBeDefined(); + expect(schemas.TraceDiagnostics.properties.nativeArtifactState.enum).toContain("not_applicable"); + expect(schemas.ExecutionDiagnostics.properties.systemd.properties).toHaveProperty("execMainStatus"); + expect(spec.paths["/api/v1/runs/{runId}"].get.responses["200"].content["application/json"].schema.$ref).toBe("#/components/schemas/RunDetail"); + expect(spec.paths["/api/v1/runs/{runId}/diagnostics"].get.responses["200"].content["application/json"].schema.$ref).toBe("#/components/schemas/RunDiagnostics"); + expect(spec.paths["/api/v1/runs/{runId}/trace/replay"].post.requestBody.content["application/json"].schema.$ref).toBe("#/components/schemas/TraceReplayRequest"); }); }); diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.json index 26a78267..6fa8c690 100644 --- a/packages/app/tsconfig.json +++ b/packages/app/tsconfig.json @@ -7,7 +7,8 @@ "strict": true, "skipLibCheck": true, "types": ["@cloudflare/workers-types", "@cloudflare/vitest-pool-workers", "vitest/globals"], - "noEmit": true + "noEmit": true, + "resolveJsonModule": true }, "include": ["src/**/*.ts", "test/**/*.ts"] } diff --git a/packages/docs/README.md b/packages/docs/README.md index e990f2d4..279f8f0b 100644 --- a/packages/docs/README.md +++ b/packages/docs/README.md @@ -1,5 +1,7 @@ # Factorize documentation -This is an independently previewable and publishable [Mintlify](https://mintlify.com) package. Install the Mintlify CLI, run `npm run dev --workspace=factorize-docs`, and open the local URL. Run `npm run validate --workspace=factorize-docs` in CI; it checks the route inventory against the Worker and verifies the LLM exports. Publish with `npm run deploy --workspace=factorize-docs` from a configured Mintlify project. See [the publishing runbook](../../docs/mintlify.md) for the repository, custom-domain, DNS, and verification configuration. +This is an independently previewable and publishable [Mintlify](https://mintlify.com) package. Install the Mintlify CLI, run `npm run dev --workspace=factorize-docs`, and open the local URL. Publish with `npm run deploy --workspace=factorize-docs` from a configured Mintlify project. See [the publishing runbook](../../docs/mintlify.md) for repository, custom-domain, DNS, and verification configuration. -`openapi.yaml`, `llms.txt`, and `llms-full.txt` are checked-in artifacts so API clients and LLMs can consume the contract without rendering the site. +The API Reference tab renders `openapi.yaml` directly. This is the generated API artifact consumed by the docs, clients, and CI. Update the executable catalog in `packages/app/src/api-contract.ts`, run `npm run generate:openapi` from the repository root, and commit the resulting YAML. Shared schemas and general metadata live beside the catalog. + +Run `npm run validate --workspace=factorize-docs` to check artifact freshness, parsed method/path equality, Mintlify configuration, and LLM exports. CI also regenerates the artifact and rejects any diff. `llms.txt` and `llms-full.txt` provide documentation summaries and point to the generated contract for operation details. diff --git a/packages/docs/api/openapi.mdx b/packages/docs/api/openapi.mdx index 2768ff0c..1f694ee7 100644 --- a/packages/docs/api/openapi.mdx +++ b/packages/docs/api/openapi.mdx @@ -1,12 +1,16 @@ --- title: OpenAPI definition -description: Download the machine-readable Factorize REST contract. +description: Download the verified Factorize REST contract. --- -The checked-in definition is [`openapi.yaml`](https://github.com/GenerationSoftware/factorize/blob/main/packages/docs/openapi.yaml). It covers every `/api/v1` operation, bearer security, scopes, request schemas, pagination, and the common error envelope. +[Download openapi.yaml](/openapi.yaml). The API Reference tab renders this exact file, and clients can use it to generate SDKs or inspect request and response schemas. + +The definition is generated from the executable route catalog in `packages/app/src/api-contract.ts`, which the Worker dispatches in `protected-api.ts`. To change an API operation, update its catalog entry (method, path, scope, validation, handler, and documentation), then run: ```bash -curl -O https://raw.githubusercontent.com/GenerationSoftware/factorize/main/packages/docs/openapi.yaml +npm run generate:openapi ``` -Run `npm run validate --workspace=factorize-docs` before publishing. The validator checks that the route inventory in the Worker and the OpenAPI paths remain synchronized. +Commit `packages/docs/openapi.yaml` with the change. CI regenerates it and rejects a diff; parsed contract tests also require exact method/path equality with the executable catalog. Shared schemas and general API metadata live beside the catalog in `flow-schemas.ts`, `trace-replay-schemas.ts`, and `api-document.json`. + +Run `npm run validate --workspace=factorize-docs` to verify the generated artifact, parsed operation contract, and Mintlify configuration before publishing. diff --git a/packages/docs/api/reference.mdx b/packages/docs/api/reference.mdx index 97a9f6ba..20da9add 100644 --- a/packages/docs/api/reference.mdx +++ b/packages/docs/api/reference.mdx @@ -1,62 +1,12 @@ --- title: REST API reference -description: Complete implementation-accurate operation inventory. +description: How to use the generated API reference. --- -All paths are relative to `APP_ORIGIN` and require a bearer token or browser owner session. Errors use `{ "error": { "code": "...", "message": "..." } }`; malformed JSON/schema input returns `400 invalid_request`, missing resources `404 not_found`, invalid/revoked tokens `401 invalid_token`, and missing scopes `403 insufficient_scope`. +The **API Reference** tab renders every application operation directly from [openapi.yaml](/openapi.yaml), including request validation, required scopes, owner-session restrictions, and JSON response schemas. This is the same generated artifact verified by CI and available to API clients. -`GET /healthz` is the unauthenticated liveness check and returns `{ "ok": true }`. It is an infrastructure probe, not an application API operation. +All application endpoints use `/api/v1`. Authenticate with a scoped bearer token or an interactive owner session; credential management and trace replay require an interactive owner session. Errors use `{ "error": { "code": "...", "message": "..." } }`. -## Discovery and read operations +`GET /healthz` is the unauthenticated infrastructure liveness probe and returns `{ "ok": true }`. It is outside the application API contract. -| Method | Path | Scope | Result | -| --- | --- | --- | --- | -| GET | `/api/v1/exe-connections` | flows:read | Safe exe connection metadata | -| GET | `/api/v1/github-installations` | flows:read | GitHub App installations | -| GET | `/api/v1/execution-targets` | flows:read | Non-secret target metadata/capabilities | -| GET | `/api/v1/job-trigger-availability` | flows:read | Currently available trigger kinds | -| GET | `/api/v1/integrations/cloudflare-tail` | flows:read | Tail integrations and reference counts | -| GET | `/api/v1/jobs` | flows:read | Jobs with `currentRuns`, `maxConcurrency`, triggers | -| GET | `/api/v1/jobs/{jobId}` | flows:read | One job | -| GET | `/api/v1/jobs/{jobId}/events?limit=50` | runs:read | Webhook activity; limit 1–100 | -| GET | `/api/v1/runs/{runId}` | runs:read | Full prompt, context, invocation, execution, output, activity | -| GET | `/api/v1/runs/{runId}/diagnostics` | runs:read | Credential-safe lifecycle checks and activity | -| GET | `/api/v1/runs/{runId}/trace` | runs:read | Paginated trace events | -| GET | `/api/v1/search?q=` | runs:read | Search jobs, runs, and metadata | - -## Integrations and provider discovery - -| Method | Path | Scope | Result | -| --- | --- | --- | --- | -| GET | `/api/v1/integrations` | flows:read | Credential-safe installed integration status | -| PUT/DELETE | `/api/v1/integrations/{exe\|amp}[/{connectionId}]` | flows:write | Save or remove an execution integration | -| POST | `/api/v1/integrations/{exe\|amp}/test` | flows:write | Test supplied or saved credentials | -| POST/PUT/DELETE | `/api/v1/integrations/cloudflare-tail[/{integrationId}]` | flows:write | Create, update, or remove a Tail integration | -| POST | `/api/v1/integrations/cloudflare-tail/{integrationId}/test` | flows:write | Test a Tail integration | -| GET | `/api/v1/providers/linear/{projects\|options}` | flows:read | Linear job-trigger resources | -| GET | `/api/v1/providers/clickup/{lists\|options}` | flows:read | ClickUp job-trigger resources | -| GET | `/api/v1/providers/github/installations` | flows:read | GitHub installations | -| GET | `/api/v1/providers/github/installations/{installationId}/repositories` | flows:read | Installation repositories | -| GET | `/api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options` | flows:read | GitHub issue-trigger resources | -| DELETE | `/api/v1/providers/github/installations/{installationId}` | flows:write | Disconnect an installation | - -Access-token and authorized-client management under `/api/v1/access-tokens` and `/api/v1/access/authorized-clients` is versioned and uses the same error contract, but deliberately requires an interactive owner session to prevent bearer credentials from minting or revoking credentials. - -## Writes and runs - -| Method | Path | Scope | Notes | -| --- | --- | --- | --- | -| POST | `/api/v1/jobs` | flows:write | Create; returns `201` | -| PUT | `/api/v1/jobs/{jobId}` | flows:write | Replace configuration | -| DELETE | `/api/v1/jobs/{jobId}` | flows:write | Deletes job and queued invocation history | -| POST | `/api/v1/jobs/{jobId}/enable` | flows:write | Enable | -| POST | `/api/v1/jobs/{jobId}/disable` | flows:write | Disable | -| POST | `/api/v1/job-handlers/test` | flows:write | Isolated synchronous test; no run | -| POST | `/api/v1/integrations/exe/{connectionId}/diagnostics` | flows:write | Probe permissions and a disposable VM's agent/model integration | -| POST | `/api/v1/jobs/{jobId}/invocations` | runs:write | Manual invocation; returns `202` | -| GET | `/api/v1/runs?jobId=&state=&contextQuery=&limit=&cursor=` | runs:read | `{items,nextCursor}`; limit 1–100 | -| POST | `/api/v1/runs/{runId}/stop` | runs:write | Stop an active run | -| POST | `/api/v1/runs/{runId}/kill` | runs:write | Immediately terminalize a non-terminal run, release capacity, and clean up its backend | -| POST | `/api/v1/schedules/preview` | flows:read | `{nextRunAt}` for `{cron,timezone}` | - -Job creation requires `name` (1–120), `slug` (lowercase, up to 30), `promptTemplate` (1–50,000), `executionTargetId`, and optional `model`, `effort`, `concurrencyLimit`, and `triggers`. Manual invocation accepts an optional display `name` (1–120), `prompt` (default empty), an optional JSON object `data` (default `{}`), and an optional unique `idempotencyKey` (1–200; never prefix it with reserved `manual:`). The display name is used for the run when supplied; prompt and data are exposed under the manual trigger slug, for example `{{trigger-1.data.name}}`. Run states are `queued`, `starting`, `running`, `done`, `blocked`, `failed`, and `ignored`. +See [authentication](/api/authentication) for access setup and [OpenAPI definition](/api/openapi) for downloading or regenerating the contract. diff --git a/packages/docs/docs.json b/packages/docs/docs.json index 7b0530a1..b5358bfd 100644 --- a/packages/docs/docs.json +++ b/packages/docs/docs.json @@ -2,15 +2,58 @@ "$schema": "https://mintlify.com/docs.json", "name": "Factorize", "theme": "mint", - "colors": { "primary": "#e5a400", "light": "#fff8e1", "dark": "#17130a" }, + "colors": { + "primary": "#e5a400", + "light": "#fff8e1", + "dark": "#17130a" + }, "favicon": "/favicon.ico", - "logo": { "light": "/logo-light.svg", "dark": "/logo-dark.svg" }, + "logo": { + "light": "/logo-light.svg", + "dark": "/logo-dark.svg" + }, "navigation": { - "groups": [ - { "group": "Start", "pages": ["index", "quickstart", "concepts"] }, - { "group": "REST API", "pages": ["api/authentication", "api/discovery", "api/openapi", "api/reference"] }, - { "group": "MCP", "pages": ["mcp/overview", "mcp/tools"] }, - { "group": "Integrations", "pages": ["integrations/triggers", "integrations/oauth"] } + "tabs": [ + { + "tab": "Guides", + "groups": [ + { + "group": "Start", + "pages": [ + "index", + "quickstart", + "concepts" + ] + }, + { + "group": "REST API", + "pages": [ + "api/authentication", + "api/discovery", + "api/openapi", + "api/reference" + ] + }, + { + "group": "MCP", + "pages": [ + "mcp/overview", + "mcp/tools" + ] + }, + { + "group": "Integrations", + "pages": [ + "integrations/triggers", + "integrations/oauth" + ] + } + ] + }, + { + "tab": "API Reference", + "openapi": "/openapi.yaml" + } ] } } diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index bad64d3c..dc443662 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -8,7 +8,7 @@ Use OAuth 2.1 authorization code with PKCE S256 or RFC 8628 device authorization ## REST -The API is rooted at `/api/v1`. Read operations list connections, installations, targets, trigger availability, Tail integrations, jobs, job events, and runs. Write operations create/replace/delete/enable/disable jobs, test handlers, invoke jobs, stop runs, and preview schedules. Run lists return `{items,nextCursor}` and accept `jobId`, `state`, `contextQuery`, `limit` (1–100), and `cursor`. +The API is rooted at `/api/v1`. The verified operation inventory, request validation, scopes, and response schemas are in [openapi.yaml](/openapi.yaml). Mintlify renders the API Reference directly from this generated contract. CI rejects stale artifacts or any method/path mismatch with the executable Worker route catalog. ## MCP @@ -21,4 +21,4 @@ Webhooks support Linear, ClickUp, GitHub, and Cloudflare Tail. Schedule config i ## Trace provenance and recovery -Codex and Claude use execution-stream primary sources when admitted by rollout gates; Pi uses its version-pinned native session. Run diagnostics expose source/CLI/harness versions, retained artifact receipts, projection checksum/parser version, live generation/offset, reconciliation, warning and unknown counts, and native fallback use. Owner sessions with runs:write may POST /api/v1/runs/{runId}/trace/replay with {requestId: UUID, source: primary|native_session}. One terminal run per request, 10 attempts per tenant/minute. Checkpoint request IDs for retries; completed outcomes are durable and idempotent, failed transactions resume, and missing/expired artifacts are explicitly unrecoverable. Native replay can recover retained historical Codex custom tool calls. Neither replay nor rollback deletes artifacts. +Codex and Claude use execution-stream primary sources when admitted by rollout gates; Pi uses its version-pinned native session. Run diagnostics expose source/CLI/harness versions, retained artifact receipts, projection checksum/parser version, live generation/offset, reconciliation, warning and unknown counts, and native fallback use. See the trace replay operation in [openapi.yaml](/openapi.yaml) for owner-session requirements, request validation, replay restrictions, rate limits, and documented outcomes. Neither replay nor rollback deletes artifacts. diff --git a/packages/docs/llms.txt b/packages/docs/llms.txt index f78f7c8f..0e1fdbc8 100644 --- a/packages/docs/llms.txt +++ b/packages/docs/llms.txt @@ -5,6 +5,7 @@ - [Quickstart](/quickstart): Configure Factorize and create a first job. - [Concepts](/concepts): Jobs, triggers, runs, and the Mustache prompt contract. - [REST authentication](/api/authentication): OAuth, scopes, and device authorization. -- [REST reference](/api/reference): Complete operation inventory and schemas. +- [REST reference](/api/reference): Using the generated API reference. +- [OpenAPI contract](/openapi.yaml): Verified operation inventory, validation, scopes, and response schemas. - [MCP](/mcp/overview): Connect a remote MCP client. - [MCP tools](/mcp/tools): Complete tool catalog. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 35167784..6e832135 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1,3 +1,4 @@ +# Generated by npm run generate:openapi. Edit packages/app/src/api-contract.ts. openapi: 3.1.0 info: title: Factorize API @@ -6,266 +7,3382 @@ info: x-dashboard-auth: Access-token and authorized-client management and trace replay operations require an interactive owner session; all other operations accept a suitably scoped bearer token or owner session. servers: - url: https://app.factorize.sh -security: [{ bearerAuth: [] }] +security: + - bearerAuth: [] components: securitySchemes: - bearerAuth: { type: http, scheme: bearer, bearerFormat: OAuth2 } + bearerAuth: + type: http + scheme: bearer + bearerFormat: OAuth2 schemas: - Error: { type: object, required: [error], properties: { error: { type: object, required: [code, message], properties: { code: { type: string }, message: { type: string } } } } } - JobInput: + Error: type: object - required: [name, slug, promptTemplate, executionTargetId] - additionalProperties: false + required: + - error properties: - name: { type: string, minLength: 1, maxLength: 120 } - slug: { type: string, pattern: '^[a-z][a-z0-9_-]{0,29}$' } - promptTemplate: { type: string, minLength: 1, maxLength: 50000 } - concurrencyLimit: { type: integer, minimum: 1, maximum: 50, default: 1 } - executionTargetId: { type: string, minLength: 1 } - model: { type: string, maxLength: 120 } - effort: { type: string, maxLength: 40 } - triggers: { type: array, maxItems: 50, items: { type: object }, description: "Job lifecycle config uses sourceJobIds and states (succeeded, failed, stopped, edited). Edited fires on successful job saves, including enable/disable; context contains source_job_id, event, and edited_at." } + error: + type: object + required: + - code + - message + properties: + code: + type: string + message: + type: string Run: type: object properties: - created_at: { type: string, format: date-time, description: Time the run was created and queued. } - started_at: { type: [string, 'null'], format: date-time, description: Time execution launch succeeded. Null until started or when unknown. Runtime starts here; the difference from created_at is queue time including launch preparation. } - updated_at: { type: string, format: date-time, description: Last run update; used as the elapsed runtime endpoint for terminal runs. } - RunPage: { type: object, required: [items], properties: { items: { type: array, items: { $ref: '#/components/schemas/Run' } }, nextCursor: { type: string, nullable: true } } } + created_at: + type: string + format: date-time + description: Time the run was created and queued. + started_at: + type: + - string + - "null" + format: date-time + description: Time execution launch succeeded. Null until started or when unknown. Runtime starts here; the difference from created_at is queue time including launch preparation. + updated_at: + type: string + format: date-time + description: Last run update; used as the elapsed runtime endpoint for terminal runs. + RunPage: + type: object + required: + - items + properties: + items: + type: array + items: + $ref: "#/components/schemas/Run" + nextCursor: + type: + - string + - "null" ExecutionDiagnostics: - type: [object, 'null'] + type: + - object + - "null" description: First terminal backend observation, retained independently of collection and cleanup errors. Null for older or nonterminal runs. Commands and raw backend responses are never included. - required: [state, detail, systemd] + required: + - state + - detail + - systemd properties: - state: { type: string, enum: [succeeded, failed, stopped] } - detail: { type: [string, 'null'], maxLength: 2048, description: Bounded credential-redacted backend observation detail } + state: + type: string + enum: + - succeeded + - failed + - stopped + detail: + type: + - string + - "null" + maxLength: 2048 + description: Bounded credential-redacted backend observation detail systemd: - type: [object, 'null'] - required: [loadState, activeState, subState, result, execMainCode, execMainStatus] + type: + - object + - "null" + required: + - loadState + - activeState + - subState + - result + - execMainCode + - execMainStatus properties: - loadState: { type: string, maxLength: 64 } - activeState: { type: string, maxLength: 64 } - subState: { type: string, maxLength: 64 } - result: { type: string, maxLength: 64 } - execMainCode: { type: [integer, 'null'], description: systemd ExecMainCode (for example 1 for exit and 2 for signal) } - execMainStatus: { type: [integer, 'null'], description: systemd exit status or signal number; null if unavailable } + loadState: + type: string + maxLength: 64 + activeState: + type: string + maxLength: 64 + subState: + type: string + maxLength: 64 + result: + type: string + maxLength: 64 + execMainCode: + type: + - integer + - "null" + description: systemd ExecMainCode (for example 1 for exit and 2 for signal) + execMainStatus: + type: + - integer + - "null" + description: systemd exit status or signal number; null if unavailable HarnessLog: - type: [object, 'null'] + type: + - object + - "null" description: Stored redacted harness stderr artifact, or null if unavailable. Uses the combined log for older VMs. Retains at most the first 64 KiB, drops a truncated final line, and redacts recognizable credentials before storage. The object key is a storage locator, not a public or signed URL. This artifact remains available after VM deletion. - required: [id, kind, object_key, provider, format, byte_size, sha256, state, created_at] + required: + - id + - kind + - object_key + - provider + - format + - byte_size + - sha256 + - state + - created_at properties: - id: { type: string } - kind: { type: string, const: terminal_log } - object_key: { type: string } - provider: { type: string } - format: { type: string, const: text } - format_version: { type: [string, 'null'] } - cli_version: { type: [string, 'null'] } - source_generation: { type: [string, 'null'], description: Live source generation bound to the terminal snapshot; unknown for historical receipts. } - native_session_id: { type: [string, 'null'] } - byte_size: { type: [integer, string], description: Byte count (PostgreSQL bigint may serialize as a decimal string), maximum: 65536 } - sha256: { type: string, pattern: '^[a-f0-9]{64}$' } - state: { type: string, enum: [stored] } - created_at: { type: string, format: date-time } + id: + type: string + kind: + type: string + const: terminal_log + object_key: + type: string + provider: + type: string + format: + type: string + const: text + format_version: + type: + - string + - "null" + cli_version: + type: + - string + - "null" + source_generation: + type: + - string + - "null" + description: Live source generation bound to the terminal snapshot; unknown for historical receipts. + native_session_id: + type: + - string + - "null" + byte_size: + type: + - integer + - string + description: Byte count (PostgreSQL bigint may serialize as a decimal string) + maximum: 65536 + sha256: + type: string + pattern: ^[a-f0-9]{64}$ + state: + type: string + enum: + - stored + created_at: + type: string + format: date-time TraceSource: type: object - required: [kind, path, mediaType, provider] + required: + - kind + - path + - mediaType + - provider properties: - kind: { type: string, enum: [execution_stream, native_session] } - path: { type: string, description: Guest source path; historical native sources may use a discovery root } - mediaType: { type: string, const: application/x-ndjson } - provider: { type: string, enum: [codex, claude, pi] } - formatVersion: { type: string } - cliVersion: { type: string } - harnessVersion: { type: string } - discoverCommand: { type: string, description: Native session discovery only } + kind: + type: string + enum: + - execution_stream + - native_session + path: + type: string + description: Guest source path; historical native sources may use a discovery root + mediaType: + type: string + const: application/x-ndjson + provider: + type: string + enum: + - codex + - claude + - pi + formatVersion: + type: string + cliVersion: + type: string + harnessVersion: + type: string + discoverCommand: + type: string + description: Native session discovery only TraceSources: - type: [object, 'null'] + type: + - object + - "null" properties: - primary: { $ref: '#/components/schemas/TraceSource' } - nativeSession: { $ref: '#/components/schemas/TraceSource' } + primary: + $ref: "#/components/schemas/TraceSource" + nativeSession: + $ref: "#/components/schemas/TraceSource" TraceProjection: - type: [object, 'null'] + type: + - object + - "null" description: Committed projection receipt. Null means no durable reconciliation evidence; it does not mean complete. properties: - source_kind: { type: string, enum: [execution_stream, native_session] } - artifact_sha256: { type: string } - parser_version: { type: string } - updated_at: { type: string, format: date-time } + source_kind: + type: string + enum: + - execution_stream + - native_session + artifact_sha256: + type: string + parser_version: + type: string + updated_at: + type: string + format: date-time reconciliation: type: object properties: - state: { type: string, enum: [matched, mismatch, no_live_cursor, reprojected] } - events: { type: integer } - liveEvents: { type: integer } - mismatches: { type: integer } - liveOffset: { type: [integer, 'null'] } - artifactBytes: { type: integer } - generation: { type: [string, 'null'] } - codexCompletion: { type: string, enum: [turn.completed, missing_turn_completed], description: Completion evidence from the exact retained canonical Codex bytes. } + state: + type: string + enum: + - matched + - mismatch + - no_live_cursor + - reprojected + events: + type: integer + liveEvents: + type: integer + mismatches: + type: integer + liveOffset: + type: + - integer + - "null" + artifactBytes: + type: integer + generation: + type: + - string + - "null" + codexCompletion: + type: string + enum: + - turn.completed + - missing_turn_completed + description: Completion evidence from the exact retained canonical Codex bytes. TraceDiagnostics: type: object - required: [provider, primarySource, sourceVersion, projection, liveCursor, counts, artifacts, nativeArtifactState, fallbackUsed, lastReplay] + required: + - provider + - primarySource + - sourceVersion + - projection + - liveCursor + - counts + - artifacts + - nativeArtifactState + - fallbackUsed + - lastReplay properties: - provider: { type: [string, 'null'], description: Agent trace provider; the outer diagnostics provider remains the trigger provider. } - primarySource: { type: string, enum: [execution_stream, native_session] } - sourceVersion: { type: [string, 'null'] } - projection: { $ref: '#/components/schemas/TraceProjection' } + provider: + type: + - string + - "null" + description: Agent trace provider; the outer diagnostics provider remains the trigger provider. + primarySource: + type: string + enum: + - execution_stream + - native_session + sourceVersion: + type: + - string + - "null" + projection: + $ref: "#/components/schemas/TraceProjection" liveCursor: - type: [object, 'null'] + type: + - object + - "null" properties: - generation: { type: string } - committed_offset: { type: [integer, string] } - pending_bytes: { type: integer } - updated_at: { type: string, format: date-time } + generation: + type: string + committed_offset: + type: + - integer + - string + pending_bytes: + type: integer + updated_at: + type: string + format: date-time counts: type: object properties: - events: { type: integer } - parse_warnings: { type: integer } - unknown_events: { type: integer } - unknownEventRate: { type: number, minimum: 0, maximum: 1 } + events: + type: integer + parse_warnings: + type: integer + unknown_events: + type: integer + unknownEventRate: + type: number + minimum: 0 + maximum: 1 artifacts: type: array description: Tenant/run-scoped receipts; storage keys are locators, never public download URLs. Includes kind, provider, source_path, source_generation, format and source/CLI/harness versions, byte size, checksum and storage state. - items: { type: object } - nativeArtifactState: { type: string, enum: [stored, missing, not_applicable], description: Canonical Codex runs do not capture native sessions. Historical native receipts remain readable. } - fallbackUsed: { type: boolean, description: Native projection selected for a run originally declared with an execution stream primary. } - lastReplay: { type: [object, 'null'], description: Latest completed replay request ID, source, result, and timestamp; failed requests are retryable and logged. } - TraceReplayRequest: - type: object - additionalProperties: false - required: [requestId] - properties: - requestId: { type: string, format: uuid, description: Tenant-scoped idempotency key; preserve it when retrying. Use a new key to reconsider a previously skipped or unrecoverable run. } - source: { type: string, enum: [primary, native_session], default: primary, description: Primary replays the persisted source declaration (native for historical runs); native_session explicitly selects retained native bytes for other providers or historical native-only Codex runs. Canonical Codex runs reject native replay. } + items: + type: object + nativeArtifactState: + type: string + enum: + - stored + - missing + - not_applicable + description: Canonical Codex runs do not capture native sessions. Historical native receipts remain readable. + fallbackUsed: + type: boolean + description: Native projection selected for a run originally declared with an execution stream primary. + lastReplay: + type: + - object + - "null" + description: Latest completed replay request ID + source: null + result: null + and timestamp; failed requests are retryable and logged.: null TraceReplayResult: type: object - required: [requestId, runId, status] + required: + - requestId + - runId + - status properties: - requestId: { type: string, format: uuid } - runId: { type: string, format: uuid } - status: { type: string, enum: [projected, already_projected, skipped, unrecoverable] } - reason: { type: string, enum: [run_active, ambiguous_artifacts, missing_artifact, unsupported_artifact, artifact_not_retained] } - sourceKind: { type: string, enum: [execution_stream, native_session] } - sha256: { type: string } - parserVersion: { type: string } - reconciliation: { type: object } + requestId: + type: string + format: uuid + runId: + type: string + format: uuid + status: + type: string + enum: + - projected + - already_projected + - skipped + - unrecoverable + reason: + type: string + enum: + - run_active + - ambiguous_artifacts + - missing_artifact + - unsupported_artifact + - artifact_not_retained + sourceKind: + type: string + enum: + - execution_stream + - native_session + sha256: + type: string + parserVersion: + type: string + reconciliation: + type: object RunDetail: allOf: - - $ref: '#/components/schemas/Run' + - $ref: "#/components/schemas/Run" type: object - required: [id, state, execution_diagnostics, harness_log] + required: + - id + - state + - execution_diagnostics + - harness_log properties: - id: { type: string } - state: { type: string } - trace_generation: { type: [string, 'null'], description: Live file generation; clients reset trace pagination when it changes. } - trace_projection: { $ref: '#/components/schemas/TraceProjection' } - trace_sources: { $ref: '#/components/schemas/TraceSources' } - execution_diagnostics: { $ref: '#/components/schemas/ExecutionDiagnostics' } - harness_log: { $ref: '#/components/schemas/HarnessLog' } - artifact_error: { type: [string, 'null'], description: Secondary artifact or cleanup error; does not replace execution_diagnostics } + id: + type: string + state: + type: string + trace_generation: + type: + - string + - "null" + description: Live file generation; clients reset trace pagination when it changes. + trace_projection: + $ref: "#/components/schemas/TraceProjection" + trace_sources: + $ref: "#/components/schemas/TraceSources" + execution_diagnostics: + $ref: "#/components/schemas/ExecutionDiagnostics" + harness_log: + $ref: "#/components/schemas/HarnessLog" + artifact_error: + type: + - string + - "null" + description: Secondary artifact or cleanup error; does not replace execution_diagnostics RunDiagnostics: type: object - required: [runId, jobId, state, execution, harnessLog, artifact, activity] + required: + - runId + - jobId + - state + - execution + - harnessLog + - artifact + - activity properties: - runId: { type: string } - jobId: { type: string } - state: { type: string } - provider: { type: string } - backendKind: { type: string } - trace: { $ref: '#/components/schemas/TraceDiagnostics' } - traceSources: { $ref: '#/components/schemas/TraceSources' } - execution: { $ref: '#/components/schemas/ExecutionDiagnostics' } - harnessLog: { $ref: '#/components/schemas/HarnessLog' } + runId: + type: string + jobId: + type: string + state: + type: string + provider: + type: string + backendKind: + type: string + trace: + $ref: "#/components/schemas/TraceDiagnostics" + traceSources: + $ref: "#/components/schemas/TraceSources" + execution: + $ref: "#/components/schemas/ExecutionDiagnostics" + harnessLog: + $ref: "#/components/schemas/HarnessLog" artifact: type: object properties: - state: { type: string } - error: { type: [string, 'null'], description: Secondary collection or cleanup error. Collection is retried up to three times before cleanup proceeds with partial artifacts. Cleanup failures remain retryable. } - activity: { type: array, items: { type: object } } - createdAt: { type: string, format: date-time } - updatedAt: { type: string, format: date-time } + state: + type: string + error: + type: + - string + - "null" + description: Secondary collection or cleanup error. Collection is retried up to three times before cleanup proceeds with partial artifacts. Cleanup failures remain retryable. + activity: + type: array + items: + type: object + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + JobInput: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 120 + slug: + type: string + pattern: ^[a-z][a-z0-9_-]{0,29}$ + promptTemplate: + type: string + minLength: 1 + maxLength: 50000 + runNameTemplate: + type: string + maxLength: 500 + concurrencyLimit: + default: 1 + type: integer + minimum: 1 + maximum: 50 + executionTargetId: + type: string + minLength: 1 + model: + type: string + maxLength: 120 + effort: + type: string + maxLength: 40 + triggers: + default: [] + maxItems: 50 + type: array + items: + oneOf: + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: manual + enabled: + default: true + type: boolean + config: + default: {} + type: object + properties: {} + additionalProperties: false + required: + - kind + additionalProperties: false + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: schedule + enabled: + default: true + type: boolean + config: + type: object + properties: + cron: + type: string + minLength: 1 + timezone: + type: string + minLength: 1 + required: + - cron + - timezone + additionalProperties: false + required: + - kind + - config + additionalProperties: false + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: webhook + enabled: + default: true + type: boolean + config: + oneOf: + - type: object + properties: + handlerCode: + type: string + maxLength: 16384 + provider: + type: string + const: linear + projectId: + type: string + minLength: 1 + matchRules: + minItems: 1 + type: array + items: + type: object + properties: + type: + type: string + enum: + - owner + - creator + - status + - label + - assignee + targetId: + type: string + minLength: 1 + required: + - type + - targetId + required: + - provider + - projectId + - matchRules + additionalProperties: false + - type: object + properties: + handlerCode: + type: string + maxLength: 16384 + provider: + type: string + const: clickup + listId: + type: string + minLength: 1 + matchRules: + minItems: 1 + type: array + items: + type: object + properties: + type: + type: string + enum: + - owner + - creator + - status + - label + - assignee + targetId: + type: string + minLength: 1 + required: + - type + - targetId + required: + - provider + - listId + - matchRules + additionalProperties: false + - type: object + properties: + handlerCode: + type: string + maxLength: 16384 + provider: + type: string + const: github + installationId: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + repositoryId: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + event: + type: string + minLength: 1 + action: + type: string + minLength: 1 + matchRules: + minItems: 1 + type: array + items: + type: object + properties: + type: + type: string + enum: + - owner + - creator + - status + - label + - assignee + targetId: + type: string + minLength: 1 + required: + - type + - targetId + required: + - provider + - installationId + - repositoryId + additionalProperties: false + - type: object + properties: + handlerCode: + type: string + maxLength: 16384 + provider: + type: string + const: cloudflareTail + integrationId: + type: string + minLength: 1 + required: + - provider + - integrationId + additionalProperties: false + required: + - kind + - config + additionalProperties: false + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: jobLifecycle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + states: + minItems: 1 + type: array + items: + type: string + enum: + - succeeded + - failed + - stopped + - edited + required: + - sourceJobIds + - states + additionalProperties: false + required: + - kind + - config + additionalProperties: false + required: + - name + - slug + - promptTemplate + - executionTargetId + additionalProperties: false ManualInvocation: type: object + properties: + prompt: + default: "" + type: string + maxLength: 50000 + data: + type: object + propertyNames: + type: string + additionalProperties: {} + name: + type: string + minLength: 1 + maxLength: 120 + idempotencyKey: + type: string + minLength: 1 + maxLength: 200 + pattern: ^(?!manual:) + additionalProperties: false + JobHandlerTest: + type: object + properties: + handlerCode: + type: string + maxLength: 16384 + payload: + type: object + propertyNames: + type: string + additionalProperties: {} + required: + - handlerCode + - payload additionalProperties: false + TraceReplayRequest: + type: object properties: - name: { type: string, minLength: 1, maxLength: 120, description: Display name for the run } - prompt: { type: string, maxLength: 50000, default: '' } - data: { type: object, additionalProperties: true, default: {} } - idempotencyKey: { type: string, minLength: 1, maxLength: 200 } + requestId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + description: Tenant-scoped idempotency key; preserve it when retrying. Use a new key to reconsider a previously skipped or unrecoverable run. + source: + default: primary + description: Primary replays the persisted source declaration (native for historical runs); native_session selects retained native bytes for other providers or historical native-only Codex runs. Canonical Codex runs reject native replay. + type: string + enum: + - primary + - native_session + required: + - requestId + additionalProperties: false + responses: + Error400: + description: Invalid request + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error401: + description: Invalid or revoked credentials + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error403: + description: Missing scope or required owner session + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error404: + description: Resource not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error409: + description: Operation conflict + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error415: + description: Unsupported media type; use application/json + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error429: + description: Rate limit exceeded + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error500: + description: Internal error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + Error503: + description: Service unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/Error" paths: - /healthz: { get: { summary: Worker health check, security: [], responses: { '200': { description: OK, content: { application/json: { example: { ok: true } } } } } } } - /api/v1/exe-connections: { get: { summary: List exe connections, responses: { '200': { description: Safe metadata } } } } - /api/v1/github-installations: { get: { summary: List GitHub installations, responses: { '200': { description: Installations } } } } - /api/v1/execution-targets: { get: { summary: List execution targets, responses: { '200': { description: Targets } } } } - /api/v1/job-trigger-availability: { get: { summary: List available trigger kinds, responses: { '200': { description: Availability } } } } - /api/v1/integrations/cloudflare-tail: { get: { summary: List Tail integrations, responses: { '200': { description: Integrations } } }, post: { summary: Create a Tail integration, responses: { '201': { description: Created } } } } - /api/v1/integrations: { get: { summary: List installed integrations, responses: { '200': { description: Credential-safe integration status } } } } - /api/v1/integrations/exe: { put: { summary: Create an exe.dev integration, responses: { '200': { description: Saved } } } } - /api/v1/integrations/exe/test: { post: { summary: Test exe.dev credentials, responses: { '200': { description: Test result } } } } - /api/v1/integrations/exe/{connectionId}: { delete: { summary: Remove an exe.dev integration, responses: { '200': { description: Removed } } } } - /api/v1/integrations/amp: { put: { summary: Create an Amp integration, responses: { '200': { description: Saved } } } } - /api/v1/integrations/amp/test: { post: { summary: Test Amp credentials, responses: { '200': { description: Test result } } } } - /api/v1/integrations/amp/{connectionId}: { delete: { summary: Remove an Amp integration, responses: { '200': { description: Removed } } } } - /api/v1/integrations/cloudflare-tail/{integrationId}: { put: { summary: Update a Tail integration, responses: { '200': { description: Updated } } }, delete: { summary: Remove a Tail integration, responses: { '200': { description: Removed } } } } - /api/v1/integrations/cloudflare-tail/{integrationId}/test: { post: { summary: Test a Tail integration, responses: { '200': { description: Test result } } } } - /api/v1/providers/linear/projects: { get: { summary: List Linear projects, responses: { '200': { description: Projects } } } } - /api/v1/providers/linear/options: { get: { summary: List Linear trigger options, responses: { '200': { description: Options } } } } - /api/v1/providers/clickup/lists: { get: { summary: List ClickUp lists, responses: { '200': { description: Lists } } } } - /api/v1/providers/clickup/options: { get: { summary: List ClickUp trigger options, responses: { '200': { description: Options } } } } - /api/v1/providers/github/installations: { get: { summary: List GitHub installations for provider setup, responses: { '200': { description: Installations } } } } - /api/v1/providers/github/installations/{installationId}: { delete: { summary: Disconnect a GitHub installation, responses: { '200': { description: Disconnected } } } } - /api/v1/providers/github/installations/{installationId}/repositories: { get: { summary: List installation repositories, responses: { '200': { description: Repositories } } } } - /api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options: { get: { summary: List GitHub issue trigger options, responses: { '200': { description: Options } } } } - /api/v1/access/authorized-clients: { get: { summary: List authorized OAuth clients, responses: { '200': { description: Clients } } } } - /api/v1/access/authorized-clients/{clientId}: { delete: { summary: Revoke an authorized OAuth client, responses: { '200': { description: Revoked grants } } } } - /api/v1/access-tokens: { get: { summary: List access tokens, responses: { '200': { description: Token metadata } } }, post: { summary: Create an access token, responses: { '201': { description: Created token } } } } - /api/v1/access-tokens/{tokenId}: { delete: { summary: Revoke an access token, responses: { '200': { description: Revoked } } } } + /api/v1/exe-connections: + get: + summary: List exe connections + responses: + "200": + description: Safe metadata + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_exe_connections + tags: + - exe-connections + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/github-installations: + get: + summary: List GitHub installations + responses: + "200": + description: Installations + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_github_installations + tags: + - github-installations + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/execution-targets: + get: + summary: List execution targets + responses: + "200": + description: Targets + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_execution_targets + tags: + - execution-targets + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/job-trigger-availability: + get: + summary: List available trigger kinds + responses: + "200": + description: Availability + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_job_trigger_availability + tags: + - job-trigger-availability + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/schedules/preview: + post: + summary: Preview schedule + responses: + "200": + description: Next occurrence + content: + application/json: + schema: + type: object + required: + - nextRunAt + properties: + nextRunAt: + type: string + format: date-time + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_schedules_preview + tags: + - schedules + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + cron: + type: string + minLength: 1 + timezone: + type: string + minLength: 1 + required: + - cron + - timezone + additionalProperties: false + /api/v1/integrations/cloudflare-tail: + get: + summary: List Tail integrations + responses: + "200": + description: Integrations + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_integrations_cloudflare_tail + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + post: + summary: Create a Tail integration + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_integrations_cloudflare_tail + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + integrationId: + type: string + minLength: 1 + name: + type: string + minLength: 1 + maxLength: 120 + signingSecret: + writeOnly: true + anyOf: + - type: string + const: "" + - type: string + minLength: 16 + generateSecret: + type: boolean + required: + - name + /api/v1/integrations: + get: + summary: List installed integrations + responses: + "200": + description: Credential-safe integration status + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_integrations + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/integrations/exe: + put: + summary: Create an exe.dev integration + responses: + "200": + description: Saved + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: put_api_v1_integrations_exe + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + connectionId: + type: string + minLength: 1 + apiToken: + type: string + minLength: 1 + writeOnly: true + agentKind: + type: string + enum: + - codex + - claude + - pi + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + required: + - apiToken + - agentKind + /api/v1/integrations/exe/test: + post: + summary: Test exe.dev credentials + responses: + "200": + description: Test result + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_integrations_exe_test + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + connectionId: + type: string + minLength: 1 + apiToken: + type: string + minLength: 1 + writeOnly: true + agentKind: + type: string + enum: + - codex + - claude + - pi + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + /api/v1/integrations/amp: + put: + summary: Create an Amp integration + responses: + "200": + description: Saved + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: put_api_v1_integrations_amp + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + connectionId: + type: string + minLength: 1 + accessToken: + type: string + minLength: 1 + writeOnly: true + project: + type: string + minLength: 1 + apiBaseUrl: + type: string + format: uri + required: + - accessToken + - project + /api/v1/integrations/amp/test: + post: + summary: Test Amp credentials + responses: + "200": + description: Test result + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_integrations_amp_test + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + connectionId: + type: string + minLength: 1 + accessToken: + type: string + minLength: 1 + writeOnly: true + project: + type: string + minLength: 1 + apiBaseUrl: + type: string + format: uri + /api/v1/providers/linear/projects: + get: + summary: List Linear projects + responses: + "200": + description: Projects + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_linear_projects + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/providers/linear/options: + get: + summary: List Linear trigger options + responses: + "200": + description: Options + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_linear_options + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/providers/clickup/lists: + get: + summary: List ClickUp lists + responses: + "200": + description: Lists + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_clickup_lists + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/providers/clickup/options: + get: + summary: List ClickUp trigger options + responses: + "200": + description: Options + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_clickup_options + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + parameters: + - name: listId + in: query + required: false + schema: + default: "" + type: string + /api/v1/providers/github/installations: + get: + summary: List GitHub installations for provider setup + responses: + "200": + description: Installations + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_github_installations + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + /api/v1/access/authorized-clients: + get: + summary: List authorized OAuth clients + responses: + "200": + description: Clients + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: get_api_v1_access_authorized_clients + tags: + - access + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: true + /api/v1/access-tokens: + get: + summary: List access tokens + responses: + "200": + description: Token metadata + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: get_api_v1_access_tokens + tags: + - access-tokens + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: true + post: + summary: Create an access token + responses: + "201": + description: Created token + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: post_api_v1_access_tokens + tags: + - access-tokens + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 100 + scopes: + minItems: 1 + type: array + items: + type: string + enum: + - flows:read + - flows:write + - runs:read + - runs:write + expiryDays: + anyOf: + - type: number + const: 7 + - type: number + const: 30 + - type: number + const: 90 + required: + - name + - scopes + - expiryDays + /api/v1/access-tokens/{tokenId}: + delete: + summary: Revoke an access token + responses: + "200": + description: Revoked + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: delete_api_v1_access_tokens_tokenId + tags: + - access-tokens + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: true + parameters: + - name: tokenId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/access/authorized-clients/{clientId}: + delete: + summary: Revoke an authorized OAuth client + responses: + "200": + description: Revoked grants + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: delete_api_v1_access_authorized_clients_clientId + tags: + - access + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: true + parameters: + - name: clientId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/integrations/exe/{connectionId}: + delete: + summary: Remove an exe.dev integration + responses: + "200": + description: Removed + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: delete_api_v1_integrations_exe_connectionId + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/integrations/amp/{connectionId}: + delete: + summary: Remove an Amp integration + responses: + "200": + description: Removed + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: delete_api_v1_integrations_amp_connectionId + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/integrations/cloudflare-tail/{integrationId}: + put: + summary: Update a Tail integration + responses: + "200": + description: Updated + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: put_api_v1_integrations_cloudflare_tail_integrationId + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: integrationId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + integrationId: + type: string + minLength: 1 + name: + type: string + minLength: 1 + maxLength: 120 + signingSecret: + writeOnly: true + anyOf: + - type: string + const: "" + - type: string + minLength: 16 + generateSecret: + type: boolean + required: + - name + delete: + summary: Remove a Tail integration + responses: + "200": + description: Removed + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: delete_api_v1_integrations_cloudflare_tail_integrationId + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: integrationId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/integrations/cloudflare-tail/{integrationId}/test: + post: + summary: Test a Tail integration + responses: + "200": + description: Test result + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_integrations_cloudflare_tail_integrationId_test + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: integrationId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/providers/github/installations/{installationId}/repositories: + get: + summary: List installation repositories + responses: + "200": + description: Repositories + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_github_installations_installationId_repositories + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + parameters: + - name: installationId + in: path + required: true + schema: + type: string + pattern: ^[0-9]+$ + /api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options: + get: + summary: List GitHub issue trigger options + responses: + "200": + description: Options + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_providers_github_installations_installationId_repositories_repositoryId_issue_options + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + parameters: + - name: installationId + in: path + required: true + schema: + type: string + pattern: ^[0-9]+$ + - name: repositoryId + in: path + required: true + schema: + type: string + pattern: ^[0-9]+$ + /api/v1/providers/github/installations/{installationId}: + delete: + summary: Disconnect a GitHub installation + responses: + "200": + description: Disconnected + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: delete_api_v1_providers_github_installations_installationId + tags: + - providers + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: installationId + in: path + required: true + schema: + type: string + pattern: ^[0-9]+$ /api/v1/integrations/exe/{connectionId}/diagnostics: - parameters: [{ name: connectionId, in: path, required: true, schema: { type: string } }] - post: { summary: Probe exe.dev permissions and a disposable VM's agent/model integration, responses: { '200': { description: Credential-safe diagnostic result } } } + post: + summary: Probe exe.dev permissions and a disposable VM's agent/model integration + responses: + "200": + description: Credential-safe diagnostic result + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_integrations_exe_connectionId_diagnostics + tags: + - integrations + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + minLength: 1 /api/v1/jobs: - get: { summary: List jobs, responses: { '200': { description: Jobs } } } - post: { summary: Create job, requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/JobInput' } } } }, responses: { '201': { description: Created } } } + get: + summary: List jobs + responses: + "200": + description: Jobs + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_jobs + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + post: + summary: Create job + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_jobs + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/JobInput" + /api/v1/job-handlers/test: + post: + summary: Test webhook handler + responses: + "200": + description: Decision + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_job_handlers_test + tags: + - job-handlers + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/JobHandlerTest" + /api/v1/jobs/{jobId}/invocations: + post: + summary: Invoke job + responses: + "202": + description: Accepted + content: + application/json: + schema: + type: object + required: + - invocationId + - runId + - state + - duplicate + properties: + invocationId: + type: string + runId: + type: string + state: + type: string + duplicate: + type: boolean + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + description: queue_full — this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run. + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_jobs_jobId_invocations + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: runs:write + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ManualInvocation" + /api/v1/jobs/{jobId}/events: + get: + summary: List webhook activity + responses: + "200": + description: Activity + content: + application/json: + schema: + type: array + items: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_jobs_jobId_events + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + - name: limit + in: query + required: false + schema: + default: 50 + type: integer + minimum: 1 + maximum: 100 + /api/v1/jobs/{jobId}/enable: + post: + summary: Enable job + responses: + "200": + description: Enabled + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_jobs_jobId_enable + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/jobs/{jobId}/disable: + post: + summary: Disable job + responses: + "200": + description: Disabled + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_jobs_jobId_disable + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 /api/v1/jobs/{jobId}: - parameters: [{ name: jobId, in: path, required: true, schema: { type: string } }] - get: { summary: Get job, responses: { '200': { description: Job } } } - put: { summary: Replace job, requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/JobInput' } } } }, responses: { '200': { description: Updated } } } - delete: { summary: Delete job, responses: { '200': { description: Deleted } } } - /api/v1/jobs/{jobId}/enable: { post: { summary: Enable job, responses: { '200': { description: Enabled } } } } - /api/v1/jobs/{jobId}/disable: { post: { summary: Disable job, responses: { '200': { description: Disabled } } } } - /api/v1/jobs/{jobId}/invocations: { post: { summary: Invoke job, requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/ManualInvocation' } } } }, responses: { '202': { description: Accepted }, '409': { description: 'queue_full — this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run.' } } } } - /api/v1/jobs/{jobId}/events: { get: { summary: List webhook activity, responses: { '200': { description: Activity } } } } - /api/v1/webhooks/deliveries: { get: { summary: Search webhook deliveries, responses: { '200': { description: Cursor-paginated safe delivery records } } } } - /api/v1/webhooks/deliveries/{deliveryId}: { get: { summary: Get webhook delivery detail and processing timeline, responses: { '200': { description: Safe delivery detail } } } } - /api/v1/job-handlers/test: { post: { summary: Test webhook handler, responses: { '200': { description: Decision } } } } + get: + summary: Get job + responses: + "200": + description: Job + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_jobs_jobId + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:read + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + put: + summary: Replace job + responses: + "200": + description: Updated + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: put_api_v1_jobs_jobId + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/JobInput" + delete: + summary: Delete job + responses: + "200": + description: Deleted + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the flows:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: delete_api_v1_jobs_jobId + tags: + - jobs + security: + - bearerAuth: [] + x-required-scope: flows:write + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 /api/v1/runs: - get: { summary: List runs, parameters: [{ name: jobId, in: query, schema: { type: string } }, { name: state, in: query, schema: { type: string } }, { name: contextQuery, in: query, schema: { type: string } }, { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }, { name: cursor, in: query, schema: { type: string } }], responses: { '200': { description: Paginated runs, content: { application/json: { schema: { $ref: '#/components/schemas/RunPage' } } } } } } - /api/v1/runs/{runId}: { get: { summary: Get run, responses: { '200': { description: Run including durable execution diagnostics and harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDetail' } } } } } } } - /api/v1/runs/{runId}/trace: { get: { summary: Get paginated run trace events, responses: { '200': { description: Trace page } } } } + get: + summary: List runs + responses: + "200": + description: Paginated runs + content: + application/json: + schema: + $ref: "#/components/schemas/RunPage" + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_runs + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: jobId + in: query + required: false + schema: + type: string + minLength: 1 + - name: state + in: query + required: false + schema: + type: string + enum: + - queued + - starting + - running + - done + - blocked + - failed + - ignored + - name: contextQuery + in: query + required: false + schema: + type: string + minLength: 1 + maxLength: 50000 + - name: limit + in: query + required: false + schema: + default: 50 + type: integer + minimum: 1 + maximum: 100 + - name: cursor + in: query + required: false + schema: + type: string + minLength: 1 + /api/v1/search: + get: + summary: Search jobs and runs + responses: + "200": + description: Search results + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_search + tags: + - search + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: q + in: query + required: false + schema: + default: "" + type: string + /api/v1/webhooks/deliveries: + get: + summary: Search webhook deliveries + responses: + "200": + description: Cursor-paginated safe delivery records + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_webhooks_deliveries + tags: + - webhooks + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: provider + in: query + required: false + schema: + type: string + - name: deliveryId + in: query + required: false + schema: + type: string + - name: event + in: query + required: false + schema: + type: string + - name: action + in: query + required: false + schema: + type: string + - name: outcome + in: query + required: false + schema: + type: string + - name: jobId + in: query + required: false + schema: + type: string + - name: q + in: query + required: false + schema: + type: string + - name: cursor + in: query + required: false + schema: + type: string + - name: limit + in: query + required: false + schema: + default: 50 + type: integer + minimum: 1 + maximum: 100 + /api/v1/webhooks/deliveries/{deliveryId}: + get: + summary: Get webhook delivery detail and processing timeline + responses: + "200": + description: Safe delivery detail + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_webhooks_deliveries_deliveryId + tags: + - webhooks + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: deliveryId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/runs/{runId}: + get: + summary: Get run + responses: + "200": + description: Run including durable execution diagnostics and harness artifact location + content: + application/json: + schema: + $ref: "#/components/schemas/RunDetail" + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_runs_runId + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/runs/{runId}/trace: + get: + summary: Get paginated run trace events + responses: + "200": + description: Trace page + content: + application/json: + schema: + type: object + required: + - items + - nextCursor + properties: + items: + type: array + items: + type: object + nextCursor: + type: + - integer + - "null" + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_runs_runId_trace + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + minLength: 1 + - name: after + in: query + required: false + schema: + default: 0 + type: integer + minimum: 0 + maximum: 9007199254740991 + - name: limit + in: query + required: false + schema: + default: 100 + type: integer + minimum: 1 + maximum: 200 /api/v1/runs/{runId}/trace/replay: post: summary: Replay a retained trace artifact or restore a native-session projection - description: Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. + description: |- + Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. + + Requires the runs:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Durable replay result + content: + application/json: + schema: + $ref: "#/components/schemas/TraceReplayResult" + "400": + $ref: "#/components/responses/Error400" + description: Invalid request + "401": + $ref: "#/components/responses/Error401" + description: Invalid owner session + "403": + $ref: "#/components/responses/Error403" + description: Missing runs:write scope or interactive owner session + "404": + $ref: "#/components/responses/Error404" + description: Run not found within the tenant + "409": + $ref: "#/components/responses/Error409" + description: Request ID conflict or artifact ownership/checksum mismatch + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + description: Tenant rate limit reached; wait one minute before retrying + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: Artifact storage unavailable + operationId: post_api_v1_runs_runId_trace_replay + tags: + - runs + security: + - bearerAuth: [] x-required-scope: runs:write x-owner-session-required: true parameters: - - { name: runId, in: path, required: true, schema: { type: string, format: uuid } } + - name: runId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ requestBody: required: true - content: { application/json: { schema: { $ref: '#/components/schemas/TraceReplayRequest' } } } - responses: - '200': { description: Durable replay result, content: { application/json: { schema: { $ref: '#/components/schemas/TraceReplayResult' } } } } - '400': { description: Invalid request } - '401': { description: Invalid owner session } - '403': { description: Missing runs:write scope or interactive owner session } - '404': { description: Run not found within the tenant } - '409': { description: Request ID conflict or artifact ownership/checksum mismatch } - '429': { description: Tenant rate limit reached; wait one minute before retrying } - '503': { description: Artifact storage unavailable } - /api/v1/runs/{runId}/diagnostics: { get: { summary: Get credential-safe run lifecycle diagnostics, responses: { '200': { description: Credential-safe execution metadata and durable harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDiagnostics' } } } } } } } - /api/v1/runs/{runId}/stop: { post: { summary: Stop run, responses: { '200': { description: Stopped } } } } - /api/v1/runs/{runId}/kill: { post: { summary: Kill run and immediately release its concurrency slot, responses: { '200': { description: Killed } } } } - /api/v1/schedules/preview: { post: { summary: Preview schedule, responses: { '200': { description: Next occurrence } } } } - /api/v1/search: { get: { summary: Search jobs and runs, responses: { '200': { description: Search results } } } } + content: + application/json: + schema: + $ref: "#/components/schemas/TraceReplayRequest" + /api/v1/runs/{runId}/diagnostics: + get: + summary: Get credential-safe run lifecycle diagnostics + responses: + "200": + description: Credential-safe execution metadata and durable harness artifact location + content: + application/json: + schema: + $ref: "#/components/schemas/RunDiagnostics" + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_runs_runId_diagnostics + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:read + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/runs/{runId}/stop: + post: + summary: Stop run + responses: + "200": + description: Stopped + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_runs_runId_stop + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:write + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + minLength: 1 + /api/v1/runs/{runId}/kill: + post: + summary: Kill run and immediately release its concurrency slot + responses: + "200": + description: Killed + content: + application/json: + schema: + type: object + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the runs:write scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_runs_runId_kill + tags: + - runs + security: + - bearerAuth: [] + x-required-scope: runs:write + x-owner-session-required: false + parameters: + - name: runId + in: path + required: true + schema: + type: string + minLength: 1 diff --git a/packages/docs/scripts/validate.mjs b/packages/docs/scripts/validate.mjs index 53a819b5..4d5765fa 100644 --- a/packages/docs/scripts/validate.mjs +++ b/packages/docs/scripts/validate.mjs @@ -1,11 +1,9 @@ import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; +import { execFileSync } from "node:child_process"; const root = resolve(import.meta.dirname, ".."); -const api = await readFile(resolve(root, "openapi.yaml"), "utf8"); -const worker = await readFile(resolve(root, "../app/src/protected-api.ts"), "utf8"); -const expected = ["exe-connections", "github-installations", "execution-targets", "job-trigger-availability", "integrations/cloudflare-tail", "jobs", "job-handlers/test", "runs", "schedules/preview"]; -const missing = expected.filter(path => !api.includes(path) || !worker.includes(path)); for (const file of ["docs.json", "llms.txt", "llms-full.txt"]) await readFile(resolve(root, file)); -if (missing.length) throw new Error(`Documentation route inventory is stale: ${missing.join(", ")}`); -console.log(`Validated ${expected.length} route families, Mintlify config, and LLM exports.`); +execFileSync("npm", ["run", "check:openapi"], { cwd: resolve(root, "../.."), stdio: "inherit" }); +execFileSync("npm", ["test", "--workspace=factorize", "--", "test/api-contract.test.ts"], { cwd: resolve(root, "../.."), stdio: "inherit" }); +console.log("Validated generated OpenAPI, executable operation equality, Mintlify configuration, and LLM exports.");