From 05ef91305eacdff24dc53dfdce8e6095f9c214f6 Mon Sep 17 00:00:00 2001 From: Brendan Date: Fri, 18 Sep 2026 17:53:14 +0000 Subject: [PATCH 1/4] Complete PostgreSQL runtime and native session artifacts --- packages/app/migrations/0001_app_schema.sql | 11 +- .../migrations/0002_native_run_artifacts.sql | 21 + packages/app/migrations/README.md | 5 +- packages/app/scripts/verify-schema.mjs | 5 +- packages/app/src/access-tokens.ts | 9 +- packages/app/src/agent-driver.ts | 56 + packages/app/src/alarm-coordinator.ts | 20 + packages/app/src/artifact-upload.ts | 64 + packages/app/src/artifacts.ts | 57 + packages/app/src/auth-do.ts | 70 - packages/app/src/exe-vm-backend.ts | 35 +- packages/app/src/exe.ts | 5 +- packages/app/src/execution.ts | 3 + packages/app/src/flow-service.ts | 134 +- packages/app/src/github-registry.ts | 28 - packages/app/src/index.ts | 132 +- packages/app/src/job-domain.ts | 2 +- .../src/postgres/access-token-repository.ts | 40 + .../app/src/postgres/artifact-repository.ts | 16 + packages/app/src/postgres/auth-repository.ts | 56 + .../app/src/postgres/automation-scheduler.ts | 38 + .../app/src/postgres/connection-repository.ts | 25 + packages/app/src/postgres/database.ts | 12 + .../app/src/postgres/github-repository.ts | 20 + .../app/src/postgres/identity-repository.ts | 35 + .../app/src/postgres/integration-service.ts | 72 + packages/app/src/postgres/job-repository.ts | 75 + .../app/src/postgres/operations-repository.ts | 28 + packages/app/src/postgres/provider-catalog.ts | 72 + .../app/src/postgres/run-query-repository.ts | 26 + packages/app/src/postgres/run-repository.ts | 78 + packages/app/src/postgres/run-scheduler.ts | 57 + packages/app/src/postgres/trace-repository.ts | 51 + packages/app/src/postgres/webhook-service.ts | 62 + packages/app/src/protected-api.ts | 2 + packages/app/src/tenant.ts | 2005 ----------------- packages/app/src/trace.ts | 113 + packages/app/src/types.ts | 10 +- packages/app/src/ui.ts | 14 +- packages/app/src/worker.ts | 16 +- packages/app/test/agent-driver.test.ts | 13 + packages/app/test/alarm-isolation.test.ts | 47 - packages/app/test/artifact-upload.test.ts | 30 + packages/app/test/artifacts.test.ts | 9 + packages/app/test/device-oauth.e2e.test.ts | 144 -- .../app/test/exe-run-lifecycle.e2e.test.ts | 162 -- packages/app/test/execution-backend.test.ts | 7 +- packages/app/test/flow-service.test.ts | 96 - packages/app/test/fresh-namespace.e2e.test.ts | 69 - .../test/postgres-identity-repository.test.ts | 11 + .../app/test/postgres-run-repository.test.ts | 12 + .../test/postgres-trace-repository.test.ts | 13 + packages/app/test/run-inspection.test.ts | 155 -- packages/app/test/session.test.ts | 11 + packages/app/test/ticket-prompt.test.ts | 2 +- packages/app/test/trace.test.ts | 38 + packages/app/test/ui.test.ts | 16 +- packages/app/test/worker.test.ts | 156 -- packages/app/wrangler.jsonc | 8 +- 59 files changed, 1466 insertions(+), 3113 deletions(-) create mode 100644 packages/app/migrations/0002_native_run_artifacts.sql create mode 100644 packages/app/src/agent-driver.ts create mode 100644 packages/app/src/alarm-coordinator.ts create mode 100644 packages/app/src/artifact-upload.ts create mode 100644 packages/app/src/artifacts.ts delete mode 100644 packages/app/src/auth-do.ts delete mode 100644 packages/app/src/github-registry.ts create mode 100644 packages/app/src/postgres/access-token-repository.ts create mode 100644 packages/app/src/postgres/artifact-repository.ts create mode 100644 packages/app/src/postgres/auth-repository.ts create mode 100644 packages/app/src/postgres/automation-scheduler.ts create mode 100644 packages/app/src/postgres/connection-repository.ts create mode 100644 packages/app/src/postgres/github-repository.ts create mode 100644 packages/app/src/postgres/identity-repository.ts create mode 100644 packages/app/src/postgres/integration-service.ts create mode 100644 packages/app/src/postgres/job-repository.ts create mode 100644 packages/app/src/postgres/operations-repository.ts create mode 100644 packages/app/src/postgres/provider-catalog.ts create mode 100644 packages/app/src/postgres/run-query-repository.ts create mode 100644 packages/app/src/postgres/run-repository.ts create mode 100644 packages/app/src/postgres/run-scheduler.ts create mode 100644 packages/app/src/postgres/trace-repository.ts create mode 100644 packages/app/src/postgres/webhook-service.ts delete mode 100644 packages/app/src/tenant.ts create mode 100644 packages/app/src/trace.ts create mode 100644 packages/app/test/agent-driver.test.ts delete mode 100644 packages/app/test/alarm-isolation.test.ts create mode 100644 packages/app/test/artifact-upload.test.ts create mode 100644 packages/app/test/artifacts.test.ts delete mode 100644 packages/app/test/device-oauth.e2e.test.ts delete mode 100644 packages/app/test/exe-run-lifecycle.e2e.test.ts delete mode 100644 packages/app/test/flow-service.test.ts delete mode 100644 packages/app/test/fresh-namespace.e2e.test.ts create mode 100644 packages/app/test/postgres-identity-repository.test.ts create mode 100644 packages/app/test/postgres-run-repository.test.ts create mode 100644 packages/app/test/postgres-trace-repository.test.ts delete mode 100644 packages/app/test/run-inspection.test.ts create mode 100644 packages/app/test/session.test.ts create mode 100644 packages/app/test/trace.test.ts delete mode 100644 packages/app/test/worker.test.ts diff --git a/packages/app/migrations/0001_app_schema.sql b/packages/app/migrations/0001_app_schema.sql index f80b819e..255b1c0a 100644 --- a/packages/app/migrations/0001_app_schema.sql +++ b/packages/app/migrations/0001_app_schema.sql @@ -14,7 +14,7 @@ CREATE TABLE app.connections (tenant_id uuid NOT NULL REFERENCES app.tenants(id) CREATE TABLE app.github_installations (installation_id bigint PRIMARY KEY, tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, account_login text NOT NULL, account_type text NOT NULL, state text NOT NULL CHECK (state IN ('active','suspended')), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (tenant_id,installation_id)); CREATE TABLE app.github_setup_states (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, nonce text NOT NULL, expires_at timestamptz NOT NULL, used_at timestamptz, PRIMARY KEY (tenant_id,nonce)); -CREATE TABLE app.jobs (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, name text NOT NULL, slug text NOT NULL, encrypted_prompt_template text NOT NULL, encrypted_run_name_template text NOT NULL DEFAULT '', execution_target jsonb NOT NULL, concurrency_limit integer NOT NULL CHECK (concurrency_limit >= 1), enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,slug)); +CREATE TABLE app.jobs (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, name text NOT NULL, slug text NOT NULL, encrypted_prompt_template text NOT NULL, encrypted_run_name_template text NOT NULL DEFAULT '', execution_target jsonb NOT NULL, model text NOT NULL DEFAULT '', effort text NOT NULL DEFAULT '', concurrency_limit integer NOT NULL CHECK (concurrency_limit >= 1), enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,slug)); CREATE TABLE app.triggers (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, kind text NOT NULL CHECK (kind IN ('manual','schedule','webhook','jobLifecycle')), slug text NOT NULL, enabled boolean NOT NULL DEFAULT true, config jsonb NOT NULL DEFAULT '{}', position integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,job_id,slug), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); CREATE TABLE app.invocations (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, source text NOT NULL CHECK (source IN ('manual','schedule','webhook','jobLifecycle')), claim_key text NOT NULL, trigger_id uuid NOT NULL, context jsonb NOT NULL, occurrence jsonb, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,job_id,claim_key), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id)); CREATE TABLE app.job_runs (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, invocation_id uuid NOT NULL, state text NOT NULL CHECK (state IN ('queued','starting','running','blocked','stopping','succeeded','failed','stopped')), encrypted_prompt text NOT NULL, run_name text NOT NULL DEFAULT '', launch_lease_expires_at timestamptz, next_poll_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), started_at timestamptz, PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,invocation_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,invocation_id) REFERENCES app.invocations(tenant_id,id) ON DELETE CASCADE); @@ -22,14 +22,17 @@ CREATE INDEX job_runs_queue ON app.job_runs (state,created_at) WHERE state='queu CREATE INDEX job_runs_poll_due ON app.job_runs (next_poll_at) WHERE state IN ('running','blocked','stopping'); CREATE INDEX job_runs_launch_lease ON app.job_runs (launch_lease_expires_at) WHERE state='starting'; -CREATE TABLE app.runs (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, invocation_id uuid NOT NULL, provider text NOT NULL, issue_id text NOT NULL, issue_url text, issue_title text NOT NULL DEFAULT '', run_name text NOT NULL DEFAULT '', agent_name text NOT NULL, workspace_name text NOT NULL DEFAULT '', agent_kind text NOT NULL DEFAULT '', state text NOT NULL, execution_backend_kind text NOT NULL DEFAULT '', execution_handle jsonb, execution_capabilities jsonb NOT NULL DEFAULT '[]', destination_url text, result text, output_captured boolean NOT NULL DEFAULT false, claim_released boolean NOT NULL DEFAULT false, vm_cleanup_attempt integer NOT NULL DEFAULT 0, cleanup_next_at timestamptz, vm_cleanup_complete boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,invocation_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,invocation_id) REFERENCES app.invocations(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.runs (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, invocation_id uuid NOT NULL, provider text NOT NULL, issue_id text NOT NULL, issue_url text, issue_title text NOT NULL DEFAULT '', run_name text NOT NULL DEFAULT '', agent_name text NOT NULL, workspace_name text NOT NULL DEFAULT '', agent_kind text NOT NULL DEFAULT '', state text NOT NULL, execution_backend_kind text NOT NULL DEFAULT '', execution_handle jsonb, execution_capabilities jsonb NOT NULL DEFAULT '[]', destination_url text, artifact_state text NOT NULL DEFAULT 'pending' CHECK (artifact_state IN ('pending','collecting','stored','partial','failed')), artifact_error text, claim_released boolean NOT NULL DEFAULT false, vm_cleanup_attempt integer NOT NULL DEFAULT 0, cleanup_next_at timestamptz, vm_cleanup_complete boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,invocation_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,invocation_id) REFERENCES app.invocations(tenant_id,id) ON DELETE CASCADE); CREATE INDEX runs_order ON app.runs (tenant_id,created_at DESC,id DESC); CREATE INDEX runs_state_order ON app.runs (tenant_id,state,created_at DESC,id DESC); CREATE INDEX runs_cleanup_due ON app.runs (cleanup_next_at) WHERE NOT vm_cleanup_complete; CREATE INDEX runs_issue_trgm ON app.runs USING gin (issue_id gin_trgm_ops); CREATE INDEX runs_name_trgm ON app.runs USING gin (run_name gin_trgm_ops); -CREATE TABLE app.run_transcripts (tenant_id uuid NOT NULL, run_id uuid NOT NULL, transcript text NOT NULL, byte_size integer NOT NULL CHECK (byte_size >= 0), search_vector tsvector GENERATED ALWAYS AS (to_tsvector('english',transcript)) STORED, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,run_id), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); -CREATE INDEX run_transcripts_search ON app.run_transcripts USING gin (search_vector); +CREATE TABLE app.run_artifacts (tenant_id uuid NOT NULL, run_id uuid NOT NULL, id uuid NOT NULL, kind text NOT NULL CHECK (kind IN ('native_session','related_session','terminal_log','manifest')), object_key text NOT NULL, provider text NOT NULL, format text NOT NULL, format_version text, cli_version text, native_session_id text, byte_size bigint NOT NULL CHECK (byte_size >= 0), sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), state text NOT NULL CHECK (state IN ('pending','collecting','stored','partial','failed')), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,object_key), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX run_artifacts_by_run ON app.run_artifacts (tenant_id,run_id,created_at,id); +CREATE TABLE app.run_trace_events (tenant_id uuid NOT NULL, run_id uuid NOT NULL, sequence bigint NOT NULL CHECK (sequence > 0), id text NOT NULL, parent_id text, event_type text NOT NULL CHECK (event_type IN ('user_message','assistant_message','reasoning','tool_call','tool_result','command','file_change','compaction','branch','usage','warning','error','metadata')), role text, title text NOT NULL, preview_text text NOT NULL, display_data jsonb NOT NULL DEFAULT '{}', occurred_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), search_vector tsvector GENERATED ALWAYS AS (to_tsvector('english',title || ' ' || preview_text)) STORED, PRIMARY KEY (tenant_id,run_id,sequence), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX run_trace_events_search ON app.run_trace_events USING gin (search_vector); +CREATE INDEX run_trace_events_by_type ON app.run_trace_events (tenant_id,run_id,event_type,sequence); CREATE TABLE app.run_activity (tenant_id uuid NOT NULL, id uuid NOT NULL, run_id uuid NOT NULL, action text NOT NULL, detail text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); CREATE TABLE app.active_claims (tenant_id uuid NOT NULL, job_id uuid NOT NULL, claim_key text NOT NULL, run_id uuid NOT NULL, expires_at timestamptz, PRIMARY KEY (tenant_id,job_id,claim_key), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); diff --git a/packages/app/migrations/0002_native_run_artifacts.sql b/packages/app/migrations/0002_native_run_artifacts.sql new file mode 100644 index 00000000..79b06c21 --- /dev/null +++ b/packages/app/migrations/0002_native_run_artifacts.sql @@ -0,0 +1,21 @@ +-- Destructive cutover: terminal transcripts are intentionally not migrated. +DROP TABLE IF EXISTS app.run_transcripts; +ALTER TABLE app.runs DROP COLUMN IF EXISTS result; +ALTER TABLE app.runs DROP COLUMN IF EXISTS output_captured; +ALTER TABLE app.runs ADD COLUMN IF NOT EXISTS artifact_state text NOT NULL DEFAULT 'pending'; +ALTER TABLE app.runs ADD COLUMN IF NOT EXISTS artifact_error text; +ALTER TABLE app.jobs ADD COLUMN IF NOT EXISTS model text NOT NULL DEFAULT ''; +ALTER TABLE app.jobs ADD COLUMN IF NOT EXISTS effort text NOT NULL DEFAULT ''; +ALTER TABLE app.runs DROP CONSTRAINT IF EXISTS runs_artifact_state_check; +ALTER TABLE app.runs ADD CONSTRAINT runs_artifact_state_check CHECK (artifact_state IN ('pending','collecting','stored','partial','failed')); + +CREATE TABLE IF NOT EXISTS app.run_artifacts (tenant_id uuid NOT NULL, run_id uuid NOT NULL, id uuid NOT NULL, kind text NOT NULL CHECK (kind IN ('native_session','related_session','terminal_log','manifest')), object_key text NOT NULL, provider text NOT NULL, format text NOT NULL, format_version text, cli_version text, native_session_id text, byte_size bigint NOT NULL CHECK (byte_size >= 0), sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), state text NOT NULL CHECK (state IN ('pending','collecting','stored','partial','failed')), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,object_key), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX IF NOT EXISTS run_artifacts_by_run ON app.run_artifacts (tenant_id,run_id,created_at,id); +CREATE TABLE IF NOT EXISTS app.run_trace_events (tenant_id uuid NOT NULL, run_id uuid NOT NULL, sequence bigint NOT NULL CHECK (sequence > 0), id text NOT NULL, parent_id text, event_type text NOT NULL CHECK (event_type IN ('user_message','assistant_message','reasoning','tool_call','tool_result','command','file_change','compaction','branch','usage','warning','error','metadata')), role text, title text NOT NULL, preview_text text NOT NULL, display_data jsonb NOT NULL DEFAULT '{}', occurred_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), search_vector tsvector GENERATED ALWAYS AS (to_tsvector('english',title || ' ' || preview_text)) STORED, PRIMARY KEY (tenant_id,run_id,sequence), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX IF NOT EXISTS run_trace_events_search ON app.run_trace_events USING gin (search_vector); +CREATE INDEX IF NOT EXISTS run_trace_events_by_type ON app.run_trace_events (tenant_id,run_id,event_type,sequence); + +-- The product decision is to discard all pre-artifact run history. +TRUNCATE app.run_trace_events, app.run_artifacts, app.active_claims, app.lifecycle_deliveries, app.run_activity, app.runs, app.job_runs, app.invocations CASCADE; + +INSERT INTO app.schema_migrations(version) VALUES ('0002_native_run_artifacts') ON CONFLICT DO NOTHING; diff --git a/packages/app/migrations/README.md b/packages/app/migrations/README.md index 2b8c8c23..c5173770 100644 --- a/packages/app/migrations/README.md +++ b/packages/app/migrations/README.md @@ -17,5 +17,6 @@ connection string or expose it as a Worker variable. The initial schema deliberately excludes the inert legacy `pipes`, `deliveries`, and `flow_events` tables. Every application-owned relationship uses a tenant-qualified key so a child row cannot reference another tenant's -record. `run_transcripts` stores only scrubbed plaintext and provides the GIN -full-text index used by PostgreSQL search. +record. Native sessions live in object storage. `run_artifacts` records exact +keys and checksums, while `run_trace_events` is the bounded projection used by +the cursor-paginated UI and PostgreSQL search. diff --git a/packages/app/scripts/verify-schema.mjs b/packages/app/scripts/verify-schema.mjs index ab8f461d..d053b78e 100644 --- a/packages/app/scripts/verify-schema.mjs +++ b/packages/app/scripts/verify-schema.mjs @@ -21,8 +21,9 @@ try { if (duplicate.rowCount !== 0) throw new Error("invocation deduplication constraint failed"); await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,'queued','cipher')", [ids.tenantA, ids.runA, ids.jobA, ids.invocationA]); await client.query("INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,agent_name,state) VALUES ($1,$2,$3,$4,'linear','GEN-2113','codex','running')", [ids.tenantA, ids.executionA, ids.jobA, ids.invocationA]); - await client.query("INSERT INTO app.run_transcripts(tenant_id,run_id,transcript,byte_size) VALUES ($1,$2,'postgres durable orchestration',30)", [ids.tenantA, ids.executionA]); - const search = await client.query("SELECT run_id FROM app.run_transcripts WHERE tenant_id=$1 AND search_vector @@ plainto_tsquery('english',$2)", [ids.tenantA, "orchestration"]); + await client.query("INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,byte_size,sha256,state) VALUES ($1,$2,gen_random_uuid(),'native_session','tenants/a/runs/one/native/session.jsonl','codex','jsonl',10,$3,'stored')", [ids.tenantA, ids.executionA, "a".repeat(64)]); + await client.query("INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,event_type,title,preview_text) VALUES ($1,$2,1,'event-1','assistant_message','Assistant','postgres durable orchestration')", [ids.tenantA, ids.executionA]); + const search = await client.query("SELECT run_id FROM app.run_trace_events WHERE tenant_id=$1 AND search_vector @@ plainto_tsquery('english',$2)", [ids.tenantA, "orchestration"]); if (search.rowCount !== 1) throw new Error("tenant-scoped full-text search failed"); let isolated = false; await client.query("SAVEPOINT cross_tenant"); diff --git a/packages/app/src/access-tokens.ts b/packages/app/src/access-tokens.ts index 2f358f76..e5327c15 100644 --- a/packages/app/src/access-tokens.ts +++ b/packages/app/src/access-tokens.ts @@ -1,4 +1,6 @@ import type { Env, OAuthProps } from "./types"; +import { databaseFor } from "./postgres/database"; +import { AccessTokenRepository } from "./postgres/access-token-repository"; export const ACCESS_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const; export type AccessScope = typeof ACCESS_SCOPES[number]; @@ -30,10 +32,5 @@ export async function authenticateAccessToken(request: Request, env: Env): Promi if (!authorization?.startsWith("Bearer fzt_")) return null; const token = authorization.slice(7), tenantId = accessTokenTenant(token); if (!tenantId) return null; - const stub = env.TENANTS.get(env.TENANTS.idFromName(`tenant:${tenantId}`)); - const response = await stub.fetch("https://tenant/access-tokens/authenticate", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ digest: await accessTokenDigest(token), tenantId }), - }); - if (!response.ok) return null; - return response.json(); + return new AccessTokenRepository(databaseFor(env), tenantId).authenticate(await accessTokenDigest(token)); } diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts new file mode 100644 index 00000000..fd87b95b --- /dev/null +++ b/packages/app/src/agent-driver.ts @@ -0,0 +1,56 @@ +export type AgentKind = "codex" | "claude" | "pi"; + +export interface AgentConfiguration { model?: string; effort?: string; } +export interface ArtifactLocator { + /** Paths are interpreted inside the guest; the compute backend only transports files. */ + roots: string[]; + fileNameIncludes: string; + sessionId?: string; + /** Prints one canonical native session path from inside the guest. */ + discoverCommand: string; +} +export interface AgentLaunchSpec { + executable: string; + args: string[]; + env: Record; + stdin: "prompt"; + artifacts: ArtifactLocator; +} +export interface AgentDriver { + readonly kind: AgentKind; + launch(runId: string, config: AgentConfiguration): AgentLaunchSpec; +} + +class CodexDriver implements AgentDriver { + readonly kind = "codex" as const; + launch(_runId: string, config: AgentConfiguration): AgentLaunchSpec { + const args = ["exec", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"']; + if (config.model?.trim()) args.push("--model", config.model.trim()); + if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`); + return { executable: "codex", args, env: {}, stdin: "prompt", artifacts: { roots: ["${CODEX_HOME:-$HOME/.codex}/sessions"], fileNameIncludes: "rollout-", discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` } }; + } +} + +class ClaudeDriver implements AgentDriver { + readonly kind = "claude" as const; + launch(runId: string, config: AgentConfiguration): AgentLaunchSpec { + const args = ["-p", "--dangerously-skip-permissions", "--session-id", runId]; + if (config.model?.trim()) args.push("--model", config.model.trim()); + if (config.effort?.trim()) args.push("--effort", config.effort.trim()); + return { executable: "claude", args, env: {}, stdin: "prompt", artifacts: { roots: ["$HOME/.claude/projects"], fileNameIncludes: runId, sessionId: runId, discoverCommand: `find "$HOME/.claude/projects" -type f -name '*${runId}.jsonl' -print | head -1` } }; + } +} + +class PiDriver implements AgentDriver { + readonly kind = "pi" as const; + launch(runId: string, config: AgentConfiguration): AgentLaunchSpec { + const sessionDir = `/tmp/factorize-artifacts/${runId}/pi`; + const args = ["-p", "--session-id", runId, "--session-dir", sessionDir]; + if (config.model?.trim()) args.push("--model", config.model.trim()); + if (config.effort?.trim()) args.push("--thinking", config.effort.trim()); + return { executable: "pi", args, env: {}, stdin: "prompt", artifacts: { roots: [sessionDir], fileNameIncludes: ".jsonl", sessionId: runId, discoverCommand: `find '${sessionDir}' -type f -name '*.jsonl' -print | head -1` } }; + } +} + +const drivers: Record = { codex: new CodexDriver(), claude: new ClaudeDriver(), pi: new PiDriver() }; +export function agentDriver(kind: AgentKind): AgentDriver { return drivers[kind]; } diff --git a/packages/app/src/alarm-coordinator.ts b/packages/app/src/alarm-coordinator.ts new file mode 100644 index 00000000..6fd22fe7 --- /dev/null +++ b/packages/app/src/alarm-coordinator.ts @@ -0,0 +1,20 @@ +import { DurableObject } from "cloudflare:workers"; +import { databaseFor } from "./postgres/database"; +import { RunRepository } from "./postgres/run-repository"; +import { RunScheduler } from "./postgres/run-scheduler"; +import type { Env } from "./types"; + +/** The sole remaining Durable Object responsibility: reliable wakeups. */ +export class AlarmCoordinator extends DurableObject { + async fetch(request: Request): Promise { + if (request.method !== "POST" || new URL(request.url).pathname !== "/wake") return new Response("Not found", { status: 404 }); + await this.schedule(); return Response.json({ scheduled: true }); + } + async alarm(): Promise { try { await new RunScheduler(databaseFor(this.env), this.env).process(); } finally { await this.schedule(); } } + private async schedule() { + const next = await new RunRepository(databaseFor(this.env)).nextWakeAt(), current = await this.ctx.storage.getAlarm(); + if (!next) return; + const desired = Math.max(Date.now() + 100, next.getTime()); + if (current === null || current > desired) await this.ctx.storage.setAlarm(desired); + } +} diff --git a/packages/app/src/artifact-upload.ts b/packages/app/src/artifact-upload.ts new file mode 100644 index 00000000..c993b063 --- /dev/null +++ b/packages/app/src/artifact-upload.ts @@ -0,0 +1,64 @@ +import { artifactKey } from "./artifacts"; +import { hmac } from "./crypto"; +import type { Env } from "./types"; +import { databaseFor } from "./postgres/database"; +import { ArtifactRepository } from "./postgres/artifact-repository"; +import { TraceRepository } from "./postgres/trace-repository"; +import { parseTraceStream } from "./trace"; + +export interface ArtifactUploadGrant { + tenantId: string; + runId: string; + path: string; + contentType: string; + provider: "codex" | "claude" | "pi"; + format: "jsonl"; + nativeSessionId?: string; + expiresAt: number; +} + +const encoder = new TextEncoder(); +const b64url = (value: string) => btoa(String.fromCharCode(...encoder.encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +const fromB64url = (value: string) => { + const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4); + return new TextDecoder().decode(Uint8Array.from(atob(padded), char => char.charCodeAt(0))); +}; + +export async function issueArtifactUploadGrant(grant: ArtifactUploadGrant, secret: string): Promise { + const payload = b64url(JSON.stringify(grant)); + return `${payload}.${await hmac(payload, secret)}`; +} + +export async function readArtifactUploadGrant(token: string, secret: string, now = Date.now()): Promise { + const separator = token.lastIndexOf("."); + if (separator < 1) return null; + const payload = token.slice(0, separator), signature = token.slice(separator + 1); + if (signature !== await hmac(payload, secret)) return null; + try { + const value = JSON.parse(fromB64url(payload)) as ArtifactUploadGrant; + if (!value.tenantId || !value.runId || !value.path || !value.contentType || !Number.isSafeInteger(value.expiresAt) || value.expiresAt < now) return null; + artifactKey(value.tenantId, value.runId, value.path); + return value; + } catch { return null; } +} + +/** Private streaming ingress used by guest harnesses. No artifact bytes are buffered. */ +export async function artifactUpload(request: Request, env: Env, token: string): Promise { + if (request.method !== "PUT") return new Response("Method not allowed", { status: 405, headers: { Allow: "PUT" } }); + if (!env.RUN_ARTIFACTS) return new Response("Artifact storage is unavailable", { status: 503 }); + const grant = await readArtifactUploadGrant(token, env.SESSION_SIGNING_SECRET); + if (!grant) return new Response("Invalid or expired artifact upload grant", { status: 401 }); + if (!request.body) return new Response("Artifact body is required", { status: 400 }); + const sha256 = request.headers.get("X-Artifact-SHA256")?.toLowerCase() ?? "", size = Number(request.headers.get("Content-Length")); + if (!/^[0-9a-f]{64}$/.test(sha256) || !Number.isSafeInteger(size) || size < 0) return new Response("Artifact checksum and size are required", { status: 400 }); + if (size > 256 * 1024 * 1024) return new Response("Artifact exceeds the 256 MiB limit", { status: 413 }); + const suppliedType = request.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase(); + if (suppliedType !== grant.contentType.toLowerCase()) return new Response("Artifact content type does not match the grant", { status: 400 }); + const key = artifactKey(grant.tenantId, grant.runId, grant.path); + const object = await env.RUN_ARTIFACTS.put(key, request.body, { httpMetadata: { contentType: grant.contentType }, customMetadata: { tenantId: grant.tenantId, runId: grant.runId }, sha256 }); + await new ArtifactRepository(databaseFor(env), grant.tenantId).record({ runId: grant.runId, kind: "native_session", objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }); + const stored = await env.RUN_ARTIFACTS.get(key); + if (!stored) return new Response("Artifact disappeared after upload", { status: 502 }); + await new TraceRepository(databaseFor(env), grant.tenantId).replace(grant.runId, await parseTraceStream(grant.provider, stored.body)); + return Response.json({ key, etag: object.httpEtag }, { status: 201 }); +} diff --git a/packages/app/src/artifacts.ts b/packages/app/src/artifacts.ts new file mode 100644 index 00000000..45c55e06 --- /dev/null +++ b/packages/app/src/artifacts.ts @@ -0,0 +1,57 @@ +export type ArtifactKind = "native_session" | "related_session" | "terminal_log" | "manifest"; +export type ArtifactState = "pending" | "collecting" | "stored" | "partial" | "failed"; + +export interface RunArtifact { + id: string; + runId: string; + kind: ArtifactKind; + objectKey: string; + provider: string; + format: string; + formatVersion?: string; + cliVersion?: string; + nativeSessionId?: string; + byteSize: number; + sha256: string; + state: ArtifactState; +} + +export interface ArtifactWrite { + key: string; + body: ReadableStream | ArrayBuffer | Uint8Array | string; + contentType?: string; + metadata?: Record; +} + +/** Blob storage boundary. Execution and agent drivers do not depend on R2. */ +export interface ArtifactStore { + put(input: ArtifactWrite): Promise<{ key: string; etag?: string }>; + get(key: string, range?: { offset: number; length: number }): Promise; + delete(key: string): Promise; +} + +/** R2 implementation; keys are always supplied from PostgreSQL, never discovered by listing. */ +export class R2ArtifactStore implements ArtifactStore { + constructor(private bucket: R2Bucket) {} + + async put(input: ArtifactWrite): Promise<{ key: string; etag?: string }> { + const object = await this.bucket.put(input.key, input.body, { + httpMetadata: input.contentType ? { contentType: input.contentType } : undefined, + customMetadata: input.metadata, + }); + return { key: input.key, etag: object?.httpEtag }; + } + + async get(key: string, range?: { offset: number; length: number }): Promise { + const object = await this.bucket.get(key, range ? { range } : undefined); + return object?.body ?? null; + } + + async delete(key: string): Promise { await this.bucket.delete(key); } +} + +export function artifactKey(tenantId: string, runId: string, relativePath: string): string { + const safe = relativePath.split("/").filter(Boolean).map(part => encodeURIComponent(part)).join("/"); + if (!safe || relativePath.includes("..")) throw new Error("Invalid artifact path"); + return `tenants/${encodeURIComponent(tenantId)}/runs/${encodeURIComponent(runId)}/${safe}`; +} diff --git a/packages/app/src/auth-do.ts b/packages/app/src/auth-do.ts deleted file mode 100644 index 98855ee6..00000000 --- a/packages/app/src/auth-do.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { DurableObject } from "cloudflare:workers"; -import { hashPassword, normalizeEmail, tokenDigest, validEmail, validPassword, verifyPassword } from "./auth"; -import type { Env } from "./types"; - -const json = (value: unknown, status = 200) => Response.json(value, { status }); -const now = () => Math.floor(Date.now() / 1000); - -export class AuthStore extends DurableObject { - constructor(ctx: DurableObjectState, env: Env) { - super(ctx, env); - ctx.storage.sql.exec(` - CREATE TABLE IF NOT EXISTS auth_users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, email_verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL); - CREATE TABLE IF NOT EXISTS auth_accounts (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, provider TEXT NOT NULL, provider_account_id TEXT NOT NULL, password_hash TEXT, UNIQUE(provider, provider_account_id)); - CREATE TABLE IF NOT EXISTS auth_reset_tokens (digest TEXT PRIMARY KEY, user_id TEXT NOT NULL, expires_at INTEGER NOT NULL, used_at INTEGER); - CREATE TABLE IF NOT EXISTS auth_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER); - `); - } - - async fetch(request: Request): Promise { - const url = new URL(request.url); - try { - const input = await request.json().catch(() => ({})) as Record; - if (request.method === "POST" && url.pathname === "/signup") return this.signup(input); - if (request.method === "POST" && url.pathname === "/login") return this.login(input); - if (request.method === "POST" && url.pathname === "/reset/request") return this.requestReset(input); - if (request.method === "POST" && url.pathname === "/reset/complete") return this.completeReset(input); - return new Response("Not found", { status: 404 }); - } catch (error) { console.error("auth store error", error); return json({ error: "Authentication failed" }, 500); } - } - - private async signup(input: Record): Promise { - const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); - if (!validEmail(email) || !validPassword(password)) return json({ error: "Use a valid email and a password of at least 12 characters." }, 400); - if (this.ctx.storage.sql.exec("SELECT id FROM auth_users WHERE email=?", email).toArray().length) return json({ error: "An account already exists for that email." }, 409); - const userId = crypto.randomUUID(); - this.ctx.storage.sql.exec("INSERT INTO auth_users VALUES (?,?,0,?)", userId, email, now()); - this.ctx.storage.sql.exec("INSERT INTO auth_accounts VALUES (?,?,?,?,?)", crypto.randomUUID(), userId, "credential", userId, await hashPassword(password)); - return json({ userId, email, tenantId: userId, emailVerified: false }, 201); - } - - private async login(input: Record): Promise { - const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); - const user = this.ctx.storage.sql.exec("SELECT id,email,email_verified FROM auth_users WHERE email=?", email).toArray()[0] as any; - const account = user && this.ctx.storage.sql.exec("SELECT password_hash FROM auth_accounts WHERE user_id=? AND provider='credential'", user.id).toArray()[0] as any; - if (!user || !account?.password_hash || !(await verifyPassword(password, String(account.password_hash)))) return json({ error: "Invalid email or password." }, 401); - return json({ userId: user.id, email: user.email, tenantId: user.id, emailVerified: Boolean(user.email_verified) }); - } - - private async requestReset(input: Record): Promise { - const email = normalizeEmail(String(input.email ?? "")); - const user = this.ctx.storage.sql.exec("SELECT id FROM auth_users WHERE email=?", email).toArray()[0] as any; - // Always return the same response to avoid account enumeration. - if (!user) return json({ ok: true }); - const token = crypto.randomUUID() + crypto.randomUUID(); - this.ctx.storage.sql.exec("INSERT INTO auth_reset_tokens VALUES (?,?,?,NULL)", await tokenDigest(token, this.env.SESSION_SIGNING_SECRET), user.id, now() + 3600); - return json({ ok: true, ...(this.env.AUTH_RESET_RETURN_TOKEN === "true" ? { token } : {}) }); - } - - private async completeReset(input: Record): Promise { - const token = String(input.token ?? ""), password = String(input.password ?? ""); - if (!token || !validPassword(password)) return json({ error: "The reset link or password is invalid." }, 400); - const digest = await tokenDigest(token, this.env.SESSION_SIGNING_SECRET); - const row = this.ctx.storage.sql.exec("SELECT user_id FROM auth_reset_tokens WHERE digest=? AND used_at IS NULL AND expires_at>?", digest, now()).toArray()[0] as any; - if (!row) return json({ error: "The reset link is invalid or expired." }, 400); - this.ctx.storage.sql.exec("UPDATE auth_accounts SET password_hash=? WHERE user_id=? AND provider='credential'", await hashPassword(password), row.user_id); - this.ctx.storage.sql.exec("UPDATE auth_reset_tokens SET used_at=? WHERE digest=?", now(), digest); - this.ctx.storage.sql.exec("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", now(), row.user_id); - return json({ ok: true }); - } -} diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index c0534dd8..84520e8a 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -1,6 +1,6 @@ import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; import { base64 } from "./crypto"; -import { defaultAgentCommand, shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; +import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; const API = "https://exe.dev/exec"; const capabilities = ["output", "recovery", "stop"] as const; @@ -14,23 +14,9 @@ export function isOwnedVmName(vm: string): boolean { return /^factorize-[a-z0-9](?:[a-z0-9-]{0,47}[a-z0-9])?$/.test(vm); } -function shellWords(value: string): string[] { - const words: string[] = []; - for (const match of value.matchAll(/(?:[^\s'\"]+|'[^']*'|\"[^\"]*\")+/g)) words.push(match[0].replace(/^'|'$/g, "").replace(/^\"|\"$/g, "")); - return words; -} - -function agentCommand(connection: ExeRunConnection): string { - const args = shellWords(connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind)); - if (connection.agentKind === "codex") args.push( - "--color", "always", - "-c", "model_provider=exe-llm", - "-c", 'model_providers.exe-llm.name="exe-llm"', - "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"', - ); - if (connection.model?.trim()) args.push("--model", connection.model.trim()); - if (connection.effort?.trim() && connection.agentKind === "codex") args.push("-c", `model_reasoning_effort=${connection.effort.trim()}`); - return args.map(shellAtom).join(" "); +function harnessCommand(harness: NonNullable): string { + const environment = Object.entries(harness.env).map(([name, value]) => `${name}=${shellAtom(value)}`); + return [...environment, harness.executable, ...harness.args].map((value, index) => index < environment.length ? value : shellAtom(value)).join(" "); } export interface ExePermissionTest { ok: boolean; missingPermissions: string[]; tags: string[]; checks: BackendCommandResult[] } @@ -77,13 +63,13 @@ export class ExeVmBackend implements ExecutionBackend { async test(): Promise { return this.api("ls --json"); } - async validateAgentAndModels(agentKind: "codex" | "claude"): Promise { + async validateAgentAndModels(agentKind: "codex" | "claude" | "pi"): Promise { const vm = vmNameFor(`validate-${crypto.randomUUID()}`); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim()); if (!created.ok) throw new Error(`Could not create the validation VM (${created.status}): ${created.body.slice(0, 300)}`); try { - const binary = agentKind === "codex" ? "codex" : "claude"; + const binary = agentKind; const remote = `command -v ${binary} >/dev/null && curl --fail --silent --show-error https://llm.int.exe.xyz/v1/models | jq -cer '[.data[]?.id | strings] | unique'`; let result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`); for (let attempt = 1; !result.ok && attempt < 5; attempt++) result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`); @@ -100,6 +86,7 @@ export class ExeVmBackend implements ExecutionBackend { async launch(request: LaunchRequest): Promise { const connection = this.connection as ExeRunConnection; if (!connection.agentKind) throw new Error("The job is missing its agent configuration"); + if (!request.harness) throw new Error("The run is missing its agent harness launch plan"); const vm = vmNameFor(request.runId); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim()); @@ -114,7 +101,7 @@ export class ExeVmBackend implements ExecutionBackend { "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:${output} ${agentCommand(connection)}; fi`, + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:${output} ${harnessCommand(request.harness)}; fi`, "echo started", ].join("; "); let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); @@ -146,6 +133,12 @@ export class ExeVmBackend implements ExecutionBackend { return result.ok ? result.body : null; } + async collectArtifact(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }) { + const remote = `file=$(${request.discoverCommand}); test -n "$file"; test -f "$file"; size=$(wc -c < "$file" | tr -d ' '); sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(request.uploadUrl)}`; + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + return { ok: result.ok, detail: result.ok ? undefined : `Native session upload failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; + } + async stop(handle: RunHandle): Promise { const result = await this.deleteVm(this.vm(handle)); return { state: result.ok ? "stopped" : "failed", detail: result.ok ? undefined : `VM deletion failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; diff --git a/packages/app/src/exe.ts b/packages/app/src/exe.ts index 5095b29b..46d3d1ba 100644 --- a/packages/app/src/exe.ts +++ b/packages/app/src/exe.ts @@ -1,7 +1,9 @@ +import type { AgentKind } from "./agent-driver"; + export interface ExeConnection { apiToken: string; tags: string[]; - agentKind: "codex" | "claude"; + agentKind: AgentKind; models?: string[]; modelsRefreshedAt?: string; } @@ -21,5 +23,6 @@ export function shellAtom(value: string): string { export function defaultAgentCommand(agentKind: string): string { if (agentKind === "codex") return "codex exec --dangerously-bypass-approvals-and-sandbox"; if (agentKind === "claude") return "claude -p --dangerously-skip-permissions"; + if (agentKind === "pi") return "pi -p"; return agentKind; } diff --git a/packages/app/src/execution.ts b/packages/app/src/execution.ts index 4ef05c10..736d4184 100644 --- a/packages/app/src/execution.ts +++ b/packages/app/src/execution.ts @@ -13,6 +13,7 @@ export interface BackendCommandResult { export interface LaunchRequest { runId: string; prompt: string; + harness?: { executable: string; args: string[]; env: Record }; } /** Opaque to orchestration. Only the backend that created it may interpret id. */ @@ -36,6 +37,7 @@ export interface PromptDeliveryReceipt { state: Exclude; command?: BackendCommandResult; } +export interface ArtifactCollectionReceipt { ok: boolean; detail?: string; command?: BackendCommandResult; } /** Provider-neutral boundary. Output and recovery are opt-in capabilities. */ export interface ExecutionBackend { @@ -46,6 +48,7 @@ export interface ExecutionBackend { stop(handle: RunHandle): Promise; deliverPrompt?(handle: RunHandle, prompt: string): Promise; readOutput?(handle: RunHandle): Promise; + collectArtifact?(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }): Promise; } /** Maps persisted execution states onto the public contract. */ diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 172f0d20..5ff1ed5f 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -1,6 +1,21 @@ import type { Env, OAuthProps } from "./types"; import type { JobInput, ManualInvocationInput } from "./flow-schemas"; import { nextOccurrence, validateScheduleConfig } from "./schedule"; +import { databaseFor } from "./postgres/database"; +import { IdentityRepository } from "./postgres/identity-repository"; +import { AccessTokenRepository } from "./postgres/access-token-repository"; +import { PostgresJobRepository } from "./postgres/job-repository"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { decrypt, encrypt } from "./crypto"; +import { InvocationService, type Job, type Trigger } from "./job-domain"; +import { RunQueryRepository } from "./postgres/run-query-repository"; +import { TraceRepository } from "./postgres/trace-repository"; +import { GitHubRepository } from "./postgres/github-repository"; +import { IntegrationService } from "./postgres/integration-service"; +import { OperationsRepository } from "./postgres/operations-repository"; +import { installedTriggerAvailability } from "./trigger-availability"; +import { invokeCustomHandler } from "./custom-handler"; +import { validateWebhookHandler } from "./webhook-trigger"; export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } @@ -11,29 +26,42 @@ type Scope = "flows:read" | "flows:write" | "runs:read" | "runs:write"; export class ApiService { constructor(private env: Env, private auth: OAuthProps) {} - private stub() { return this.env.TENANTS.get(this.env.TENANTS.idFromName(`tenant:${this.auth.tenantId}`)); } + private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } + private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } - private async authorize(scope: Scope): Promise { - if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); - const response = await this.stub().fetch("https://tenant/authorize", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userId: this.auth.userId, sessionVersion: this.auth.sessionVersion, accessTokenId: this.auth.accessTokenId }), - }); - if (!response.ok) { - const body = await response.json().catch(() => ({})) as { error?: string }; - throw new ServiceError(401, "invalid_token", body.error ?? "The request is not authorized."); + private async executionTarget(id: string) { + if (id.startsWith("amp:")) { + const connectionId = id.slice(4), value = await this.connections().get<{ project: string }>(`amp:${connectionId}`); + if (!value) throw new ServiceError(400, "invalid_request", "Execution target not found"); + return { connectionId, workspace: value.project, cwd: "", agentKind: "Amp" }; } + const value = await this.connections().get<{ agentKind: string }>(`exe:${id}`); + if (!value) throw new ServiceError(400, "invalid_request", "Execution target not found"); + return { connectionId: id, workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind }; + } + + private normalizedTriggers(input: JobInput["triggers"], existing: Trigger[] = []): Trigger[] { + const source = input.some(trigger => trigger.kind === "manual") ? input : [{ kind: "manual" as const, enabled: true, config: {} }, ...input]; + const prior = new Map(existing.map(trigger => [trigger.id, trigger])), used = new Set(existing.map(trigger => trigger.slug)); + let next = 1, timestamp = new Date().toISOString(); + return source.map(trigger => { + const old = trigger.id ? prior.get(trigger.id) : undefined; + while (used.has(`trigger-${next}`)) next++; + const slug = old?.slug ?? trigger.slug ?? `trigger-${next++}`; used.add(slug); + return { id: old?.id ?? trigger.id ?? crypto.randomUUID(), jobId: old?.jobId ?? "", kind: trigger.kind, slug, enabled: trigger.enabled !== false, config: trigger.config, createdAt: old?.createdAt ?? timestamp, updatedAt: timestamp }; + }); + } + + private presentJob(job: Job) { + return { ...job, runNameTemplate: job.runNameTemplate ?? "", executionTargetId: `${job.executionTarget.agentKind === "Amp" ? "amp:" : ""}${job.executionTarget.connectionId}`, agentKind: job.executionTarget.agentKind, runningCount: 0, currentRuns: 0, maxConcurrency: job.concurrencyLimit, lastRunState: null }; } - private async call(scope: Scope, path: string, init?: RequestInit): Promise { - await this.authorize(scope); - const response = await this.stub().fetch(`https://tenant${path}`, init); - let body: unknown = null; - const text = await response.text(); - if (text) { try { body = JSON.parse(text); } catch { body = { error: text }; } } - if (!response.ok) throw new ServiceError(response.status, response.status === 404 ? "not_found" : "operation_failed", (body as any)?.error ?? "Operation failed"); - return body; + private async authorize(scope: Scope): Promise { + if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); + const database = databaseFor(this.env); + const member = await new IdentityRepository(database, this.auth.tenantId).member(this.auth.userId); + const tokenActive = !this.auth.accessTokenId || await new AccessTokenRepository(database, this.auth.tenantId).active(this.auth.accessTokenId); + if (member?.role !== "owner" || member.sessionVersion !== this.auth.sessionVersion || !tokenActive) throw new ServiceError(401, "invalid_token", "The request is not authorized."); } private publicJob(value: any) { @@ -44,29 +72,51 @@ export class ApiService { return value; } - listExeConnections() { return this.call("flows:read", "/connections/status").then((value: any) => value.exeConnections ?? []); } - listGitHubInstallations() { return this.call("flows:read", "/github/installations"); } - listTailIntegrations() { return this.call("flows:read", "/connections/cloudflare-tail"); } - listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); } - search(query: string) { return this.call("runs:read", `/v1/search?q=${encodeURIComponent(query)}`); } - getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); } - getRunDiagnostics(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}/diagnostics`); } - stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); } - killRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/kill`, { method: "POST" }); } - async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); } - async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); } - listJobEvents(jobId: string, limit = 50) { return this.call("runs:read", `/v1/jobs/${encodeURIComponent(jobId)}/events?limit=${limit}`); } - listWebhookDeliveries(query: URLSearchParams) { return this.call("runs:read", `/v1/webhooks/deliveries?${query}`); } - getWebhookDelivery(deliveryId: string) { return this.call("runs:read", `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}`); } - testJobHandler(input: { handlerCode: string; payload: Record }) { return this.call("flows:write", "/v1/job-handlers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } - async createJob(input: JobInput) { return this.publicJob(await this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } - async updateJob(jobId: string, input: JobInput) { return this.publicJob(await this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } - deleteJob(jobId: string) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE" }); } - setJobEnabled(jobId: string, enabled: boolean) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}/${enabled ? "enable" : "disable"}`, { method: "POST" }); } - invokeJob(jobId: string, input: ManualInvocationInput) { return this.call("runs:write", `/v1/jobs/${encodeURIComponent(jobId)}/invocations`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } - listExecutionTargets() { return this.call("flows:read", "/v1/execution-targets"); } - diagnoseExeIntegration(connectionId: string) { return this.call("flows:write", `/v1/integrations/exe/${encodeURIComponent(connectionId)}/diagnostics`, { method: "POST" }); } - listJobTriggerAvailability() { return this.call("flows:read", "/v1/job-trigger-availability"); } + async listExeConnections() { await this.authorize("flows:read"); return (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections; } + async listGitHubInstallations() { await this.authorize("flows:read"); return new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations(); } + async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); } + async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); } + async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); } + async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); return run; } + async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); } + async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } + async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } + killRun(runId: string) { return this.stopRun(runId); } + async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); } + async getJob(jobId: string) { await this.authorize("flows:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } + async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } + async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } + async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } + async testJobHandler(input: { handlerCode: string; payload: Record }) { await this.authorize("flows:write"); const config: any = { provider: "linear", projectId: "handler-test", matchRules: [], handlerCode: input.handlerCode }; validateWebhookHandler(config); if (!this.env.CUSTOM_HANDLER_LOADER) throw new ServiceError(503,"operation_failed","Webhook handler platform is unavailable"); return invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, config, input.payload); } + async createJob(input: JobInput) { + await this.authorize("flows:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); + const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); + const job: Job = { id, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp }; + try { return this.presentJob(await this.jobs().save(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; } + } + async updateJob(jobId: string, input: JobInput) { + await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); + const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); + return this.presentJob(await repository.save({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() })); + } + async deleteJob(jobId: string) { await this.authorize("flows:write"); if (!await this.jobs().delete(jobId)) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, deleted: true }; } + async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); await repository.save({ ...job, enabled, updatedAt: new Date().toISOString() }); return { id: jobId, enabled }; } + async invokeJob(jobId: string, input: ManualInvocationInput) { + await this.authorize("runs:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); + const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); + const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); + const result = await service.invoke(jobId, { source: "manual", triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); + if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); + return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; + } + async listExecutionTargets() { + await this.authorize("flows:read"); const connections = this.connections(), kinds = await connections.kinds(); const targets: any[] = []; + for (const kind of kinds) if (kind.startsWith("exe:")) { const id = kind.slice(4), value = await connections.get(kind); targets.push({ id, kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind, models: value.models ?? [], modelsRefreshedAt: value.modelsRefreshedAt ?? null, efforts: value.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], capabilities: ["recovery", "stop"] }); } + else if (kind.startsWith("amp:")) { const id = kind.slice(4), value = await connections.get(kind); targets.push({ id: `amp:${id}`, kind: "amp", name: `Amp ยท ${value.project}`, workspace: value.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }); } + return targets; + } + async diagnoseExeIntegration(connectionId: string) { await this.authorize("flows:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } + async listJobTriggerAvailability() { await this.authorize("flows:read"); const connections=this.connections(), kinds=await connections.kinds(), states=(await new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()).map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } async previewSchedule(input: unknown) { await this.authorize("flows:read"); try { diff --git a/packages/app/src/github-registry.ts b/packages/app/src/github-registry.ts deleted file mode 100644 index 186b1283..00000000 --- a/packages/app/src/github-registry.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { DurableObject } from "cloudflare:workers"; -import type { Env } from "./types"; - -export class GitHubInstallationRegistryV2 extends DurableObject { - constructor(ctx: DurableObjectState, env: Env) { - super(ctx, env); - this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS installations (installation_id INTEGER PRIMARY KEY, tenant_id TEXT NOT NULL, account_login TEXT NOT NULL, account_type TEXT NOT NULL, state TEXT NOT NULL, updated_at TEXT NOT NULL)`); - } - async fetch(request: Request): Promise { - const url = new URL(request.url), installationId = Number(url.pathname.split("/")[2]); - if (!Number.isSafeInteger(installationId)) return new Response("Invalid installation", { status: 400 }); - const row = [...this.ctx.storage.sql.exec("SELECT * FROM installations WHERE installation_id = ?", installationId)][0] as any; - if (request.method === "GET") return row ? Response.json(row) : new Response("Not found", { status: 404 }); - if (request.method === "PUT") { - const value = await request.json() as any; - if (!value.tenantId) return new Response("Missing tenant", { status: 400 }); - if (row && row.tenant_id !== value.tenantId) return new Response("Installation belongs to another tenant", { status: 409 }); - this.ctx.storage.sql.exec("INSERT INTO installations VALUES (?,?,?,?,?,?) ON CONFLICT(installation_id) DO UPDATE SET account_login=excluded.account_login,account_type=excluded.account_type,state=excluded.state,updated_at=excluded.updated_at", installationId, value.tenantId, value.accountLogin ?? "", value.accountType ?? "", value.state ?? "active", new Date().toISOString()); - return Response.json({ ok: true }); - } - if (request.method === "PATCH" && row) { const { state } = await request.json() as any; this.ctx.storage.sql.exec("UPDATE installations SET state=?,updated_at=? WHERE installation_id=?", state, new Date().toISOString(), installationId); return Response.json({ ok: true }); } - if (request.method === "DELETE" && row) { this.ctx.storage.sql.exec("DELETE FROM installations WHERE installation_id=?", installationId); return Response.json({ ok: true, tenantId: row.tenant_id }); } - return new Response("Not found", { status: 404 }); - } -} - -/** @deprecated Retained only until the Phase 2 namespace-retirement deployment. */ -export class GitHubInstallationRegistry extends DurableObject {} diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 3e532f63..cc039ed1 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -2,12 +2,19 @@ import { Hono } from "hono"; import { deleteCookie, getCookie, setCookie } from "hono/cookie"; import { parse } from "hono/utils/cookie"; import { equalHmac, hmac } from "./crypto"; -import { Tenant, TenantV2 } from "./tenant"; -import { GitHubInstallationRegistry, GitHubInstallationRegistryV2 } from "./github-registry"; import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github"; import { apiKeysSettingsPage, authPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, loginPage, settingsPage } from "./ui"; import type { Env } from "./types"; import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; +import { databaseFor } from "./postgres/database"; +import { AuthRepository } from "./postgres/auth-repository"; +import { IdentityRepository } from "./postgres/identity-repository"; +import { AccessTokenRepository } from "./postgres/access-token-repository"; +import { IntegrationService } from "./postgres/integration-service"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { GitHubRepository } from "./postgres/github-repository"; +import { ProviderCatalog } from "./postgres/provider-catalog"; +import { WebhookService } from "./postgres/webhook-service"; const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>(); @@ -46,25 +53,23 @@ export const requestCookie = (request: Request, name: string) => { return header ? parse(header, name)[name] : undefined; }; -function tenant(c: { env: Env }, tenantId: string) { return c.env.TENANTS.get(c.env.TENANTS.idFromName(`tenant:${tenantId}`)); } -function githubRegistry(c: { env: Env }) { if (!c.env.GITHUB_INSTALLATIONS) throw new Error("GitHub registry is not configured"); return c.env.GITHUB_INSTALLATIONS.get(c.env.GITHUB_INSTALLATIONS.idFromName("github-installations")); } -function auth(c: { env: Env }) { if (!c.env.AUTH) throw new Error("Authentication is not configured"); return c.env.AUTH.get(c.env.AUTH.idFromName("auth")); } -async function authIdentity(c: any, path: string, input: Record) { const response = await auth(c).fetch(`https://auth${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); return { response, body: await response.json().catch(() => ({})) as any }; } +async function authIdentity(c: any, path: string, input: Record) { + const auth = new AuthRepository(databaseFor(c.env), c.env); + const result = path === "/signup" ? await auth.signup(input) : path === "/login" ? await auth.login(input) : path === "/reset/request" ? await auth.requestReset(input) : await auth.completeReset(input); + return { response: new Response(JSON.stringify(result.body), { status: result.status, headers: { "Content-Type": "application/json" } }), body: result.body as any }; +} async function establishSession(c: any, identity: { userId: string; email: string; tenantId: string }) { - const member = await tenant(c, identity.tenantId).fetch("https://tenant/members", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: identity.userId, email: identity.email }) }); - const data = await member.json() as { role: string; session_version: number }; + const data = await new IdentityRepository(databaseFor(c.env), identity.tenantId).upsertOwner(identity.userId, identity.email); if (data.role !== "owner") return false; const lifetime = 60 * 60 * 24 * 7; - setCookie(c, "factorize_session", await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: data.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); + setCookie(c, "factorize_session", await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: data.sessionVersion }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); return true; } async function authed(c: any): Promise { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); } async function owner(c: any): Promise { const session = await authed(c); if (!session) return null; - const response = await tenant(c, session.tenantId).fetch(`https://tenant/members/${session.userId}`); - if (!response.ok) return null; - const member = await response.json() as { role: string; session_version: number }; - return member.role === "owner" && member.session_version === session.sessionVersion ? session : null; + const member = await new IdentityRepository(databaseFor(c.env), session.tenantId).member(session.userId); + return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null; } app.get("/api/health", (c) => c.json({ ok: true })); @@ -91,24 +96,24 @@ app.delete("/api/access/authorized-clients/:clientId", async (c) => { app.get("/api/access-tokens", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/access-tokens"); + return c.json(await new AccessTokenRepository(databaseFor(c.env), session.tenantId).list()); }); app.post("/api/access-tokens", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); const input = await c.req.json().catch(() => null) as any, name = typeof input?.name === "string" ? input.name.trim() : ""; - const requested = Array.isArray(input?.scopes) ? [...new Set(input.scopes)] : [], expiryDays = Number(input?.expiryDays); + const requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], expiryDays = Number(input?.expiryDays); if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any)) || ![7, 30, 90].includes(expiryDays)) return c.json({ error: "A name, supported scopes, and expiryDays of 7, 30, or 90 are required." }, 400); const token = issueAccessToken(session.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); - const response = await tenant(c, session.tenantId).fetch("https://tenant/access-tokens", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, scopes: requested, expiresAt, digest: await accessTokenDigest(token), userId: session.userId, sessionVersion: session.sessionVersion }) }); - const metadata = await response.json() as Record; - if (!response.ok) return c.json(metadata, response.status as any); - return c.json({ ...metadata, token }, response.status as any); + const metadata = await new AccessTokenRepository(databaseFor(c.env), session.tenantId).create({ name, scopes: requested, expiresAt, digest: await accessTokenDigest(token), userId: session.userId, sessionVersion: session.sessionVersion }); + if (!metadata) return c.json({ error: "The owner session is no longer active." }, 401); + return c.json({ ...metadata, token }, 201); }); app.delete("/api/access-tokens/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/access-tokens/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); + const revoked = await new AccessTokenRepository(databaseFor(c.env), session.tenantId).revoke(c.req.param("id")); + return revoked ? c.json({ revoked: true }) : c.json({ error: "Access token not found" }, 404); }); app.get("/auth/linear", async (c) => { @@ -134,13 +139,11 @@ app.get("/auth/linear/callback", async (c) => { const organization = me.data?.organization; const viewer = me.data?.viewer; if (!organization?.id || !viewer?.id) return c.text("Could not identify Linear workspace", 502); - const stub = tenant(c, organization.id); - const memberResponse = await stub.fetch("https://tenant/members", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: viewer.id, email: viewer.email }) }); - const member = await memberResponse.json() as { role: string; session_version: number }; + const member = await new IdentityRepository(databaseFor(c.env), organization.id).upsertOwner(viewer.id, viewer.email, organization.name); if (member.role !== "owner") return c.text("This Factorize tenant requires an owner invitation.", 403); - await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }) }); + await new ConnectionRepository(databaseFor(c.env), organization.id, c.env.CREDENTIAL_ENCRYPTION_KEY).put("linear", { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }); const lifetime = 60 * 60 * 24 * 7; - setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); + setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.sessionVersion }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); const oauthReturn = getCookie(c, "factorize_oauth_return"); if (oauthReturn?.startsWith("/authorize?") || oauthReturn?.startsWith("/device")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn); } return c.redirect("/jobs"); @@ -180,75 +183,73 @@ app.get("/auth/clickup/callback", async (c) => { const hookResponse = await fetch(`https://api.clickup.com/api/v2/team/${encodeURIComponent(team.id)}/webhook`, { method: "POST", headers: { Authorization: tokens.access_token, "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: `${c.env.APP_ORIGIN}/webhooks/clickup/${encodeURIComponent(session.tenantId)}`, events: ["taskCreated", "taskUpdated", "taskStatusUpdated", "taskAssigneeUpdated", "taskTagUpdated", "taskMoved"] }) }); const hook = await hookResponse.json() as any; if (!hookResponse.ok || !hook.id) return c.text("Could not register the ClickUp webhook", 502); - await tenant(c, session.tenantId).fetch("https://tenant/connections/clickup", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, teamId: String(team.id), teamName: team.name, webhookId: String(hook.id), webhookSecret: hook.secret }) }); + await new ConnectionRepository(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).put("clickup", { accessToken: tokens.access_token, teamId: String(team.id), teamName: team.name, webhookId: String(hook.id), webhookSecret: hook.secret }); deleteCookie(c, "clickup_oauth_state", { path: "/auth/clickup" }); return c.redirect("/settings/integrations"); }); app.get("/api/connections/status", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/status"); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).status()); }); app.get("/api/connections/cloudflare-tail", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/cloudflare-tail"); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).tails()); }); app.post("/api/connections/cloudflare-tail", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/cloudflare-tail", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveTail(await c.req.json()), 201); }); app.put("/api/connections/cloudflare-tail/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveTail({ ...await c.req.json() as any, integrationId: c.req.param("id") })); }); app.post("/api/connections/cloudflare-tail/:id/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}/test`, { method: "POST" }); + const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testTail(c.req.param("id")); return result ? c.json(result) : c.json({ error: "Not found" }, 404); }); app.delete("/api/connections/cloudflare-tail/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); + const deleted = await new ConnectionRepository(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).delete(`cloudflare-tail:${c.req.param("id")}`); return deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); }); app.get("/api/linear/projects", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/linear/projects"); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).linearProjects()); }); app.get("/api/linear/options", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/linear/options"); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).linearOptions()); }); app.get("/api/clickup/lists", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/clickup/lists"); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).clickUpLists()); }); app.get("/api/clickup/options", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/clickup/options?listId=${encodeURIComponent(c.req.query("listId") ?? "")}`); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).clickUpOptions(c.req.query("listId") ?? "")); }); app.get("/api/github/installations", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/github/installations"); + return c.json(await new GitHubRepository(databaseFor(c.env), session.tenantId).installations()); }); app.get("/api/github/installations/:id/repositories", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("id"))}/repositories`); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).githubRepositories(Number(c.req.param("id")))); }); app.get("/api/github/installations/:installationId/repositories/:repositoryId/issue-options", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("installationId"))}/repositories/${encodeURIComponent(c.req.param("repositoryId"))}/issue-options`); + return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).githubIssueOptions(Number(c.req.param("installationId")), Number(c.req.param("repositoryId")))); }); app.delete("/api/github/installations/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const response = await tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); - if (response.ok) await githubRegistry(c).fetch(`https://registry/installations/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); - return response; + return await new GitHubRepository(databaseFor(c.env), session.tenantId).delete(Number(c.req.param("id"))) ? c.json({ ok: true }) : c.json({ error: "Not found" }, 404); }); app.get("/auth/github/install", async (c) => { const session = await owner(c); if (!session) return c.redirect("/auth/linear"); if (!c.env.GITHUB_APP_SLUG) return c.text("GitHub App is not configured", 503); const nonce = crypto.randomUUID(); const state = await signSetupState({ tenantId: session.tenantId, userId: session.userId, nonce, exp: Math.floor(Date.now() / 1000) + 600 }, c.env.SESSION_SIGNING_SECRET); - await tenant(c, session.tenantId).fetch("https://tenant/github/setup-state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nonce, exp: Math.floor(Date.now() / 1000) + 600 }) }); + await new GitHubRepository(databaseFor(c.env), session.tenantId).saveSetupState(nonce, Math.floor(Date.now() / 1000) + 600); return c.redirect(`https://github.com/apps/${encodeURIComponent(c.env.GITHUB_APP_SLUG)}/installations/new?state=${encodeURIComponent(state)}`); }); app.get("/auth/github/setup", async (c) => { @@ -256,48 +257,45 @@ app.get("/auth/github/setup", async (c) => { const state = await readSetupState(c.req.query("state") ?? "", c.env.SESSION_SIGNING_SECRET); const installationId = Number(c.req.query("installation_id")); if (!state || state.tenantId !== session.tenantId || state.userId !== session.userId || !Number.isSafeInteger(installationId)) return c.text("Invalid or expired setup state", 400); - const consume = await tenant(c, session.tenantId).fetch("https://tenant/github/setup-state/consume", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nonce: state.nonce }) }); - if (!consume.ok) return c.text("Setup state was already used", 400); + if (!await new GitHubRepository(databaseFor(c.env), session.tenantId).consumeSetupState(state.nonce)) return c.text("Setup state was already used", 400); if (!c.env.GITHUB_APP_ID || !c.env.GITHUB_APP_PRIVATE_KEY) return c.text("GitHub App is not configured", 503); const jwt = await createAppJwt(c.env.GITHUB_APP_ID, c.env.GITHUB_APP_PRIVATE_KEY.replaceAll("\\n", "\n")); const gh = await fetch(`https://api.github.com/app/installations/${installationId}`, { headers: githubHeaders(jwt) }); const installation = await gh.json() as any; if (!gh.ok || installation.id !== installationId) return c.text("Could not verify GitHub installation", 502); - const bind = await githubRegistry(c).fetch(`https://registry/installations/${installationId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tenantId: session.tenantId, accountLogin: installation.account?.login, accountType: installation.account?.type, state: installation.suspended_at ? "suspended" : "active" }) }); - if (!bind.ok) return c.text("This GitHub installation is already connected to another tenant", 409); - await tenant(c, session.tenantId).fetch("https://tenant/github/installations", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ installationId, accountLogin: installation.account?.login, accountType: installation.account?.type, state: installation.suspended_at ? "suspended" : "active" }) }); + try { await new GitHubRepository(databaseFor(c.env), session.tenantId).save({ installationId, accountLogin: installation.account?.login, accountType: installation.account?.type, state: installation.suspended_at ? "suspended" : "active" }); } + catch (error) { if (error instanceof Error && error.message === "installation_conflict") return c.text("This GitHub installation is already connected to another tenant", 409); throw error; } return c.redirect("/settings"); }); app.put("/api/connections/exe", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/exe", { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveExe(await c.req.json())); }); app.post("/api/connections/exe/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/exe/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testExe(await c.req.json())); }); app.delete("/api/connections/exe/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/exe/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); + const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).remove("exe", c.req.param("id")); return result.conflict ? c.json({ error: "This integration is used by a job." }, 409) : result.deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); }); app.put("/api/connections/amp", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/amp", { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveAmp(await c.req.json())); }); app.post("/api/connections/amp/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch("https://tenant/connections/amp/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); + return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testAmp(await c.req.json())); }); app.delete("/api/connections/amp/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/amp/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); + const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).remove("amp", c.req.param("id")); return result.conflict ? c.json({ error: "This integration is used by a job." }, 409) : result.deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); }); app.post("/webhooks/cloudflare/:tenantId/:jobId", async (c) => { const raw = await c.req.text(); if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); - return tenant(c, c.req.param("tenantId")).fetch(`https://tenant/webhook/cloudflare/${encodeURIComponent(c.req.param("jobId"))}`, { - method: "POST", headers: { "Content-Type": "application/json", "X-Factorize-Timestamp": c.req.header("X-Factorize-Timestamp") ?? "", "X-Factorize-Delivery": c.req.header("X-Factorize-Delivery") ?? "", "X-Factorize-Signature": c.req.header("X-Factorize-Signature") ?? "" }, body: raw, - }); + try { await new WebhookService(databaseFor(c.env), c.env, c.req.param("tenantId")).tail(c.req.param("jobId"), raw, c.req.raw.headers); return c.body(null, 202); } + catch (error) { return c.text(error instanceof Error && error.message === "not_found" ? "Not found" : "Invalid signature", error instanceof Error && error.message === "not_found" ? 404 : 401); } }); app.post("/webhooks/linear", async (c) => { @@ -312,14 +310,14 @@ app.post("/webhooks/linear", async (c) => { if (typeof organizationId !== "string" || !organizationId) return c.text("Missing organization ID", 400); const deliveryId = c.req.header("linear-delivery"); if (!deliveryId) return c.text("Missing delivery ID", 400); - return tenant(c, organizationId).fetch("https://tenant/webhook/linear", { method: "POST", headers: { "Content-Type": "application/json", "Linear-Delivery": `linear:${deliveryId}` }, body: raw }); + await new WebhookService(databaseFor(c.env), c.env, organizationId).linear(event, `linear:${deliveryId}`); return c.body(null, 200); }); app.post("/webhooks/clickup/:tenantId", async (c) => { const raw = await c.req.text(); if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); try { JSON.parse(raw); } catch { return c.text("Invalid JSON", 400); } - return tenant(c, c.req.param("tenantId")).fetch("https://tenant/webhook/clickup", { method: "POST", headers: { "Content-Type": "application/json", "X-Signature": c.req.header("X-Signature") ?? "" }, body: raw }); + try { await new WebhookService(databaseFor(c.env), c.env, c.req.param("tenantId")).clickup(raw, c.req.header("X-Signature") ?? ""); return c.body(null, 200); } catch { return c.text("Invalid signature", 401); } }); app.post("/webhooks/github", async (c) => { @@ -332,17 +330,16 @@ app.post("/webhooks/github", async (c) => { let event: any; try { event = JSON.parse(raw); } catch { return c.text("Invalid JSON", 400); } const installationId = event.installation?.id; if (!Number.isSafeInteger(installationId)) return c.text("Missing installation ID", 400); - const registryResponse = await githubRegistry(c).fetch(`https://registry/installations/${installationId}`); - if (!registryResponse.ok) { console.info(JSON.stringify({ event: "github_webhook_unrouted", installationId, delivery, eventName })); return c.body(null, 202); } - const registration = await registryResponse.json() as any; + const registration = await GitHubRepository.locate(databaseFor(c.env), installationId); + if (!registration) { console.info(JSON.stringify({ event: "github_webhook_unrouted", installationId, delivery, eventName })); return c.body(null, 202); } if (eventName === "installation" && ["deleted", "suspend", "unsuspend"].includes(event.action)) { - const state = event.action === "unsuspend" ? "active" : event.action === "suspend" ? "suspended" : "removed"; - await tenant(c, registration.tenant_id).fetch(`https://tenant/github/installations/${installationId}/state`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state }) }); - await githubRegistry(c).fetch(`https://registry/installations/${installationId}`, event.action === "deleted" ? { method: "DELETE" } : { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state }) }); + const state: "active" | "suspended" = event.action === "unsuspend" ? "active" : "suspended"; + const repository = new GitHubRepository(databaseFor(c.env), registration.tenant_id); + if (event.action === "deleted") await repository.delete(installationId); else await repository.updateState(installationId, state); return c.body(null, 202); } if (registration.state !== "active") return c.body(null, 202); - return tenant(c, registration.tenant_id).fetch("https://tenant/webhook/github", { method: "POST", headers: { "Content-Type": "application/json", "GitHub-Delivery": `github:${delivery}`, "GitHub-Event": eventName }, body: raw }); + await new WebhookService(databaseFor(c.env), c.env, registration.tenant_id).github(event, `github:${delivery}`, eventName); return c.body(null, 202); }); const render = (page: string, nonce: string) => page.replaceAll("