Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion pm-stack/dispatch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,25 @@ where the GitHub App is not installed, the attach is skipped with a
`warnings` entry; the task is still enqueued and `issue_number` is
still returned.

### `GET /v1/tasks/:id` — task status (issue #5555)

Authenticated read of the queue task row dispatch (or a worker)
created: `{task_id, queue, title, status, worker_id, lane_id, repo,
kind, attempts, max_attempts, claimed_at, lease_until, created_at,
updated_at, completed_at, progress, result, last_error, dedupe_key}`.
The packet body and payload are NOT returned — this is a status
surface, not a packet dump; only the payload's `repo`/`kind` are
surfaced, and a task whose packet names a repo is readable only by
callers allowed for that repo (the same gate as the write routes).
Unknown id → `404`; non-numeric id → `400`; unauthenticated → `401`.

### `GET /v1/sessions/:id` — session status (issue #5555)

Authenticated read proxied from the OpenCode server:
`{session_id, title, directory, time}`. A session the OpenCode
server does not know → `404`; an OpenCode-side failure (server down,
auth) → `502`, never conflated with "session gone".

### Why assignment is a direct PATCH

The queue's `claim_repo_task` RPC claims the _next_ task in a queue —
Expand Down Expand Up @@ -159,7 +178,18 @@ Every endpoint except `GET /health` requires `Authorization: Bearer …`:
See `examples/dispatch-workflow.yml`.
- **Static bearer secret**: `DISPATCH_API_TOKEN` (in the laptop's
`~/secrets/dispatch.env`), compared in constant time — the shape a
repo stores as a GitHub Actions secret.
repo stores as a GitHub Actions secret. The vault home for the
value by name is Bitwarden **`pm-dispatch.api-token`** (filed
under issue #5555, verified byte-identical to the service's by
hash): a rotation updates the vault entry and
`~/secrets/dispatch.env` together, and then restarts
`pm-dispatch.service` — the unit reads the env file only at
start, so without a restart the new token is rejected and the
old one stays valid. If `~/secrets/dispatch.env` is lost,
restore the token from this vault item before running
install.sh: a missing file makes the installer generate a fresh
token, desyncing the vault copy and every client (401s) until
they are updated to match.

The caller identity (`{type:"bearer"}` or `{type:"oidc", repository,
actor, workflow_ref}`) is recorded in the task payload.
Expand Down
13 changes: 12 additions & 1 deletion pm-stack/dispatch/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,18 @@
# DELETED legacy project's preserved key is
# `supabase.muse-dev.service-role-key` — never use it; see code#5120.)
# - NOT in sops: DISPATCH_API_TOKEN lives in ~/secrets/dispatch.env
# (mode 600, laptop-only), which the unit also reads. This script
# (mode 600, laptop-only), which the unit also reads. Its by-name
# vault home is Bitwarden `pm-dispatch.api-token` (issue #5555) —
# a rotation updates both places and then restarts
# pm-dispatch.service: the unit reads this file only at start, so
# without a restart the service keeps serving the old token and
# rejects the new one. Recovery: if ~/secrets/dispatch.env is
# lost, restore DISPATCH_API_TOKEN from the Bitwarden item BEFORE
# running this script — when the file is absent the script
# generates a fresh token, which silently desyncs from the vault
# copy and from every client holding the saved token (they get
# 401s) until the vault and the clients are updated to match.
# This script
# ensures that file exists and carries a generated
# DISPATCH_API_TOKEN when one is absent. SUPABASE_URL /
# SUPABASE_SERVICE_ROLE_KEY lines left in that file are stale: the
Expand Down
55 changes: 46 additions & 9 deletions pm-stack/dispatch/src/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import type { ModelRef } from "./validate.ts";

export class OpenCodeError extends Error {
status = 502;
constructor(
message: string,
readonly httpStatus?: number,
) {
super(message);
}
}

