An open-source, faster Devin alternative
TypeScript
Work API: routes, work:read and work:write, composition and the open list's ETag (work tracking 3.10)
Igor Zalutski via Computer7e52c29e2db7
diff --git a/docs/api/overview.mdx b/docs/api/overview.mdxindex 03d7cca8..741dd5c6 100644--- a/docs/api/overview.mdx+++ b/docs/api/overview.mdx@@ -53,6 +53,10 @@ A credential without a scope list has every scope.| `sessions:write` | `turns.send`, `turns.cancel`, `sessions.update`, `sessions.interrupt`, `sessions.compact`, `sessions.suspend`, `sessions.resume`, file upload || `asks:answer` | `asks.answer`, `asks.dismiss` || `terminals` | `terminals.open`, `terminals.resize`, `terminals.eof`, `terminals.close` |+| `work:read` | `GET /work/repository`, `GET /work/items`, `GET /work/items/{number}`, `GET /work/items/{number}/history` |+| `work:write` | `PUT /work/repository` |++`work:read` and `work:write` are granted only to a key that names them, never by a missing scope list or `*`. A session's own key is refused on `PUT /work/repository`.A scope may also name sessions (`sessionIds`), be read-only (`readOnly`) and expire (`until`).diff --git a/services/managed-agents/src/computer/api-http.ts b/services/managed-agents/src/computer/api-http.tsindex a0ebe3b0..b50ad35a 100644--- a/services/managed-agents/src/computer/api-http.ts+++ b/services/managed-agents/src/computer/api-http.ts@@ -26,6 +26,8 @@ import { isSessionId, memberId } from "./session-ids.js";import type { ApiCaller, ApiOp, ApiReply, WriteMethod } from "./sessions-api.js";import type { SecretsApiOp } from "./secrets-store.js";import type { WorkContextOp } from "./work/briefs.js";+import { type WorkRoute, workApi } from "./work/api.js";+import type { WorkIndexRpc } from "./work/index-contract.js";import { gatewayTelemetry } from "./telemetry/gateway.js";/** What api-http needs of the Computer DO stub. */@@ -63,6 +65,15 @@ export function matchApiRoute(method: string, suffix: string): Route | null {if (p[0] === "me" && p[1] === "secrets" && p.length === 3 && (method === "PUT" || method === "DELETE")) return { op: "secrets" };// The same for every session, so the new-session screen can read it before there is one.if (is("GET", 1) && p[0] === "capabilities") return { op: "capabilities" };+ // The Work API (work tracking 3.10): the organization's items, read from its knowledge repository.+ if (p[0] === "work") {+ if (p[1] === "repository" && p.length === 2) return method === "GET" ? { op: "work.repository.get" } : method === "PUT" ? { op: "work.repository.put" } : null;+ if (p[1] !== "items") return null;+ if (is("GET", 2)) return { op: "work.items" };+ if (is("GET", 3)) return { op: "work.item", sub: p[2] };+ if (is("GET", 4) && p[3] === "history") return { op: "work.history", sub: p[2] };+ return null;+ }if (p[0] !== "sessions") return null;if (p.length === 1) return method === "GET" ? { op: "list" } : method === "POST" ? { op: "create" } : null;const sessionId = p[1]!;@@ -98,6 +109,8 @@ function scopeOf(op: string): ApiScope | null {if (op === "asks.answer" || op === "asks.dismiss") return "asks:answer";if (op === "secrets" || op === "secrets.put" || op === "secrets.delete") return "secrets:write";if (op === "secrets.events") return "sessions:read";+ if (op === "work.repository.put") return "work:write";+ if (op.startsWith("work.")) return "work:read";if (op === "list" || op === "get" || op === "capabilities" || op.endsWith(".list") || op.endsWith(".get")) return "sessions:read";return "sessions:write";}@@ -133,7 +146,7 @@ class Reply {"x-request-id": this.requestId,"server-timing": `blue;dur=${(performance.now() - this.started).toFixed(1)}`,});- return new Response(status === 204 ? null : JSON.stringify(body), { status, headers });+ return new Response(status === 204 || status === 304 ? null : JSON.stringify(body), { status, headers });}error(status: number, code: string, message: string, extra: Record<string, unknown> = {}): Response {@@ -245,6 +258,7 @@ export function routeFamily(op: string): string {if (op.startsWith("subagents.")) return "subagents";if (op === "ticket") return "tickets";if (op === "secrets" || op.startsWith("secrets.")) return "secrets";+ if (op.startsWith("work.")) return "work";return "other";}@@ -253,6 +267,7 @@ const OPS = new Set(["sessions.interrupt", "sessions.compact", "sessions.suspend", "sessions.resume","turns.send", "turns.list", "turns.get", "turns.cancel", "events.list","asks.list", "asks.get", "asks.answer", "asks.dismiss", "subagents.list", "subagents.get", "subagents.stop",+ "work.repository.get", "work.repository.put", "work.items", "work.item", "work.history",]);/** The request's one `httpapi.request`; never throws, never awaited. */@@ -352,6 +367,10 @@ async function routeApi(if ((route.op === "secrets" || route.op.startsWith("secrets.")) && identity.principal === COMPUTER_PRINCIPAL) {return out.error(403, "forbidden", "Sessions cannot read or set secrets over this API.", { reason: "computer_principal" });}+ // Only people change the Work setting (3.9, 3.10): a session's own key is refused on writes.+ if (route.op === "work.repository.put" && identity.principal === COMPUTER_PRINCIPAL) {+ return out.error(403, "forbidden", "Sessions cannot change Work over this API.", { reason: "computer_principal" });+ }const scope = scopeOf(route.op);if (scope && !caller.scopes.includes(scope)) {return out.error(403, "forbidden", `This key does not have the ${scope} scope.`, { reason: "missing_scope", scope });@@ -362,6 +381,25 @@ async function routeApi(const query = url.searchParams;const call = (op: ApiOp | SecretsApiOp) => computer.computerApi(accountId, caller, op).then((reply) => out.of(reply));+ if (route.op.startsWith("work.")) {+ let body: unknown;+ if (request.method === "PUT") {+ const parsed = await bodyOf(request);+ if ("error" in parsed) return out.error(...parsed.error);+ body = parsed.value;+ }+ const index = env.WORK_INDEX ? (env.WORK_INDEX.getByName(accountId) as unknown as WorkIndexRpc) : null;+ const reply = await workApi(+ { accountId, caller, index, context: (op) => computer.computerApi(accountId, caller, op) },+ route as WorkRoute,+ query,+ body,+ request.headers.get("if-none-match"),+ );+ const response = out.of(reply);+ if (reply.etag) response.headers.set("etag", reply.etag);+ return response;+ }if (route.op === "secrets") return out.error(409, "feature_unavailable", "Only organization secrets can be set over this API for now.", { feature: "secrets" });if (route.op === "secrets.list") return call({ op: "secrets.list" });if (route.op.startsWith("secrets.")) {diff --git a/services/managed-agents/src/computer/api-types.ts b/services/managed-agents/src/computer/api-types.tsindex f44d5357..17e7c8cb 100644--- a/services/managed-agents/src/computer/api-types.ts+++ b/services/managed-agents/src/computer/api-types.ts@@ -225,5 +225,5 @@ export interface ApiErrorBody {}/** The API key scopes (authentication.mdx#scopes). */-export const API_SCOPES = ["sessions:read", "sessions:write", "asks:answer", "secrets:write", "terminals"] as const;+export const API_SCOPES = ["sessions:read", "sessions:write", "asks:answer", "secrets:write", "terminals", "work:read", "work:write"] as const;export type ApiScope = (typeof API_SCOPES)[number];diff --git a/services/managed-agents/src/computer/keys.ts b/services/managed-agents/src/computer/keys.tsindex 7b41b04b..d3ba2f6f 100644--- a/services/managed-agents/src/computer/keys.ts+++ b/services/managed-agents/src/computer/keys.ts@@ -22,12 +22,15 @@ export interface WireKeysWriter {delete(key: string): Promise<void>;}-/** Scopes a wildcard never grants: the key must name them (work 095). */-const NAMED_ONLY: readonly ApiScope[] = ["secrets:write"];+/**+ * Scopes a wildcard never grants: the key must name them (work 095). The Work scopes too (work+ * tracking 3.10): a key made before they existed must not silently read an organization's documents.+ */+const NAMED_ONLY: readonly ApiScope[] = ["secrets:write", "work:read", "work:write"];/*** A key's API scopes. Keys made before scopes existed carry `sandbox:*` (the edge hardcodes it),- * and `*` or no scopes at all mean the same: every scope except `secrets:write`, which a key gets+ * and `*` or no scopes at all mean the same: every scope except NAMED_ONLY, which a key gets* only by naming it (work 095: the one-hour keys sessions mint are `sandbox:*`, and a session must* not be able to set a secret). Otherwise the scopes the API knows.*/diff --git a/services/managed-agents/src/computer/telemetry/catalog.ts b/services/managed-agents/src/computer/telemetry/catalog.tsindex 2cc4c1f7..9f0a8c48 100644--- a/services/managed-agents/src/computer/telemetry/catalog.ts+++ b/services/managed-agents/src/computer/telemetry/catalog.ts@@ -279,7 +279,7 @@ export const CATALOG = {// One per revoke (Q9): known to this computer, and the host told (protocol v4 `revoked`).'keys.revoked': gateway('key_id', 'known', 'host_told'),// One per blue /v1/computer API request (Q3 delivery, Q4): route (closed: sessions turns asks subagents control- // events workspace secrets tickets other), op (the API op), duration_ms = the request's time in blue; do_ms/log_ms:+ // events workspace secrets tickets work other), op (the API op), duration_ms = the request's time in blue; do_ms/log_ms:// awaiting the Computer DO / the SessionLog; wait_ms: a long-poll's asked wait; events/empty: events.list's page;// oldest_age_ms/newest_age_ms: now − createdAt of its first/last event (delivery freshness).'httpapi.request': gateway(diff --git a/services/managed-agents/src/computer/work/api.ts b/services/managed-agents/src/computer/work/api.tsnew file mode 100644index 00000000..d35f792d--- /dev/null+++ b/services/managed-agents/src/computer/work/api.ts@@ -0,0 +1,289 @@+// The Work API (work tracking tech design 3.10), in the stateless Worker: validation, then the+// Work index's items composed with the Computer object's `work.context` for the caller. Neither+// object calls the other; this is the only place their answers meet.+//+// api-http.ts matches the routes, checks scopes and turns the `WorkReply` into a response.++import type { ApiCaller, ApiReply } from "../sessions-api.js";+import type { SessionBrief, WorkContext, WorkContextOp } from "./briefs.js";+import type { IndexedItem, ItemsResult, Revision, WorkIndexRpc } from "./index-contract.js";++export interface Person {+ email: string;+ name: string | null;+ id: string | null;+}++export interface ItemAttention {+ state: "needs_you" | "waiting_on" | "working";+ name: string | null;+ since: string;+}++/** `Item` of 3.10. */+export interface Item {+ number: number;+ stage: "open" | "closed";+ path: string;+ url: string;+ title: string;+ stateLine: string | null;+ tags: string[];+ owner: Person | null;+ author: Person | null;+ mine: boolean;+ left: number | null;+ readyToClose: boolean;+ warnings: string[];+ pullRequests: IndexedItem["pullRequests"];+ attention: ItemAttention | null;+ /** 3.10's `{id, title, ownerName}`, plus the session's lifecycle `status` (the board shows it). */+ sessions: { id: string; title: string | null; ownerName: string | null; status: SessionBrief["status"] }[];+ unpublished: boolean;+ updatedAt: string;+ createdAt: string | null;+ closedAt: string | null;+ closedBy: string | null;+}++export type WorkRouteOp = "work.repository.get" | "work.repository.put" | "work.items" | "work.item" | "work.history";++export interface WorkRoute {+ op: WorkRouteOp;+ /** The item number's path segment, unvalidated. */+ sub?: string;+}++/** An ApiReply, with the open list's ETag; status 304 has no body. */+export type WorkReply = ApiReply & { etag?: string };++export interface WorkDeps {+ accountId: string;+ caller: ApiCaller;+ /** The Work index, or null when the binding is missing. */+ index: WorkIndexRpc | null;+ /** The Computer object's `work.context`. */+ context(op: WorkContextOp): Promise<ApiReply>;+}++/** The query parameters each route takes; any other is refused. */+const PARAMS: Record<WorkRouteOp, readonly string[]> = {+ "work.repository.get": [],+ "work.repository.put": [],+ "work.items": ["stage", "cursor", "limit"],+ "work.item": [],+ "work.history": ["cursor"],+};++const CLOSED_LIMIT_MAX = 100;+const NUMBER = /^[1-9]\d{0,8}$/;+const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;+const REPO_NAME = /^[A-Za-z0-9._-]{1,100}$/;+const BRANCH = /^[^\s~^:?*[\\]{1,255}$/;+const UNAVAILABLE: WorkReply = { status: 503, error: { code: "unavailable", message: "Work is unavailable. Try again shortly.", retryAfterMs: 5_000 } };++const invalid = (message: string, field: string): WorkReply => ({ status: 400, error: { code: "invalid_request", message, field } });+const notFound = (): WorkReply => ({ status: 404, error: { code: "item_not_found", message: "No such item." } });++/** One Work API request: validated, sent to the index, composed. Never throws for a refusal. */+export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearchParams, body: unknown, ifNoneMatch: string | null): Promise<WorkReply> {+ for (const name of new Set(query.keys())) {+ if (!PARAMS[route.op].includes(name)) return invalid(`Unknown query parameter ${name}.`, name);+ }+ const index = deps.index;+ if (!index) return UNAVAILABLE;++ switch (route.op) {+ case "work.repository.get":+ return { status: 200, body: { repository: await index.repository(deps.accountId) } };++ case "work.repository.put": {+ const choice = repositoryChoice(body);+ if ("error" in choice) return choice.error;+ const by = { member: deps.caller.member, name: deps.caller.name, email: deps.caller.email };+ const result = await index.setRepository(deps.accountId, choice.value, by);+ if (!result.ok) {+ const { status, code, message, ok: _ok, ...extra } = result;+ return { status, error: { code, message, ...extra } };+ }+ return { status: 200, body: { repository: result.value } };+ }++ case "work.items": {+ const stage = query.get("stage");+ if (stage !== "open" && stage !== "closed") return invalid("stage is open or closed.", "stage");+ if (stage === "open") {+ for (const name of ["cursor", "limit"]) if (query.has(name)) return invalid(`${name} is only for stage=closed; the open list is whole.`, name);+ }+ const rawLimit = query.get("limit");+ if (rawLimit !== null && (!/^\d{1,3}$/.test(rawLimit) || Number(rawLimit) < 1 || Number(rawLimit) > CLOSED_LIMIT_MAX)) {+ return invalid(`limit is 1 to ${CLOSED_LIMIT_MAX}.`, "limit");+ }+ const cursor = query.get("cursor");+ const result: ItemsResult = await index.items(deps.accountId, {+ stage,+ ...(cursor !== null ? { cursor } : {}),+ ...(rawLimit !== null ? { limit: Number(rawLimit) } : {}),+ });+ if (!result.ok) return { status: 400, error: { code: "invalid_cursor", message: "The cursor is not valid for this list." } };+ const composed = await compose(deps, result.items, result.asOf);+ if ("status" in composed) return composed;+ if (stage === "closed") return { status: 200, body: { items: composed.items, nextCursor: result.nextCursor } };+ const page = { repository: result.repository, head: result.head, asOf: result.asOf, building: result.building, items: composed.items };+ const etag = await etagOf(page);+ if (ifNoneMatch !== null && matches(ifNoneMatch, etag)) return { status: 304, etag };+ return { status: 200, body: page, etag };+ }++ case "work.item": {+ if (!NUMBER.test(route.sub ?? "")) return notFound();+ const result = await index.item(deps.accountId, Number(route.sub));+ if (!result.item) return notFound();+ // A closed item's body is read on first view; GitHub could not be reached.+ if (result.body === null) return UNAVAILABLE;+ const composed = await compose(deps, [result.item], result.asOf);+ if ("status" in composed) return composed;+ return { status: 200, body: { item: composed.items[0]!, body: result.body } };+ }++ case "work.history": {+ if (!NUMBER.test(route.sub ?? "")) return notFound();+ const cursor = query.get("cursor");+ const result = await index.history(deps.accountId, Number(route.sub), cursor ?? undefined);+ if (!result.ok) {+ if (result.error === "item_not_found") return notFound();+ if (result.error === "invalid_cursor") return { status: 400, error: { code: "invalid_cursor", message: "The cursor is not valid for this list." } };+ return { ...UNAVAILABLE, error: { ...UNAVAILABLE.error!, retryAfterMs: result.retryAfterMs ?? 5_000 } };+ }+ const ids = [...new Set(result.revisions.map((r) => r.sessionId).filter((id): id is string => id !== null))];+ const context = ids.length ? await workContext(deps, ids, []) : { sessions: {}, people: {}, callerEmails: [] };+ if ("status" in context) return context;+ // A trailer names a session id or a Slack session's key: shown as the session's id, and only+ // when the caller may see it.+ const revisions: Revision[] = result.revisions.map((r) => ({ ...r, sessionId: r.sessionId ? (context.sessions[r.sessionId]?.id ?? null) : null }));+ return { status: 200, body: { revisions, nextCursor: result.nextCursor } };+ }+ }+}++function repositoryChoice(body: unknown): { value: { installationId: string; owner: string; name: string; branch?: string } } | { error: WorkReply } {+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: invalid("The body must be a JSON object.", "") };+ const input = body as Record<string, unknown>;+ for (const key of Object.keys(input)) {+ if (!["installationId", "owner", "name", "branch"].includes(key)) return { error: invalid(`Unknown field ${key}.`, key) };+ }+ const { installationId, owner, name, branch } = input;+ const installation =+ typeof installationId === "number" && Number.isSafeInteger(installationId) && installationId > 0+ ? String(installationId)+ : typeof installationId === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(installationId)+ ? installationId+ : null;+ if (installation === null) return { error: invalid("installationId is the GitHub installation's id.", "installationId") };+ if (typeof owner !== "string" || !OWNER.test(owner)) return { error: invalid("owner is a GitHub account login.", "owner") };+ if (typeof name !== "string" || !REPO_NAME.test(name) || name === "." || name === "..") return { error: invalid("name is a GitHub repository name.", "name") };+ if (branch !== undefined && branch !== null && (typeof branch !== "string" || !BRANCH.test(branch))) return { error: invalid("branch is a branch name.", "branch") };+ return { value: { installationId: installation, owner, name, ...(typeof branch === "string" ? { branch } : {}) } };+}++async function workContext(deps: WorkDeps, sessionIds: string[], emails: string[]): Promise<WorkContext | WorkReply> {+ const reply = await deps.context({ op: "work.context", sessionIds, emails });+ if (reply.error) return reply;+ return reply.body as WorkContext;+}++/** The index's items joined with the caller's sessions and the members behind emails. */+async function compose(deps: WorkDeps, items: IndexedItem[], asOf: string | null): Promise<{ items: Item[] } | WorkReply> {+ const sessionIds = [...new Set(items.flatMap((i) => i.sessionIds))];+ const emails = [...new Set(items.flatMap((i) => [i.owner, i.author?.email ?? null]).filter((e): e is string => !!e).map((e) => e.toLowerCase()))];+ const context = items.length ? await workContext(deps, sessionIds, emails) : { sessions: {}, people: {}, callerEmails: [] };+ if ("status" in context) return context;+ const mine = new Set(context.callerEmails.map((e) => e.toLowerCase()));+ const person = (email: string, fallbackName: string | null = null): Person => {+ const known = context.people[email.toLowerCase()];+ return { email, name: known?.name ?? fallbackName, id: known?.id ?? null };+ };+ return {+ items: items.map((i): Item => {+ const briefs = linkedBriefs(i.sessionIds, context.sessions);+ return {+ number: i.number,+ stage: i.stage,+ path: i.path,+ url: i.url,+ title: i.title,+ stateLine: i.stateLine,+ tags: i.tags,+ owner: i.owner ? person(i.owner) : null,+ author: i.author?.email ? person(i.author.email, i.author.name) : null,+ mine: i.owner !== null && mine.has(i.owner.toLowerCase()),+ left: i.left,+ readyToClose: i.readyToClose,+ warnings: i.warnings,+ pullRequests: i.pullRequests,+ attention: itemAttention(briefs, deps.caller.member),+ sessions: briefs.map((b) => ({ id: b.id, title: b.title, ownerName: b.ownerName, status: b.status })),+ unpublished: false,+ updatedAt: i.updatedAt ?? i.closedAt ?? i.createdAt ?? asOf ?? new Date(0).toISOString(),+ createdAt: i.createdAt,+ closedAt: i.closedAt,+ closedBy: i.closedBy,+ };+ }),+ };+}++/** The item's linked sessions the caller may see, once each, in the index's order (most recent first). */+function linkedBriefs(ids: string[], sessions: Record<string, SessionBrief>): SessionBrief[] {+ const out = new Map<string, SessionBrief>();+ for (const id of ids) {+ const brief = sessions[id];+ if (brief && !out.has(brief.id)) out.set(brief.id, brief);+ }+ return [...out.values()];+}++/**+ * The item's attention for the caller, the first that holds over its visible sessions (3.10):+ * `needs_you` (one of the caller's sessions has an open ask), `waiting_on` (someone else's has),+ * `working` (one is starting or running). Until the session's `attention` field (3.7) lands, an+ * open ask is the only thing that needs a person.+ */+export function itemAttention(briefs: SessionBrief[], member: string): ItemAttention | null {+ const oldest = (list: SessionBrief[], at: (b: SessionBrief) => string) => list.reduce((a, b) => (at(b) < at(a) ? b : a));+ const asking = briefs.filter((b) => b.openAskAt !== null);+ const mineAsking = asking.filter((b) => b.ownerId === member);+ if (mineAsking.length) {+ const b = oldest(mineAsking, (x) => x.openAskAt!);+ return { state: "needs_you", name: b.ownerName, since: b.openAskAt! };+ }+ if (asking.length) {+ const b = oldest(asking, (x) => x.openAskAt!);+ return { state: "waiting_on", name: b.ownerName, since: b.openAskAt! };+ }+ const working = briefs.filter((b) => b.status === "running" || b.status === "starting");+ if (working.length) {+ const b = working.reduce((a, x) => (x.lastActiveAt > a.lastActiveAt ? x : a));+ return { state: "working", name: b.ownerName, since: b.lastActiveAt };+ }+ return null;+}++/**+ * The open list's ETag: the head, and a stamp of everything else the page says except `asOf`+ * (attention, sessions, people and pull request states change without a commit).+ */+export async function etagOf(page: { head: string | null; asOf: string | null }): Promise<string> {+ const { asOf: _asOf, ...rest } = page;+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(rest)));+ const stamp = [...new Uint8Array(digest).slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");+ return `"${page.head ?? "none"}-${stamp}"`;+}++function matches(ifNoneMatch: string, etag: string): boolean {+ return ifNoneMatch.split(",").some((tag) => {+ const t = tag.trim().replace(/^W\//, "");+ return t === "*" || t === etag;+ });+}+diff --git a/services/managed-agents/test/work-api.test.ts b/services/managed-agents/test/work-api.test.tsnew file mode 100644index 00000000..6bb2a2fe--- /dev/null+++ b/services/managed-agents/test/work-api.test.ts@@ -0,0 +1,290 @@+import { describe, expect, it, vi } from "vitest";++import { routeComputerApi, type ComputerApiStub } from "../src/computer/api-http.js";+import type { Session } from "../src/computer/api-types.js";+import type { ApiCaller, ApiRow } from "../src/computer/sessions-api.js";+import { itemAttention } from "../src/computer/work/api.js";+import { type SessionBrief, type WorkContextOp, workContext } from "../src/computer/work/briefs.js";+import type { TokenMinter } from "../src/computer/work/github.js";+import { WorkIndex } from "../src/computer/work/index.js";+import type { WorkIndexRpc } from "../src/computer/work/index-contract.js";+import { memberId } from "../src/computer/session-ids.js";+import type { RequestIdentity } from "../src/edge/auth.js";+import { sqlStorage } from "./fixtures/computer-sql.js";+import { FakeRepo } from "./fixtures/fake-github-repo.js";++/** Work tracking 3.10: the Work API's routes, scopes and composition in the Worker. */++const ORG = "acct_1";+const ME = await memberId("user_me");+const BO = await memberId("user_bo");+const SID = { mine: "cs_0000000000000001", bos: "cs_0000000000000002", slack: "cs_0000000000000003", private: "cs_0000000000000004", idle: "cs_0000000000000005" };++const person = { kind: "user", accountId: ORG, organizationId: ORG, userId: "user_me", role: "member", userName: "Me", userEmail: "[email protected]" } as RequestIdentity;+const key = { id: "key_1", hash: "a".repeat(64), name: "laptop", kind: "user" as const, expiresAt: null, createdAt: null };+const withKey = (scopes: string[], extra: Partial<RequestIdentity> = {}) => ({ ...person, apiKey: { ...key, scopes }, ...extra }) as RequestIdentity;++interface FakeSession {+ row: Partial<ApiRow> & { key: string; sessionId: string; originType: string; ownerUserId: string | null; ownerName: string | null };+ status: Session["status"];+ asks?: { status: string; createdAt: string }[];+ lastActiveAt?: string;+}++/** The Computer object's side: sessions and people in SQL, `work.context` as durable-object.ts dispatches it. */+function computer(sessions: FakeSession[]) {+ const sql = sqlStorage();+ sql.exec(`CREATE TABLE sessions (runner_key TEXT, session_id TEXT, owner_id TEXT, owner_user_id TEXT, owner_name TEXT, owner_email TEXT, updated_at INTEGER);+ CREATE TABLE people (slack_user_id TEXT PRIMARY KEY, dir TEXT, git_name TEXT, git_email TEXT, updated_at INTEGER);`);+ for (const s of sessions) {+ sql.exec("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, 1)", s.row.key, s.row.sessionId, s.row.ownerId ?? null, s.row.ownerUserId, s.row.ownerName, s.row.ownerEmail ?? null);+ }+ sql.exec("INSERT INTO people VALUES ('U_ME', 'me', 'Me', '[email protected]', 1)");+ sql.exec("INSERT INTO people VALUES ('U_CY', 'cy', 'Cy Git', '[email protected]', 1)");+ const find = (id: string) => sessions.find((s) => s.row.sessionId === id);+ const api = {+ row: (id: string) => find(id)?.row as ApiRow | undefined,+ rowByKey: (k: string) => sessions.find((s) => s.row.key === k)?.row as ApiRow | undefined,+ visible: (caller: ApiCaller, id: string) => {+ const s = find(id);+ return s && !(s.row.originType === "slack" && s.row.ownerUserId !== caller.member) ? (s.row as ApiRow) : undefined;+ },+ compose: (row: ApiRow) => {+ const s = find(row.sessionId)!;+ return { id: row.sessionId, title: `Session ${row.sessionId.slice(-1)}`, status: s.status, asks: s.asks ?? [], lastActiveAt: s.lastActiveAt ?? "2026-11-19T09:00:00.000Z" } as unknown as Session;+ },+ };+ const ops: WorkContextOp[] = [];+ const stub: ComputerApiStub = {+ computerApi: vi.fn(async (_account, caller, op) => {+ if (op.op !== "work.context") throw new Error(`unexpected ${op.op}`);+ ops.push(op as WorkContextOp);+ return workContext({ sql, api }, caller, op as WorkContextOp);+ }),+ };+ return { stub, ops, sql };+}++/** A Work index over a fake GitHub, as the binding answers it. */+async function workIndex(repo: FakeRepo) {+ const pending: Promise<unknown>[] = [];+ const account: TokenMinter = { mintGitHubInstallationToken: async () => ({ outcome: "minted", token: "ghs_test", expiresAt: "2099-01-01T00:00:00Z" }) };+ const index = new WorkIndex({ sql: sqlStorage(), transaction: (fn) => fn(), account: () => account, arm: async () => {}, waitUntil: (p) => void pending.push(p), fetch: repo.fetch });+ const rpc: WorkIndexRpc = {+ repository: (a) => index.getRepository(a),+ setRepository: (a, c, by) => index.setRepository(a, c, by),+ items: (a, q) => index.items(a, q),+ item: (a, n) => index.item(a, n),+ history: (a, n, c) => index.history(a, n, c),+ poke: (a) => index.poke(a),+ };+ const settle = async () => {+ while (pending.length) await Promise.allSettled(pending.splice(0));+ };+ return { rpc, settle, env: { WORK_INDEX: { getByName: () => rpc } } };+}++function call(env: unknown, stub: ComputerApiStub, identity: RequestIdentity, method: string, path: string, init: { body?: string; headers?: Record<string, string> } = {}) {+ const request = new Request(`https://blue.test/v1/computer${path}`, { method, ...init });+ return routeComputerApi(request, env as never, identity, ORG, stub, new URL(request.url).pathname.slice("/v1/computer".length));+}+const json = async (res: Response) => (await res.json()) as Record<string, any>;++const doc = (n: number, title: string, owner?: string, extra = "") =>+ `${owner ? `---\nowner: ${owner}\n---\n` : ""}# ${n}. ${title}\n\nState of ${title}.\n${extra}`;++/** A repository with items linked to sessions of every kind, connected and built. */+async function board() {+ const repo = new FakeRepo({ "work/1-mine.md": doc(1, "Mine", "[email protected]"), "work/2-bos.md": doc(2, "Bo's", "[email protected]"), "done/3-old.md": doc(3, "Old") });+ const w = await workIndex(repo);+ const c = computer([+ { row: { key: "k1", sessionId: SID.mine, originType: "api", ownerUserId: ME, ownerName: "Me", ownerId: "U_ME", ownerEmail: "[email protected]" }, status: "waiting", asks: [{ status: "open", createdAt: "2026-11-19T08:00:00.000Z" }] },+ { row: { key: "k2", sessionId: SID.bos, originType: "api", ownerUserId: BO, ownerName: "Bo", ownerEmail: "[email protected]" }, status: "running", asks: [{ status: "open", createdAt: "2026-11-19T07:00:00.000Z" }] },+ // My Slack session, named in the trailer by its key.+ { row: { key: "T1:C1:111", sessionId: SID.slack, originType: "slack", ownerUserId: ME, ownerName: "Me" }, status: "running", lastActiveAt: "2026-11-19T09:30:00.000Z" },+ // Bo's Slack session: private to Bo.+ { row: { key: "T1:C2:222", sessionId: SID.private, originType: "slack", ownerUserId: BO, ownerName: "Bo" }, status: "waiting", asks: [{ status: "open", createdAt: "2026-11-19T06:00:00.000Z" }] },+ { row: { key: "k5", sessionId: SID.idle, originType: "api", ownerUserId: BO, ownerName: "Bo" }, status: "idle" },+ ]);+ const put = await call(w.env, c.stub, person, "PUT", "/work/repository", { body: JSON.stringify({ installationId: 12, owner: "acme", name: "knowledge" }) });+ expect(put.status).toBe(200);+ await w.settle();+ // Commits after the build, which the index advances over and links.+ const commits: [Record<string, string>, string, { name: string; email: string }?][] = [+ [{ "work/1-mine.md": doc(1, "Mine", "[email protected]", "more") }, `Update 1\n\nSession: ${SID.mine}\nSession: ${SID.bos}`],+ [{ "work/2-bos.md": doc(2, "Bo's", "[email protected]", "more") }, `Update 2\n\nSession: T1:C1:111\nSession: ${SID.private}`],+ [{ "work/4-new.md": doc(4, "New", "[email protected]") }, `Add 4\n\nSession: ${SID.idle}`, { name: "Cy", email: "[email protected]" }],+ ];+ for (const [changes, message, author] of commits) {+ repo.commit(changes, message, author);+ await w.rpc.poke(ORG);+ await w.settle();+ }+ return { repo, w, c };+}++describe("Work API scopes", () => {+ const env = { WORK_INDEX: { getByName: () => ({ repository: async () => null, setRepository: async () => ({ ok: true, value: null }) }) } };+ const stub: ComputerApiStub = { computerApi: vi.fn() };+ const status = async (identity: RequestIdentity, method = "GET", path = "/work/repository", body?: string) => {+ const res = await call(env, stub, identity, method, path, body ? { body } : {});+ return { status: res.status, error: res.status >= 400 ? (await json(res)).error : undefined };+ };+ const choice = JSON.stringify({ installationId: "inst_1", owner: "acme", name: "knowledge" });++ it("needs work:read to read and work:write to change; sessions:read and wildcards grant neither", async () => {+ expect(await status(withKey(["sessions:read"]))).toMatchObject({ status: 403, error: { reason: "missing_scope", scope: "work:read" } });+ expect(await status(withKey(["sandbox:*"]))).toMatchObject({ status: 403, error: { scope: "work:read" } });+ expect((await status(withKey(["work:read"]))).status).toBe(200);+ expect(await status(withKey(["work:read"]), "PUT", "/work/repository", choice)).toMatchObject({ status: 403, error: { scope: "work:write" } });+ expect((await status(withKey(["work:write"]), "PUT", "/work/repository", choice)).status).toBe(200);+ });++ it("lets the dashboard read and write", async () => {+ expect((await status(person)).status).toBe(200);+ expect((await status(person, "PUT", "/work/repository", choice)).status).toBe(200);+ });++ it("refuses a session's key on writes whatever it names, and lets it read", async () => {+ const session = withKey(["work:read", "work:write"], { principal: "computer" } as Partial<RequestIdentity>);+ expect(await status(session, "PUT", "/work/repository", choice)).toMatchObject({ status: 403, error: { reason: "computer_principal" } });+ expect((await status(session)).status).toBe(200);+ });++ it("answers 200 with a null repository, and 503 unavailable when the index is not bound", async () => {+ const res = await call(env, stub, person, "GET", "/work/repository");+ expect(await json(res)).toEqual({ repository: null });+ const unbound = await call({}, stub, person, "GET", "/work/items?stage=open");+ expect(unbound.status).toBe(503);+ expect((await json(unbound)).error).toMatchObject({ code: "unavailable", retryable: true });+ });++ it("routes only the Work routes", async () => {+ expect((await call(env, stub, person, "DELETE", "/work/repository")).status).toBe(404);+ expect((await call(env, stub, person, "POST", "/work/items/1/close")).status).toBe(404);+ expect((await call(env, stub, person, "GET", "/work/files")).status).toBe(404);+ });+});++describe("Work API requests", () => {+ const env = { WORK_INDEX: { getByName: () => ({ repository: async () => null, setRepository: vi.fn(async (_a: string, c: unknown) => ({ ok: true, value: c })), items: async () => ({ ok: false, error: "invalid_cursor" }), item: async () => ({ item: null, body: null }) }) } };+ const stub: ComputerApiStub = { computerApi: vi.fn() };+ const err = async (res: Response) => ({ status: res.status, ...(await json(res)).error });++ it("refuses unknown query parameters, a missing stage, and paging on the open list", async () => {+ expect(await err(await call(env, stub, person, "GET", "/work/items?stage=open&owner=me"))).toMatchObject({ status: 400, code: "invalid_request", field: "owner" });+ expect(await err(await call(env, stub, person, "GET", "/work/repository?x=1"))).toMatchObject({ status: 400, field: "x" });+ expect(await err(await call(env, stub, person, "GET", "/work/items"))).toMatchObject({ status: 400, field: "stage" });+ expect(await err(await call(env, stub, person, "GET", "/work/items?stage=open&limit=5"))).toMatchObject({ status: 400, field: "limit" });+ expect(await err(await call(env, stub, person, "GET", "/work/items?stage=closed&limit=101"))).toMatchObject({ status: 400, field: "limit" });+ expect(await err(await call(env, stub, person, "GET", "/work/items?stage=closed&cursor=zz"))).toMatchObject({ status: 400, code: "invalid_cursor" });+ });++ it("answers item_not_found for a missing item or a number that is not one", async () => {+ for (const n of ["9", "0", "abc", "01"]) expect(await err(await call(env, stub, person, "GET", `/work/items/${n}`))).toMatchObject({ status: 404, code: "item_not_found" });+ });++ it("checks the PUT body: known fields only, the installation id as a string or a number", async () => {+ const put = (body: unknown, headers: Record<string, string> = {}) => call(env, stub, person, "PUT", "/work/repository", { body: JSON.stringify(body), headers });+ expect(await err(await put({ installationId: "i", owner: "acme", name: "k", extra: 1 }))).toMatchObject({ status: 400, field: "extra" });+ expect(await err(await put({ owner: "acme", name: "k" }))).toMatchObject({ status: 400, field: "installationId" });+ expect(await err(await put({ installationId: 1, owner: "a/b", name: "k" }))).toMatchObject({ status: 400, field: "owner" });+ expect(await err(await put({ installationId: 1, owner: "acme", name: ".." }))).toMatchObject({ status: 400, field: "name" });+ expect(await err(await put([1]))).toMatchObject({ status: 400, field: "" });+ expect(await err(await put({ installationId: 1, owner: "acme", name: "k" }, { "idempotency-key": "has space" }))).toMatchObject({ status: 400, field: "Idempotency-Key" });+ const ok = await put({ installationId: 12, owner: "acme", name: "k", branch: "trunk" }, { "idempotency-key": "k-1" });+ expect(await json(ok)).toEqual({ repository: { installationId: "12", owner: "acme", name: "k", branch: "trunk" } });+ });+});++describe("Work API composition", () => {+ it("joins the open items with the caller's sessions, people and emails", async () => {+ const { w, c } = await board();+ const res = await call(w.env, c.stub, person, "GET", "/work/items?stage=open");+ expect(res.status).toBe(200);+ const page = await json(res);+ expect(Object.keys(page)).toEqual(["repository", "head", "asOf", "building", "items"]);+ expect(page.repository).toEqual({ installationId: "12", owner: "acme", name: "knowledge", branch: "main", problem: null });+ expect(page.building).toBe(false);+ const [one, two, four] = page.items;++ // Mine: the owner is the git email the computer uses for me (people, through my Slack session's owner id).+ expect(one).toMatchObject({ number: 1, mine: true, owner: { email: "[email protected]", name: "Me", id: ME } });+ expect(one.attention).toEqual({ state: "needs_you", name: "Me", since: "2026-11-19T08:00:00.000Z" });+ expect(one.sessions).toEqual([+ { id: SID.mine, title: "Session 1", ownerName: "Me", status: "waiting" },+ { id: SID.bos, title: "Session 2", ownerName: "Bo", status: "running" },+ ]);++ // Bo's private Slack session is left out entirely: no attention from its open ask, not listed.+ // My Slack session, named by its key, is shown by its id; it is running.+ expect(two).toMatchObject({ number: 2, mine: false, owner: { email: "[email protected]", name: "Bo", id: BO } });+ expect(two.sessions).toEqual([{ id: SID.slack, title: "Session 3", ownerName: "Me", status: "running" }]);+ expect(two.attention).toEqual({ state: "working", name: "Me", since: "2026-11-19T09:30:00.000Z" });++ // An idle session adds no attention; a member known only by their git email has a name, no id.+ expect(four).toMatchObject({ number: 4, owner: { email: "[email protected]", name: "Cy Git", id: null }, author: { email: "[email protected]", name: "Cy Git", id: null }, attention: null, unpublished: false });+ expect(typeof four.updatedAt).toBe("string");++ // One call to the Computer object per page, with every linked session and email.+ expect(c.ops).toHaveLength(1);+ expect(new Set(c.ops[0]!.sessionIds)).toEqual(new Set([SID.mine, SID.bos, "T1:C1:111", SID.private, SID.idle]));+ });++ it("answers 304 to an unchanged poll, and a new ETag when attention or the head moves", async () => {+ const { repo, w, c } = await board();+ const first = await call(w.env, c.stub, person, "GET", "/work/items?stage=open");+ const etag = first.headers.get("etag")!;+ expect(etag).toMatch(new RegExp(`^"${repo.head}-[0-9a-f]{16}"$`));+ const again = await call(w.env, c.stub, person, "GET", "/work/items?stage=open", { headers: { "if-none-match": etag } });+ expect(again.status).toBe(304);+ expect(again.headers.get("etag")).toBe(etag);+ expect(await again.text()).toBe("");++ // Someone else's view of the same head differs (mine, needs_you), so its tag does too.+ const other = await call(w.env, c.stub, { ...person, userId: "user_bo", userEmail: "[email protected]" } as RequestIdentity, "GET", "/work/items?stage=open");+ expect(other.headers.get("etag")).not.toBe(etag);++ c.sql.exec("UPDATE sessions SET owner_email = NULL");+ const moved = await call(w.env, c.stub, person, "GET", "/work/items?stage=open", { headers: { "if-none-match": etag } });+ expect(moved.status).toBe(200);+ });++ it("pages closed items and answers one item with its body", async () => {+ const { w, c } = await board();+ const closed = await json(await call(w.env, c.stub, person, "GET", "/work/items?stage=closed&limit=10"));+ expect(Object.keys(closed)).toEqual(["items", "nextCursor"]);+ expect(closed.items.map((i: { number: number; stage: string }) => [i.number, i.stage])).toEqual([[3, "closed"]]);+ expect(closed.nextCursor).toBeNull();+ const one = await json(await call(w.env, c.stub, person, "GET", "/work/items/1"));+ expect(Object.keys(one)).toEqual(["item", "body"]);+ expect(one.item.attention.state).toBe("needs_you");+ expect(one.body).toContain("# 1. Mine");+ });++ it("shows a revision's session by its id, and only when the caller may see it", async () => {+ const { w, c } = await board();+ const res = await json(await call(w.env, c.stub, person, "GET", "/work/items/2/history"));+ expect(Object.keys(res)).toEqual(["revisions", "nextCursor"]);+ const update = res.revisions.find((r: { summary: string }) => r.summary === "Update 2");+ // The first trailer, my Slack session's key, becomes its id.+ expect(update.sessionId).toBe(SID.slack);+ const bo = await json(await call(w.env, c.stub, { ...person, userId: "user_bo" } as RequestIdentity, "GET", "/work/items/2/history"));+ expect(bo.revisions.find((r: { summary: string }) => r.summary === "Update 2").sessionId).toBeNull();+ });+});++describe("itemAttention", () => {+ const brief = (over: Partial<SessionBrief>): SessionBrief => ({ id: "cs_x", title: null, ownerId: BO, ownerName: "Bo", status: "idle", openAskAt: null, lastActiveAt: "2026-11-19T00:00:00Z", ...over });++ it("is needs_you, then waiting_on, then working, then nothing", () => {+ const mine = brief({ ownerId: ME, ownerName: "Me", openAskAt: "2026-11-19T05:00:00Z" });+ const bos = brief({ openAskAt: "2026-11-19T01:00:00Z" });+ const running = brief({ status: "running", lastActiveAt: "2026-11-19T06:00:00Z" });+ expect(itemAttention([bos, running, mine], ME)).toEqual({ state: "needs_you", name: "Me", since: "2026-11-19T05:00:00Z" });+ expect(itemAttention([running, bos], ME)).toEqual({ state: "waiting_on", name: "Bo", since: "2026-11-19T01:00:00Z" });+ expect(itemAttention([running, brief({ status: "starting", lastActiveAt: "2026-11-19T07:00:00Z" })], ME)).toEqual({ state: "working", name: "Bo", since: "2026-11-19T07:00:00Z" });+ expect(itemAttention([brief({ status: "waiting" }), brief({ status: "suspended" })], ME)).toBeNull();+ expect(itemAttention([], ME)).toBeNull();+ });+});diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.tsindex d9046e6f..8ef400aa 100644--- a/services/managed-agents/vitest.config.ts+++ b/services/managed-agents/vitest.config.ts@@ -496,6 +496,7 @@ export default defineConfig({"test/computer-secrets.test.ts", "test/computer-secrets-scopes.test.ts","test/work-item.test.ts","test/work-index.test.ts",+ "test/work-api.test.ts","test/computer-connections.test.ts","test/computer-model-subscriptions.test.ts","test/computer-codex-subscriptions.test.ts",