export class OpenCodeClient {
Expand Down Expand Up @@ -44,17 +50,30 @@ export class OpenCodeClient {
}

private async api(method: string, path: string, body?: unknown): Promise<unknown> {
const res = await fetch(`${this.baseUrl}${path}`, {
method,
headers: {
Authorization: await this.authHeader(),
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
let res: Response;
try {
res = await fetch(`${this.baseUrl}${path}`, {
method,
headers: {
Authorization: await this.authHeader(),
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (e) {
// A connection failure (server down, refused) is an upstream
// failure, not a caller error: surface it as OpenCodeError so
// routes answer the documented 502 instead of a raw 500.
throw new OpenCodeError(
`opencode ${method} ${path} unreachable: ${e instanceof Error ? e.message : String(e)}`,
);
}
const text = await res.text();
if (!res.ok) {
throw new OpenCodeError(`opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
throw new OpenCodeError(
`opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`,
res.status,
);
}
if (!text.trim()) return null;
let parsed: unknown;
Expand Down Expand Up @@ -94,4 +113,22 @@ export class OpenCodeClient {
async listSessions(): Promise<unknown> {
return this.api("GET", "/api/session");
}

/** Read one session's current state (issue #5555): the raw session
* object from the OpenCode server, or null when the server says the
* session does not exist (HTTP 404). Any other failure (server down,
* auth, non-JSON) stays an OpenCodeError so callers can tell "gone"
* apart from "unknown". */
async getSession(sessionId: string): Promise<unknown> {
try {
return await this.api("GET", `/api/session/${encodeURIComponent(sessionId)}`);
} catch (e) {
// The 404 decision rides on the upstream status recorded by
// api(), never on message text: a 500 whose body happens to
// contain "(HTTP 404)" is a server failure, not a missing
// session.
if (e instanceof OpenCodeError && e.httpStatus === 404) return null;
throw e;
}
}
}
36 changes: 35 additions & 1 deletion pm-stack/dispatch/src/queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,41 @@ export class QueueClient {
const res = await fetch(`${this.baseUrl}/rest/v1/tasks?id=eq.${id}&select=*`, {
headers: this.headers(false),
});
if (!res.ok) return null;
// A failed lookup is not a missing task: returning null here made
// the read route report an existing task as 404 whenever PostgREST
// answered 401/5xx. Null is reserved for a successful empty result.
if (!res.ok) {
throw new QueueError(`task GET ${id} failed (HTTP ${res.status})`, res.status);
}
const rows = (await res.json()) as TaskRow[];
return rows[0] ?? null;
}

/** Session -> task lookup (issue #5555): the dispatch-launched task
* bound to sessionId, or null. Two bindings are checked, live first:
* the current progress.session_id, and - when that binding has been
* cleared - the durable progress.session_cleared.session_id record
* the queue leaves on the task row when it clears a binding on park /
* lease expiry (opencode-claimant migration-0023). The cleared record
* is what keeps the session route repo gate attached to a session
* after its task unbinds: without it, removing the repo from the
* allowlist would silently un-gate a still-live session. Unlike the
* dedupe pre-check below, a lookup failure throws QueueError - this
* lookup backs the repo gate on GET /v1/sessions/:id, and a transient
* PostgREST failure must fail closed (the route answers 502), never
* read as no task, so no gate. */
async findTaskBySessionId(sessionId: string): Promise<TaskRow | null> {
const live = await this.findTaskByProgressField('progress->>session_id', sessionId);
if (live) return live;
return this.findTaskByProgressField('progress->session_cleared->>session_id', sessionId);
}

private async findTaskByProgressField(field: string, sessionId: string): Promise<TaskRow | null> {
const url = this.baseUrl + '/rest/v1/tasks?' + field + '=eq.' + encodeURIComponent(sessionId) + '&select=*&limit=1';
const res = await fetch(url, { headers: this.headers(false) });
if (!res.ok) {
throw new QueueError('task lookup by session failed (HTTP ' + res.status + ')', res.status);
}
const rows = (await res.json()) as TaskRow[];
return rows[0] ?? null;
}
Expand Down
139 changes: 138 additions & 1 deletion pm-stack/dispatch/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
// usually a GitHub issue.
// POST /v1/tasks enqueue-only: a repo-task/v1 packet into the
// Supabase queue, optionally with a GitHub issue.
// GET /v1/tasks/:id authenticated read: that task's status,
// worker and progress (issue #5555) — callers no
// longer cross domains into the queue store.
// GET /v1/sessions/:id authenticated read: that OpenCode session's
// existence/state, proxied from the OpenCode
// server (issue #5555).
// GET /health unauthenticated {ok, version}, aggregator-style.
//
// Everything else requires auth (GitHub Actions OIDC or the static bearer
Expand Down Expand Up @@ -39,7 +45,7 @@ import {
} from "./launch_failure.ts";
import { annotateLaunch } from "./launch_annotations.ts";
import { GitHubClient } from "./github.ts";
import { OpenCodeClient } from "./opencode.ts";
import { OpenCodeClient, OpenCodeError } from "./opencode.ts";

const cfg: Config = loadConfig();
const queue = cfg.supabaseServiceRoleKey ? new QueueClient(cfg.supabaseUrl, cfg.supabaseServiceRoleKey) : null;
Expand Down Expand Up @@ -629,6 +635,127 @@ export async function verifyAttachTarget(args: {
return { outcome: "verified" };
}

// ---------------------------------------------------------------------------
// GET /v1/tasks/:id and GET /v1/sessions/:id — read/status (issue #5555)
// ---------------------------------------------------------------------------

/** The caller-facing view of a queue task row: identity, lifecycle and
* the fields a dispatch caller needs to answer "what happened to task
* N?" — status, worker, progress, result — without the packet body or
* payload internals (the payload can carry caller prompts verbatim;
* the read route is a status surface, not a packet dump). */
export function taskStatusView(row: TaskRow): Record<string, unknown> {
const payload = (row.payload ?? null) as Record<string, unknown> | null;
return {
task_id: row.id,
queue: row.queue,
title: row.title ?? null,
status: row.status,
worker_id: row.worker_id ?? null,
lane_id: row.lane_id ?? null,
repo: payload && typeof payload.repo === "string" ? payload.repo : null,
kind: payload && typeof payload.kind === "string" ? payload.kind : null,
attempts: row.attempts ?? null,
max_attempts: row.max_attempts ?? null,
claimed_at: row.claimed_at ?? null,
lease_until: row.lease_until ?? null,
created_at: row.created_at ?? null,
updated_at: row.updated_at ?? null,
completed_at: row.completed_at ?? null,
progress: row.progress ?? null,
result: row.result ?? null,
last_error: row.last_error ?? null,
dedupe_key: row.dedupe_key,
};
}

/** The caller-facing view of an OpenCode session: existence plus the
* identifying/state fields the server reports. Unknown extra fields
* are not forwarded — the session object is another service's schema
* and this route promises a stable minimal shape. */
export function sessionStatusView(raw: unknown): Record<string, unknown> {
const obj = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
return {
session_id: typeof obj.id === "string" ? obj.id : null,
title: typeof obj.title === "string" ? obj.title : null,
directory:
typeof obj.directory === "string"
? obj.directory
: typeof (obj.location as Record<string, unknown> | undefined)?.directory === "string"
? ((obj.location as Record<string, unknown>).directory as string)
: null,
time: typeof obj.time === "object" && obj.time !== null ? obj.time : null,
};
}

async function handleGetTask(caller: CallerIdentity, idSegment: string): Promise<Response> {
if (!/^\d+$/.test(idSegment)) throw new ValidationError("task id: must be a positive integer");
const id = Number(idSegment);
if (!Number.isSafeInteger(id) || id <= 0) throw new ValidationError("task id: must be a positive integer");
const row = await requireQueue().getTask(id);
if (!row) return json(404, { error: `task ${id} not found` });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const view = taskStatusView(row);
// Same repo gate as the write routes: a task whose packet names a
// repo is only readable by callers allowed for that repo. A denied
// task answers exactly like a missing one — surfacing the auth
// error would confirm the id exists and leak the repo it names to
// an ID probe.
if (typeof view.repo === "string") {
try {
assertCallerRepo(caller, view.repo, cfg.repoAllowlist);
} catch (e) {
if (e instanceof AuthError) return json(404, { error: `task ${id} not found` });
throw e;
}
}
return json(200, view);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

async function handleGetSession(caller: CallerIdentity, idSegment: string): Promise<Response> {
let sessionId: string;
try {
sessionId = decodeURIComponent(idSegment);
} catch {
// A malformed percent-encoding is a bad request, not a 500.
throw new ValidationError("session id: malformed percent-encoding");
}
if (!sessionId.trim()) throw new ValidationError("session id: required");
let raw: unknown;
try {
raw = await opencode.getSession(sessionId);
} catch (e) {
if (e instanceof OpenCodeError) return json(e.status, { error: e.message });
throw e;
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
if (raw === null || raw === undefined) return json(404, { error: `session ${sessionId} not found` });
// Repo gate, the task read's rule applied to sessions: a
// dispatch-launched session is bound to the queue task that
// launched it - by the live progress.session_id binding, or by
// the durable progress.session_cleared record the queue keeps
// after a park/lease-expiry unbinds it - and that task's repo must be
// in the current allowlist for the session's status to be
// readable — removing a repo from the allowlist closes its
// sessions too. A denied session answers like a missing one: no
// title, no directory, no repo name. Sessions with no dispatch
// task carry no repo association in any record; a queue-less
// deployment (queue === null) can have no dispatch sessions at
// all, so the gate applies exactly when the record is reachable,
// and a failed lookup fails closed via QueueError (502).
if (queue) {
const task = await queue.findTaskBySessionId(sessionId);
const repo = task ? taskStatusView(task).repo : null;
if (typeof repo === "string") {
Comment thread
dezren39 marked this conversation as resolved.
Resolved
try {
assertCallerRepo(caller, repo, cfg.repoAllowlist);
} catch (e) {
if (e instanceof AuthError) return json(404, { error: `session ${sessionId} not found` });
throw e;
}
}
}
return json(200, sessionStatusView(raw));
}

// ---------------------------------------------------------------------------
// Routing
// ---------------------------------------------------------------------------
Expand All @@ -650,6 +777,16 @@ export async function handler(req: Request): Promise<Response> {
});
return path === "/v1/sessions" ? await handleSessions(req, caller) : await handleTasks(req, caller);
}
const taskMatch = path.match(/^\/v1\/tasks\/([^/]+)$/);
const sessionMatch = path.match(/^\/v1\/sessions\/([^/]+)$/);
if (req.method === "GET" && (taskMatch || sessionMatch)) {
const caller = await authenticate(req, {
apiToken: cfg.apiToken,
oidcAudience: cfg.oidcAudience,
allowlist: cfg.repoAllowlist,
});
return taskMatch ? await handleGetTask(caller, taskMatch[1]) : await handleGetSession(caller, sessionMatch![1]);
}
return json(404, { error: "not found" });
} catch (e) {
if (e instanceof AuthError) return json(401, { error: e.message });
Expand Down
8 changes: 4 additions & 4 deletions pm-stack/dispatch/test/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,15 @@ describe("JWKS body shape (#7565)", () => {
resetJwksCacheForTests();
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = async () => {
globalThis.fetch = (async () => {
calls++;
return {
ok: true,
json: async () => {
throw new SyntaxError("Unexpected token < in JSON");
},
} as Response;
};
} as unknown as Response;
}) as unknown as typeof fetch;
try {
await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError);
await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError);
Expand All @@ -249,7 +249,7 @@ describe("JWKS body shape (#7565)", () => {
test("fetchGithubJwks rejects a wrong-shape 200 body as AuthError", async () => {
resetJwksCacheForTests();
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => ({ ok: true, json: async () => ({}) }) as Response;
globalThis.fetch = (async () => ({ ok: true, json: async () => ({}) }) as unknown as Response) as unknown as typeof fetch;
try {
await expect(fetchGithubJwks()).rejects.toBeInstanceOf(AuthError);
} finally {
Expand Down
Loading
Loading