Multiplayer agent harness for work.
Derive admin, strict-posture and catalog policy from route metadata (#2481)
Regan Bell1dded315e339
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex b01444062..ecd758bff 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -1,5 +1,7 @@import type { CapabilityClaims } from "../auth/capability-token.ts";import { livePersonCapability } from "./artifact-share.ts";+import { adminRoutes } from "./routes/admin.ts";+import { UNATTENDED_ADMIN_GRANTS } from "./control-service.ts";interface AgentApiRoute {method: string;@@ -14,24 +16,16 @@ interface AgentApiView {}interface AgentApiFamily {- match: (method: string, pathname: string) => boolean;when?: (view: AgentApiView) => boolean;guidance?: string;routes: AgentApiRoute[];}-const onPath = (m: string, p: string) => (method: string, pathname: string) => method === m && pathname === p;-const CONVERSATION_UPDATE ="update one of the asking person's conversations — body {archived?, pinned?, title?, color?}; archive/unarchive, pin/unpin, rename (null title clears), or set the sidebar color (#rrggbb; null clears). These are per-person.";const FAMILIES: AgentApiFamily[] = [{- match: (method, path) =>- (method === "POST" && path === "/v1/composio/twitter/media") ||- (method === "GET" &&- ["identity", "connections", "toolkits", "tools"].some((name) => path === `/v1/composio/${name}`)) ||- (method === "POST" && ["authorize", "execute", "disconnect"].some((name) => path === `/v1/composio/${name}`)),guidance:"Use the composio skill for backend app access. Never load a Composio project key or call its SDK directly. Execution binds accounts to your identity and sharing permissions.",routes: [@@ -73,7 +67,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (method, path) => path === "/v1/swarm" && (method === "GET" || method === "POST"),when: (view) => view.swarmsEnabled,guidance:"Swarm workers are ordinary sessions with private blank computers. Inspect peers and their context, then send to chosen IDs or all; shared history is visible to every member. Notifications queue unattended turns. Each swarm gets one shared board computer (inspect returns board.sandboxId) that the root and every worker reach with execute's sandbox_id; pass forumSandboxId at creation to use an existing shared computer instead. Spawn accepts model, effort and fastMode to choose the runtime for the workers it creates; children inherit it unless they choose again. POST action control with memberId and state active, paused or stopped pauses delivery to, resumes, or stops a descendant worker. To keep a worker going instead of stopping after one reply, give it a goal on spawn or send ({objective, floor?, token_cap?}): its turn then runs like a goal turn, past the swarm turn deadline, until the goal is complete, paused or out of tokens. Only a parent can assign goals, to its own workers; send a goal again to replace a paused one.",@@ -93,11 +86,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (m === "GET" && p === "/v1/files/upload-client") ||- (p === "/v1/files/uploads" && m === "POST") ||- (/^\/v1\/files\/uploads\/[^/]+$/.test(p) && (m === "GET" || m === "DELETE")) ||- (/^\/v1\/files\/uploads\/[^/]+\/(complete|parts\/[^/]+)$/.test(p) && m === "POST"),guidance:'Publish important outputs to durable Files before retiring a sandbox. Run: curl -fsS "$AGENT_API_URL/v1/files/upload-client" -H "x-agent-capability: $AGENT_API_TOKEN" -o /tmp/qm-upload.py && python3 /tmp/qm-upload.py path/to/file. The helper uploads directly to S3, retries parts, and resumes when rerun with the same file. Only final success means the file is published. Files are saved to this conversation\'s scope. Up to 100 GiB per file, including empty files.',routes: [@@ -127,7 +115,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: onPath("POST", "/v1/search"),guidance:"Search uses this conversation's complete principal set as its visibility floor. Shared conversations without a complete roster fail closed.",routes: [@@ -140,7 +127,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: onPath("GET", "/v1/apis"),routes: [{method: "GET",@@ -150,27 +136,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) => p === "/v1/runtime-config" && (m === "GET" || m === "PUT"),- when: () => false,- guidance:- "Runtime choice is scoped: changing it affects this personal or shared context, not the whole org. Confirm before changing a shared scope. An inherit reset follows future org defaults automatically.",- routes: [- {- method: "GET",- path: "/v1/runtime-config",- summary:- "read this scope's effective harness/model, approved choices, override, and whether the org recommends an upgrade",- },- {- method: "PUT",- path: "/v1/runtime-config",- summary:- "set this scope's default with {harnessId,modelId}, follow the org with {inherit:true}, or keep the current override while acknowledging the recommendation with {keep:true}",- },- ],- },- {- match: (m, p) => p === "/v1/channel-header-pin" && (m === "GET" || m === "PUT"),guidance:"The pinned Slack header (a small pinned message naming the model in use) follows an org-wide default (off unless an admin turned it on). Only override it for a channel scope when someone in that channel asks.",routes: [@@ -188,12 +153,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/projects" && (m === "GET" || m === "POST")) ||- (/^\/v1\/projects\/[^/]+$/.test(p) && m === "PATCH") ||- (/^\/v1\/projects\/[^/]+\/members$/.test(p) && m === "POST") ||- (/^\/v1\/projects\/[^/]+\/members\/[^/]+$/.test(p) && m === "DELETE") ||- (/^\/v1\/projects\/[^/]+\/slack-channel$/.test(p) && (m === "PUT" || m === "DELETE")),guidance:"These act as the ASKING PERSON across every project they belong to, matching the web UI. Do not send principalId; the capability token always determines the person, and inaccessible projects return 404.",routes: [@@ -232,8 +191,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- /^\/v1\/loops\/[^/]+\/items(\/[^/]+(\/(action|followup))?)?$/.test(p) && (m === "GET" || m === "POST"),guidance:"A loop's ledger is its durable queue of work items. Each entry carries an opaque sourcePayload the loop's own frontend understands, a proposal held for human review, and a follow-up chat thread. States run pending -> processed -> held -> actioned|dismissed. Ingest only what the loop's playbook tells you to; proposals are prepared, never executed — the person actions them from their review surface.",routes: [@@ -269,14 +226,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/loops" && (m === "POST" || m === "GET")) ||- ((m === "POST" || m === "DELETE") &&- p.startsWith("/v1/loops/") &&- (p.endsWith("/fire") || p.endsWith("/autopilot") || p.includes("/grants") || p.includes("/outputs/"))) ||- (p.startsWith("/v1/loops/") &&- !p.slice("/v1/loops/".length).includes("/") &&- (m === "GET" || m === "PATCH" || m === "DELETE")),guidance:'A loop is standing autonomous work: a trigger plus a playbook plus a durable work ledger, with finished outputs HELD for a person to ship. Prefer the define-loop skill to author one (it interviews, shadow-runs one item, then creates the loop). New loops should declare every externally-visible ship action at gate "hold"; "auto" is earned through grants after real approvals. Work turns run without surface tools or addressed delivery; final external actions happen in the fenced ship stage. Broader work-stage tool restriction is a known limitation pending turn-runner tool policy.',routes: [@@ -320,49 +269,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/crons" && (m === "POST" || m === "GET")) ||- (m === "POST" &&- p.startsWith("/v1/crons/") &&- (p.endsWith("/disable") || p.endsWith("/destination") || p.endsWith("/run") || p.endsWith("/note"))) ||- (m === "GET" && p.startsWith("/v1/crons/") && p.endsWith("/runs")) ||- (p.startsWith("/v1/crons/") &&- !p.slice("/v1/crons/".length).includes("/") &&- (m === "GET" || m === "PATCH" || m === "DELETE")),- when: () => false,- routes: [- {- method: "POST",- path: "/v1/crons",- summary:- 'schedule future or recurring work — a 2-5 word `title` naming what the cron is for (distinctive in a list, not the command) plus `task` (re-run at fire time) or exact `text`, optionally addressed by name to a teammate (`recipient`), a channel (`channel`), or a group DM (`participants`: its other members, which must already exist as a group DM — reach it once first, which opens it; same venue rule as /v1/reach — narrowest audience, a channel only when explicitly requested or genuinely room-wide), or run privately for whoever asked at their own scope (`scope:"personal"`, even from a channel); pass `unfurlLinks:false` to suppress Slack previews; the cron is tied to this conversation so it shows as ongoing work here unless `session:false` (to send now instead, use /v1/reach)',- },- { method: "GET", path: "/v1/crons", summary: "list your crons" },- {- method: "GET|PATCH|DELETE",- path: "/v1/crons/:id",- summary:- "inspect, rename, archive, edit, or delete a cron; create/patch accepts runtime: {harnessId, modelId, effortLevel?, fastMode?} for agent tasks, null clears the override; omitted preserves existing defaults",- },- {- method: "GET",- path: "/v1/crons/:id/runs",- summary: "read the retained fire log for a cron; use only when older run history is relevant",- },- { method: "POST", path: "/v1/crons/:id/disable", summary: "disable a cron" },- { method: "POST", path: "/v1/crons/:id/destination", summary: "retarget where a cron delivers" },- { method: "POST", path: "/v1/crons/:id/run", summary: "fire a cron now" },- {- method: "POST",- path: "/v1/crons/:id/note",- summary:- "at the end of a cron fire, leave a short shift-change note for the cron's next fire — body {note}: one or two sentences, outcome plus anything the next fire must know",- },- ],- },- {- match: (m, p) =>- ((m === "POST" || m === "GET") && p === "/v1/pins") || (m === "DELETE" && /^\/v1\/pins\/[^/]+$/.test(p)),guidance:"Pins are conversation-scoped bookmarks shown at the top of the web UI — for the handful of things worth keeping in view for a whole session: a decision, a link, a working answer, a key transcript entry. Use them SPARINGLY — a few pins that matter, not a running log (there is a hard cap, and every pin takes reader attention); durable facts belong in memory, working state in files. Pin a transcript entry by its seq, or a short free-text note. In a Slack DM, pinning a transcript entry also pins the underlying Slack message natively (and unpinning removes it). Keep them current — unpin what no longer matters.",routes: [@@ -377,32 +283,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/ui/canvas" && ["GET", "POST", "DELETE"].includes(m)) || (m === "POST" && p === "/v1/ui/observe"),- when: () => false,- routes: [- { method: "GET", path: "/v1/ui/canvas", summary: "read this conversation's web UI canvas" },- { method: "POST", path: "/v1/ui/canvas", summary: "write, update, replace or pin the canvas (ui-canvas skill)" },- { method: "DELETE", path: "/v1/ui/canvas", summary: "dismiss the canvas" },- { method: "POST", path: "/v1/ui/observe", summary: "snapshot the person's open web UI (ui-state skill)" },- ],- },- {- match: onPath("POST", "/v1/share"),- when: () => false,- routes: [- {- method: "POST",- path: "/v1/share",- summary:- 'share or move one of YOUR artifacts to another context — body {type:"file"|"skill"|"deploy"|"cron", id, toScope:"org"|<scope id>|a teammate\'s name, permission?:"read"(default)|"write", move?:false}. For app sharing only, `email` may replace `toScope` to grant view access to an exact email outside the directory. Default (share) adds a grant — the artifact keeps its home and creator. move:true changes its home scope instead (skills only today). Frictionless into any context you belong to; allowed for anyone who manages the artifact\'s home (its owner, or a current member of its private-channel/group home), from any conversation; ceding a skill to the org is admin-gated (a live org admin only).',- },- ],- },- {- match: (m, p) =>- (m === "GET" && (p === "/v1/conversations" || /^\/v1\/conversations\/[^/]+$/.test(p))) ||- (m === "POST" && /^\/v1\/conversations\/[^/]+$/.test(p)),guidance:"These act on the ASKING PERSON's own conversation list (the web UI sidebar) — archiving, pinning, or renaming is a per-person view change, never a deletion, and never touches anyone else's list. Confirm before bulk-archiving.",routes: [@@ -421,7 +301,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: () => false,routes: [{method: "POST",@@ -431,7 +310,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) => m === "GET" && (p === "/v1/files" || /^\/v1\/files\/[^/]+\/content$/.test(p)),guidance:"These show the ASKING PERSON's file library across every context they can reach. A file outside their visibility returns 404 without revealing whether it exists.",routes: [@@ -449,7 +327,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: onPath("POST", "/v1/reach"),routes: [{method: "POST",@@ -460,14 +337,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (m === "GET" && p === "/v1/deployments") ||- (m === "GET" && /^\/v1\/deployments\/[^/]+$/.test(p)) ||- (m === "GET" && /^\/v1\/deployments\/[^/]+\/fetch$/.test(p)) ||- (m === "GET" && /^\/v1\/deployments\/[^/]+\/logs$/.test(p)) ||- (m === "GET" && /^\/v1\/deployments\/[^/]+\/(git-url|share)$/.test(p)) ||- (m === "POST" &&- /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name|always-on|embed-ancestors)$/.test(p)),guidance:'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`apps` action `publish`) is reachable only by its owner plus whoever the owner shares it with. For authenticated access, POST /v1/deployments/:id/share with `scope:"org"`, `recipient:"<name>"`, or an exact `email:"[email protected]"` with `access:"view"`; email grants to people outside the organization are view-only, send an invitation with the app link, and are refused unless an org admin has enabled external app sharing (off by default). Check `invitation.emailSent` and surface `emailProblem` if delivery fails. This does not make the recipient an instance member. To make the app reachable without sign-in, POST the same endpoint with `{public:true}`; `{public:false}` restricts it again. Public access is never the default, only the owner may change it, and it is refused (and existing public links require sign-in) unless an org admin has enabled external app sharing. POST /v1/deployments/:id/embed-ancestors with `{embedAncestors:["https://tools.example.com", ...]}` lets those sites embed the app; pass `[]` to forbid embedding again. To rename, archive, restore, or change always-on behavior, use the corresponding endpoint.',routes: [@@ -547,30 +416,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/webhooks" && (m === "POST" || m === "GET")) ||- (m === "GET" && /^\/v1\/webhooks\/[^/]+\/events$/.test(p)) ||- (m === "POST" && /^\/v1\/webhooks\/[^/]+\/(disable|enable|update)$/.test(p)),- when: () => false,- routes: [- {- method: "POST",- path: "/v1/webhooks",- summary: "register an inbound webhook that runs a prompt when an external system calls it (secret shown once)",- },- { method: "GET", path: "/v1/webhooks", summary: "list your webhooks" },- { method: "GET", path: "/v1/webhooks/:id/events", summary: "recent webhook payloads and sessions" },- { method: "POST", path: "/v1/webhooks/:id/disable", summary: "disable a webhook" },- {- method: "POST",- path: "/v1/webhooks/:id/update",- summary: "update a webhook task in place (URL and secret unchanged)",- },- { method: "POST", path: "/v1/webhooks/:id/enable", summary: "re-enable a webhook" },- ],- },- {- match: (m, p) => p === "/v1/pinned-skills" && (m === "GET" || m === "PUT"),routes: [{ method: "GET", path: "/v1/pinned-skills", summary: "list the skills pinned to this conversation's scope" },{@@ -582,18 +427,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) => p === "/v1/soul" && (m === "POST" || m === "GET"),- when: () => false,- routes: [- { method: "GET", path: "/v1/soul", summary: "read this scope's standing instructions (SOUL)" },- { method: "POST", path: "/v1/soul", summary: "update this scope's standing instructions (versioned, audited)" },- ],- },- {- match: (m, p) =>- (p === "/v1/memory/self" && m === "GET") ||- (p === "/v1/memory/facts" && (m === "PATCH" || m === "DELETE")) ||- (m === "POST" && (p === "/v1/memory/search" || p === "/v1/memory/facts")),when: (v) => !!v.claims.memory,guidance: "Memory bodies and curation rules are documented in the memory skill.",routes: [@@ -612,7 +445,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: () => false,when: (v) => !!v.claims.memory?.orgWrite,routes: [{@@ -624,14 +456,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (p === "/v1/keychain/credentials" && (m === "POST" || m === "GET")) ||- (p === "/v1/keychain/overview" && m === "GET") ||- (m === "DELETE" && p.startsWith("/v1/keychain/credentials/")) ||- (p === "/v1/keychain/grants" && m === "GET") ||- (m === "POST" && p.startsWith("/v1/keychain/grants/") && p.endsWith("/revoke")) ||- (p === "/v1/keychain/asks" && (m === "POST" || m === "GET")) ||- (m === "POST" && p === "/v1/keychain/drops"),guidance:"The keychain ask→card approval→execute.credentials protocol is documented in your keychain manifest when one renders.",routes: [@@ -664,7 +488,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) => m === "POST" && (p === "/v1/surface-context" || p === "/v1/surface-file"),routes: [{method: "POST",@@ -681,20 +504,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: onPath("GET", "/v1/directory/resolve"),- when: () => false,- routes: [- {- method: "GET",- path: "/v1/directory/resolve",- summary:- "resolve a teammate's name/handle to directory matches incl. their Slack mention id — ?q=<name> → {matches:[{principalId,displayName,type,slackId?}]}; write slackId as <@slackId> to @-mention them so Slack notifies them",- },- ],- },- {- match: (m, p) =>- (p === "/v1/environments" && (m === "POST" || m === "GET")) || (m === "POST" && p === "/v1/environments/attach"),routes: [{method: "GET",@@ -714,11 +523,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) =>- (m === "POST" && p === "/v1/skills") ||- (m === "GET" && p.startsWith("/v1/skills/")) ||- ((m === "PUT" || m === "DELETE") && p.startsWith("/v1/skills/")) ||- (m === "POST" && /^\/v1\/skills\/[^/]+\/restore$/.test(p)),guidance:"Save a skill when you've worked out a repeatable procedure worth keeping (a checklist, a multi-step flow, a house style) — it is advertised in the skill index and loaded with the skills tool on future turns. The skill homes in THIS conversation's scope: in a 1:1 DM it's yours alone; in a private channel or group DM it's owned by that room and every member can edit or delete it (the audit trail records who changed what); a public channel stays owner-only. Write the `body` as a plain-step recipe addressed to your future self; edit or delete it as it goes stale.",routes: [@@ -752,7 +556,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (m, p) => m === "POST" && p === "/v1/emoji",guidance:"Pick or produce a square image under ~128KB, base64 it, then call this once. An upload error is a real result to relay, not a reason to ask the user to do it by hand.",routes: [@@ -765,7 +568,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: onPath("POST", "/v1/connectors/oauth/revoke"),guidance:"Disconnect a user's OAuth connector (the reverse of connecting one). Defaults to you; to disconnect a teammate's, name them with principalId — they must share this conversation. Confirm before revoking someone else's.",routes: [@@ -778,7 +580,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: () => false,routes: [{method: "POST",@@ -795,7 +596,6 @@ const FAMILIES: AgentApiFamily[] = [],},{- match: (_m, p) => p.startsWith("/v1/admin/"),when: (v) => v.isAdmin && livePersonCapability(v.claims),guidance:"Admin plane: you act AS this org admin — live-authorized per call, audited under their name; confirm before any mutation (bodies/params in the admin skill). Enforced limits: content reads require a DM or effective Open sharing for the live admin (organization, personal, and conversation restrictions all apply); configuration mutations work anywhere; admin grant changes, impersonation, and identity links are portal-only. Open admin reads can expose private data to the conversation; retrieve and report only what the request needs.",@@ -841,11 +641,6 @@ const FAMILIES: AgentApiFamily[] = [summary:"document store listing; files/read?id= and files/download?id= for content (DM or effective Open sharing)",},- {- method: "GET",- path: "/v1/admin/volumes?scope=",- summary: "a scope's computer/backup contents (paths and sizes; DM or effective Open sharing)",- },{method: "GET",path: "/v1/admin/crons|deployments|skills?scope=",@@ -888,58 +683,27 @@ const FAMILIES: AgentApiFamily[] = [},],},- {- match: () => false,- when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes("admin.sessions.read") === true,- guidance:- "This cron has a specific read-only admin grant. Use only these listed routes; flag any other admin action to a human.",- routes: [- { method: "GET", path: "/v1/admin/sessions", summary: "list conversation metadata" },- { method: "GET", path: "/v1/admin/sessions/:id", summary: "read a conversation transcript" },- { method: "GET", path: "/v1/admin/scopes", summary: "list the scope directory" },- { method: "GET", path: "/v1/admin/errors", summary: "read error telemetry" },- { method: "GET", path: "/v1/admin/runs", summary: "read queued, in-flight, and recent runs" },- ],- },- {- match: () => false,- when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes("admin.audit.read") === true,- guidance:- "This cron has a specific read-only admin grant. Use only these listed routes; flag any other admin action to a human.",- routes: [{ method: "GET", path: "/v1/admin/audit", summary: "read security audit events" }],- },- {- match: () => false,- when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes("admin.egress.read") === true,- guidance:- "This cron has a specific read-only admin grant. Use only these listed routes; flag any other admin action to a human.",- routes: [{ method: "GET", path: "/v1/admin/egress", summary: "read scope-labelled egress decisions" }],- },- {- match: () => false,- when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes("admin.files.read") === true,+];++const unattendedFamilies = (): AgentApiFamily[] =>+ UNATTENDED_ADMIN_GRANTS.map((grant) => ({+ when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes(grant) === true,guidance:"This cron has a specific read-only admin grant. Use only these listed routes; flag any other admin action to a human.",- routes: [- { method: "GET", path: "/v1/admin/files", summary: "list a scope's document store" },- { method: "GET", path: "/v1/admin/files/read?id=", summary: "read a stored file" },- { method: "GET", path: "/v1/admin/files/download?id=", summary: "download a stored file" },- ],- },-];+ routes: adminRoutes.flatMap((route) =>+ "path" in route && route.admin?.unattended?.grant === grant+ ? [{ method: route.method, path: route.path, summary: route.admin.unattended.summary }]+ : [],+ ),+ }));const WHOAMI_FOR_ALL: AgentApiFamily = {- match: () => false,when: (v) => !(v.isAdmin && livePersonCapability(v.claims)),routes: [{ method: "GET", path: "/v1/admin/whoami", summary: "this user's org capabilities: {permissions, isAdmin, role?}" },],};-export function agentApiMatches(method: string, pathname: string): boolean {- return FAMILIES.some((f) => f.match(method, pathname));-}-export interface AgentApiListing {actorId: string;scopeId: string;@@ -958,7 +722,7 @@ export function renderAgentApis(isAdmin: admin.isAdmin,swarmsEnabled: features.swarmsEnabled,};- const visible = [...FAMILIES, WHOAMI_FOR_ALL].filter((f) => f.when?.(view) ?? true);+ const visible = [...FAMILIES, ...unattendedFamilies(), WHOAMI_FOR_ALL].filter((f) => f.when?.(view) ?? true);return {actorId: claims.actorId,scopeId: claims.scopeId,diff --git a/src/api/control-service.ts b/src/api/control-service.tsindex 284850df3..6ee2bd8a3 100644--- a/src/api/control-service.ts+++ b/src/api/control-service.ts@@ -317,10 +317,16 @@ function patchFromCronPatchRequest(};}-const UNATTENDED_GRANTS = new Set(["admin.sessions.read", "admin.audit.read", "admin.egress.read", "admin.files.read"]);+export const UNATTENDED_ADMIN_GRANTS = [+ "admin.sessions.read",+ "admin.audit.read",+ "admin.egress.read",+ "admin.files.read",+] as const;function validateUnattendedGrants(grants: string[]): string | null {- if (!grants.every((grant) => UNATTENDED_GRANTS.has(grant))) return "unknown unattended grant";+ if (!grants.every((grant) => (UNATTENDED_ADMIN_GRANTS as readonly string[]).includes(grant)))+ return "unknown unattended grant";return null;}diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex f8426d591..c30c05b48 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -122,6 +122,7 @@ export interface AdminResource {authz?: "scope-admin" | "org-admin";label?: string;enumValues?: readonly unknown[];+ refreshesModels?: true;}function generic<V>(@@ -194,6 +195,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [},{id: "auto-flagger",+ refreshesModels: true,kind: "custom",target: "org",clearable: true,@@ -524,6 +526,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [},{id: "memory-embedding-model",+ refreshesModels: true,kind: "enum",target: "org",clearable: true,@@ -538,16 +541,15 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [const { modelId } = ctx.body as { modelId?: unknown };if (modelId !== null && (typeof modelId !== "string" || !modelId.trim()))return { error: "Provide an embedding modelId, or null to disable semantic recall" };- if (modelId !== null) {- await ctx.deps.refreshModels?.();- if (!resolveEmbeddingModel(modelId as string)) return { error: "Unknown or unverified embedding model" };- }+ if (modelId !== null && !resolveEmbeddingModel(modelId))+ return { error: "Unknown or unverified embedding model" };await ctx.deps.config!.setEmbeddingModel(modelId as string | null);return { ok: true };},},{id: "base-model",+ refreshesModels: true,kind: "enum",target: "any",clearable: true,@@ -619,6 +621,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [},...([undefined, "cron", "subagent", "fallback"] as const).map((purpose): AdminResource => ({id: purpose ? `${purpose}-runtime` : "runtime",+ refreshesModels: true,kind: "custom",target: purpose ? "org" : "any",clearable: true,@@ -700,6 +703,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [},{id: "webui-models",+ refreshesModels: true,kind: "string-list",target: "org",clearable: true,@@ -810,6 +814,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [},{id: "browse-model",+ refreshesModels: true,kind: "enum",target: "org",clearable: true,diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.tsindex 14ec71385..acd4fed02 100644--- a/src/api/routes/admin.ts+++ b/src/api/routes/admin.ts@@ -1,5 +1,5 @@import { modelRegistry, lookupRegistryModel, enableBuiltinModel } from "./admin/model-registry.ts";-import { type ApiCtx, type Route } from "./route.ts";+import { withAdmin, type ApiCtx, type Route } from "./route.ts";import {getAdminResources,getScopeConfig,@@ -75,98 +75,321 @@ const timed =}};-const routes: ReadonlyArray<Route<ApiCtx>> = [- { method: "POST", path: "/v1/admin/slack-installation/start", auth: "either", handle: startSlackInstallation },+const GRANTS = "admin grant changes (promote/revoke) are portal-only — the agent cannot manage who governs the org";+const IMPERSONATE = "impersonating a user is portal-only — the agent cannot act as another person";+const LINKS = "identity links are portal-only — the agent cannot decide which sign-ins belong to one person";++const routes: Route<ApiCtx>[] = [{ method: "POST", path: "/v1/slack/managed/installation", auth: "public", handle: managedSlackRequest },{ method: "DELETE", path: "/v1/slack/managed/installation", auth: "public", handle: managedSlackRequest },{ method: "POST", path: "/v1/slack/managed/events", auth: "public", handle: managedSlackRequest },- { method: "GET", path: "/v1/admin/slack-installation", auth: "either", handle: getSlackInstallation },- { method: "GET", path: "/v1/admin/slack-emoji", auth: "either", handle: getSlackEmojiList },- { method: "PUT", path: "/v1/admin/slack-installation", auth: "either", handle: putSlackInstallation },- { method: "DELETE", path: "/v1/admin/slack-installation", auth: "either", handle: deleteSlackInstallation },- { method: "GET", path: "/v1/admin/model-providers", auth: "either", handle: getModelProviders },- { method: "PUT", path: "/v1/admin/model-providers/:provider", auth: "either", handle: putModelProvider },- { method: "GET", path: "/v1/admin/mcp-servers", auth: "either", handle: getMcpServers },- { method: "PUT", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: putMcpServer },- { method: "DELETE", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: deleteMcpServer },- { method: "DELETE", path: "/v1/admin/model-providers/:provider", auth: "either", handle: deleteModelProvider },- { method: "POST", path: "/v1/admin/model-registry/lookup", auth: "either", handle: lookupRegistryModel },- { method: "POST", path: "/v1/admin/model-registry/:model/enable", auth: "either", handle: enableBuiltinModel },- { method: "GET", path: "/v1/admin/model-registry", auth: "either", handle: modelRegistry },- { method: "PUT", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },- { method: "DELETE", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },- { method: "GET", path: "/v1/admin/custom-providers", auth: "either", handle: getCustomProviders },- { method: "PUT", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: putCustomProvider },- { method: "DELETE", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: deleteCustomProvider },- {- method: "POST",- path: "/v1/admin/scopes/:scope/auto-flagger/test",- auth: "either",- handle: testAutoFlagger,- },- { method: "PUT", path: "/v1/admin/scopes/:scope/:resource", auth: "either", handle: putScopeConfig },- { method: "GET", path: "/v1/admin/whoami", auth: "either", handle: whoami },- { method: "GET", path: "/v1/admin/scopes", auth: "either", handle: listAdminScopes },- { method: "GET", path: "/v1/admin/scopes/:scope", auth: "either", handle: getScopeConfig },- {- method: "GET",- path: "/v1/admin/scopes/:scope/credential-usage",- auth: "either",- handle: getCredentialUsageSummary,- },- { method: "GET", path: "/v1/admin/resources", auth: "either", handle: getAdminResources },- { method: "GET", path: "/v1/admin/retention", auth: "either", handle: retention },- { method: "GET", path: "/v1/admin/spend", auth: "either", handle: spend },- { method: "GET", path: "/v1/admin/egress", auth: "either", handle: egress },- { method: "GET", path: "/v1/admin/sessions", auth: "either", handle: listAdminSessions },- { method: "GET", path: "/v1/admin/sessions/:id/llm", auth: "either", handle: getAdminSessionLlm },- { method: "GET", path: "/v1/admin/sessions/:id", auth: "either", handle: getAdminSession },- { method: "GET", path: "/v1/admin/runs", auth: "either", handle: listAdminRuns },- { method: "GET", path: "/v1/admin/deliveries/shadow", auth: "either", handle: listAdminShadowDeliveries },- { method: "GET", path: "/v1/admin/slack-mirror/messages", auth: "either", handle: listSlackMirrorMessages },- { method: "GET", path: "/v1/admin/slack-mirror", auth: "either", handle: listSlackMirrorContainers },- { method: "GET", path: "/v1/admin/ambient-judgments", auth: "either", handle: listAmbientJudgments },- { method: "GET", path: "/v1/admin/ack-emoji-picks", auth: "either", handle: listAckEmojiPicks },- { method: "GET", path: "/v1/admin/files/read", auth: "either", handle: readAdminFile },- { method: "GET", path: "/v1/admin/files/download", auth: "either", handle: downloadAdminFile },- { method: "POST", path: "/v1/admin/files/upload", auth: "either", handle: uploadAdminFile },- { method: "GET", path: "/v1/admin/files", auth: "either", handle: listAdminFiles },- { method: "GET", path: "/v1/admin/errors", auth: "either", handle: listAdminErrors },- { method: "GET", path: "/v1/admin/audit", auth: "either", handle: listAdminAudit },- { method: "GET", path: "/v1/admin/security/flags", auth: "either", handle: listSecurityFlags },- {- match: (m, p) =>- m === "GET" && (p === "/v1/admin/crons" || p === "/v1/admin/deployments" || p === "/v1/admin/skills"),- auth: "either",- handle: listAdminArtifacts,- },- { method: "PUT", path: "/v1/admin/crons/:id/runtime", auth: "either", handle: putAdminCronRuntime },- { method: "PUT", path: "/v1/admin/crons/:id/destination", auth: "either", handle: putAdminCronDestination },- { method: "GET", path: "/v1/admin/skills/:id", auth: "either", handle: getAdminSkill },- { method: "DELETE", path: "/v1/admin/skills/:id", auth: "either", handle: archiveAdminSkill },- { method: "GET", path: "/v1/admin/memory/scopes", auth: "either", handle: listMemoryScopes },- { method: "GET", path: "/v1/admin/memory", auth: "either", handle: adminMemory },- { method: "POST", path: "/v1/admin/memory", auth: "either", handle: adminMemory },- { method: "PATCH", path: "/v1/admin/memory", auth: "either", handle: adminMemory },- { method: "DELETE", path: "/v1/admin/memory", auth: "either", handle: adminMemory },- { method: "GET", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },- { method: "POST", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },- { method: "GET", path: "/v1/admin/users", auth: "either", handle: listUsers },- { method: "GET", path: "/v1/admin/directory", auth: "either", handle: searchDirectory },- { method: "GET", path: "/v1/admin/keychain", auth: "either", handle: listKeychainStatus },- { method: "GET", path: "/v1/admin/users/:principalId", auth: "either", handle: getUserDetail },- { method: "PUT", path: "/v1/admin/users/:principalId/onboarding", auth: "either", handle: setUserOnboarding },- { method: "POST", path: "/v1/admin/users/:principalId/reset", auth: "either", handle: resetUserToBrandNew },- { method: "GET", path: "/v1/admin/principal-links", auth: "either", handle: listPrincipalLinks },- { method: "POST", path: "/v1/admin/principal-links", auth: "either", handle: createPrincipalLink },- { method: "DELETE", path: "/v1/admin/principal-links/:principalId", auth: "either", handle: deletePrincipalLink },- { method: "POST", path: "/v1/admin/grants", auth: "either", handle: createAdminGrant },- { method: "DELETE", path: "/v1/admin/grants/:principalId", auth: "either", handle: revokeAdminGrant },- { method: "POST", path: "/v1/admin/users/invite", auth: "either", handle: inviteTeammate },- { method: "POST", path: "/v1/admin/external-users", auth: "either", handle: inviteExternalUser },- { method: "DELETE", path: "/v1/admin/external-users/:email", auth: "either", handle: revokeExternalUser },- { method: "POST", path: "/v1/admin/impersonate/stop", auth: "either", handle: stopImpersonation },- { method: "POST", path: "/v1/admin/impersonate", auth: "either", handle: startImpersonation },+ ...withAdmin([+ { method: "POST", path: "/v1/admin/slack-installation/start", auth: "either", handle: startSlackInstallation },+ { method: "GET", path: "/v1/admin/slack-installation", auth: "either", handle: getSlackInstallation },+ { method: "GET", path: "/v1/admin/slack-emoji", auth: "either", handle: getSlackEmojiList },+ { method: "PUT", path: "/v1/admin/slack-installation", auth: "either", handle: putSlackInstallation },+ { method: "DELETE", path: "/v1/admin/slack-installation", auth: "either", handle: deleteSlackInstallation },+ { method: "GET", path: "/v1/admin/model-providers", auth: "either", handle: getModelProviders },+ { method: "PUT", path: "/v1/admin/model-providers/:provider", auth: "either", handle: putModelProvider },+ { method: "GET", path: "/v1/admin/mcp-servers", auth: "either", handle: getMcpServers },+ { method: "PUT", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: putMcpServer },+ { method: "DELETE", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: deleteMcpServer },+ { method: "DELETE", path: "/v1/admin/model-providers/:provider", auth: "either", handle: deleteModelProvider },+ { method: "POST", path: "/v1/admin/model-registry/lookup", auth: "either", handle: lookupRegistryModel },+ { method: "POST", path: "/v1/admin/model-registry/:model/enable", auth: "either", handle: enableBuiltinModel },+ { method: "GET", path: "/v1/admin/model-registry", auth: "either", handle: modelRegistry },+ { method: "PUT", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },+ { method: "DELETE", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },+ { method: "GET", path: "/v1/admin/custom-providers", auth: "either", handle: getCustomProviders },+ { method: "PUT", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: putCustomProvider },+ { method: "DELETE", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: deleteCustomProvider },+ {+ method: "POST",+ path: "/v1/admin/scopes/:scope/auto-flagger/test",+ auth: "either",+ handle: testAutoFlagger,+ },+ { method: "PUT", path: "/v1/admin/scopes/:scope/:resource", auth: "either", handle: putScopeConfig },+ { method: "GET", path: "/v1/admin/whoami", auth: "either", admin: { agent: "anyone" }, handle: whoami },+ {+ method: "GET",+ path: "/v1/admin/scopes",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.sessions.read", summary: "list the scope directory" },+ },+ handle: listAdminScopes,+ },+ {+ method: "GET",+ path: "/v1/admin/scopes/:scope",+ auth: "either",+ admin: { privateRead: "unless-org-scope" },+ handle: getScopeConfig,+ },+ {+ method: "GET",+ path: "/v1/admin/scopes/:scope/credential-usage",+ auth: "either",+ admin: { privateRead: "unless-org-scope" },+ handle: getCredentialUsageSummary,+ },+ { method: "GET", path: "/v1/admin/resources", auth: "either", handle: getAdminResources },+ { method: "GET", path: "/v1/admin/retention", auth: "either", handle: retention },+ { method: "GET", path: "/v1/admin/spend", auth: "either", handle: spend },+ {+ method: "GET",+ path: "/v1/admin/egress",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.egress.read", summary: "read scope-labelled egress decisions" },+ },+ handle: egress,+ },+ {+ method: "GET",+ path: "/v1/admin/sessions",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.sessions.read", summary: "list conversation metadata" },+ },+ handle: listAdminSessions,+ },+ {+ method: "GET",+ path: "/v1/admin/sessions/:id/llm",+ auth: "either",+ admin: { privateRead: "always" },+ handle: getAdminSessionLlm,+ },+ {+ method: "GET",+ path: "/v1/admin/sessions/:id",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.sessions.read", summary: "read a conversation transcript" },+ },+ handle: getAdminSession,+ },+ {+ method: "GET",+ path: "/v1/admin/runs",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.sessions.read", summary: "read queued, in-flight, and recent runs" },+ },+ handle: listAdminRuns,+ },+ {+ method: "GET",+ path: "/v1/admin/deliveries/shadow",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAdminShadowDeliveries,+ },+ {+ method: "GET",+ path: "/v1/admin/slack-mirror/messages",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listSlackMirrorMessages,+ },+ {+ method: "GET",+ path: "/v1/admin/slack-mirror",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listSlackMirrorContainers,+ },+ {+ method: "GET",+ path: "/v1/admin/ambient-judgments",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAmbientJudgments,+ },+ {+ method: "GET",+ path: "/v1/admin/ack-emoji-picks",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAckEmojiPicks,+ },+ {+ method: "GET",+ path: "/v1/admin/files/read",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.files.read", summary: "read a stored file by ?id=" },+ },+ handle: readAdminFile,+ },+ {+ method: "GET",+ path: "/v1/admin/files/download",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.files.read", summary: "download a stored file by ?id=" },+ },+ handle: downloadAdminFile,+ },+ { method: "POST", path: "/v1/admin/files/upload", auth: "either", handle: uploadAdminFile },+ {+ method: "GET",+ path: "/v1/admin/files",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.files.read", summary: "list a scope's document store" },+ },+ handle: listAdminFiles,+ },+ {+ method: "GET",+ path: "/v1/admin/errors",+ auth: "either",+ admin: { privateRead: "always", unattended: { grant: "admin.sessions.read", summary: "read error telemetry" } },+ handle: listAdminErrors,+ },+ {+ method: "GET",+ path: "/v1/admin/audit",+ auth: "either",+ admin: {+ privateRead: "always",+ unattended: { grant: "admin.audit.read", summary: "read security audit events" },+ },+ handle: listAdminAudit,+ },+ {+ method: "GET",+ path: "/v1/admin/security/flags",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listSecurityFlags,+ },+ {+ method: "GET",+ path: "/v1/admin/crons",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAdminArtifacts,+ },+ {+ method: "GET",+ path: "/v1/admin/deployments",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAdminArtifacts,+ },+ {+ method: "GET",+ path: "/v1/admin/skills",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listAdminArtifacts,+ },+ { method: "PUT", path: "/v1/admin/crons/:id/runtime", auth: "either", handle: putAdminCronRuntime },+ { method: "PUT", path: "/v1/admin/crons/:id/destination", auth: "either", handle: putAdminCronDestination },+ {+ method: "GET",+ path: "/v1/admin/skills/:id",+ auth: "either",+ admin: { privateRead: "always" },+ handle: getAdminSkill,+ },+ { method: "DELETE", path: "/v1/admin/skills/:id", auth: "either", handle: archiveAdminSkill },+ { method: "GET", path: "/v1/admin/memory/scopes", auth: "either", handle: listMemoryScopes },+ {+ method: "GET",+ path: "/v1/admin/memory",+ auth: "either",+ admin: { privateRead: "unless-org-scope" },+ handle: adminMemory,+ },+ { method: "POST", path: "/v1/admin/memory", auth: "either", handle: adminMemory },+ { method: "PATCH", path: "/v1/admin/memory", auth: "either", handle: adminMemory },+ { method: "DELETE", path: "/v1/admin/memory", auth: "either", handle: adminMemory },+ { method: "GET", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },+ { method: "POST", path: "/v1/admin/sandboxes/:scopeId", auth: "either", handle: manageSandboxResources },+ { method: "GET", path: "/v1/admin/users", auth: "either", handle: listUsers },+ { method: "GET", path: "/v1/admin/directory", auth: "either", handle: searchDirectory },+ {+ method: "GET",+ path: "/v1/admin/keychain",+ auth: "either",+ admin: { privateRead: "always" },+ handle: listKeychainStatus,+ },+ {+ method: "GET",+ path: "/v1/admin/users/:principalId",+ auth: "either",+ admin: { privateRead: "always" },+ handle: getUserDetail,+ },+ { method: "PUT", path: "/v1/admin/users/:principalId/onboarding", auth: "either", handle: setUserOnboarding },+ { method: "POST", path: "/v1/admin/users/:principalId/reset", auth: "either", handle: resetUserToBrandNew },+ {+ method: "GET",+ path: "/v1/admin/principal-links",+ auth: "either",+ admin: { agent: { portalOnly: LINKS } },+ handle: listPrincipalLinks,+ },+ {+ method: "POST",+ path: "/v1/admin/principal-links",+ auth: "either",+ admin: { agent: { portalOnly: LINKS } },+ handle: createPrincipalLink,+ },+ {+ method: "DELETE",+ path: "/v1/admin/principal-links/:principalId",+ auth: "either",+ admin: { agent: { portalOnly: LINKS } },+ handle: deletePrincipalLink,+ },+ {+ method: "POST",+ path: "/v1/admin/grants",+ auth: "either",+ admin: { agent: { portalOnly: GRANTS } },+ handle: createAdminGrant,+ },+ {+ method: "DELETE",+ path: "/v1/admin/grants/:principalId",+ auth: "either",+ admin: { agent: { portalOnly: GRANTS } },+ handle: revokeAdminGrant,+ },+ { method: "POST", path: "/v1/admin/users/invite", auth: "either", handle: inviteTeammate },+ { method: "POST", path: "/v1/admin/external-users", auth: "either", handle: inviteExternalUser },+ { method: "DELETE", path: "/v1/admin/external-users/:email", auth: "either", handle: revokeExternalUser },+ {+ method: "POST",+ path: "/v1/admin/impersonate/stop",+ auth: "either",+ admin: { agent: { portalOnly: IMPERSONATE } },+ handle: stopImpersonation,+ },+ {+ method: "POST",+ path: "/v1/admin/impersonate",+ auth: "either",+ admin: { agent: { portalOnly: IMPERSONATE } },+ handle: startImpersonation,+ },+ ]),];export const adminRoutes: ReadonlyArray<Route<ApiCtx>> = routes.map((r) => ({ ...r, handle: timed(r.handle) }));diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.tsindex 489aafd38..806b791fd 100644--- a/src/api/routes/admin/scope-config.ts+++ b/src/api/routes/admin/scope-config.ts@@ -47,19 +47,6 @@ export async function putScopeConfig(ctx: ApiCtx): Promise<void> {const actor = await authorizeAdmin(ctx, targetScope);if (!actor) return;- if (- [- "base-model",- "runtime",- "cron-runtime",- "subagent-runtime",- "fallback-runtime",- "webui-models",- "browse-model",- "auto-flagger",- ].includes(resource)- )- await deps.refreshModels?.();const withScopeMutationLock = async <T>(fn: () => Promise<T>): Promise<T> =>deps.advisoryLock ? deps.advisoryLock.withLock(`admin-governance:${targetScope}`, fn) : fn();@@ -104,6 +91,7 @@ export async function putScopeConfig(ctx: ApiCtx): Promise<void> {const desc = ADMIN_RESOURCE_BY_ID.get(resource);if (!desc) return sendJson(res, 404, { error: "not_found", message: `unknown admin resource: ${resource}` });+ if (desc.refreshesModels) await deps.refreshModels?.();return withScopeMutationLock(async () => {try {const result = await desc.apply(ctx, actor, targetScope);diff --git a/src/api/routes/context.ts b/src/api/routes/context.tsindex 560a5a58c..cdc791f15 100644--- a/src/api/routes/context.ts+++ b/src/api/routes/context.ts@@ -255,7 +255,14 @@ async function fulfillContextRequest(ctx: ApiCtx): Promise<void> {}export const contextRoutes: ReadonlyArray<Route<ApiCtx>> = [- { method: "POST", path: "/v1/surface-context", actor: "system", auth: "either", handle: createSurfaceContextRequest },+ {+ method: "POST",+ path: "/v1/surface-context",+ actor: "system",+ auth: "either",+ allowedInStrict: true,+ handle: createSurfaceContextRequest,+ },{ method: "POST", path: "/v1/surface-file", actor: "system", auth: "either", handle: createSurfaceFileRequest },{ method: "GET", path: "/v1/surface-context/pending", auth: "source", handle: listPendingContextRequests },{diff --git a/src/api/routes/file-uploads.ts b/src/api/routes/file-uploads.tsindex 4ace362c0..3bdedae37 100644--- a/src/api/routes/file-uploads.ts+++ b/src/api/routes/file-uploads.ts@@ -5,52 +5,31 @@ import { FileUploadError } from "../../files/file-upload-store.ts";import { isObj, audit } from "./shared.ts";import { withActor, type ApiCtx, type Route } from "./route.ts";-async function handleUpload(ctx: ApiCtx): Promise<void> {- const { res, deps, app, capability, actor, params, method, pathname } = ctx;- const uploads = deps.fileUploads;- if (!uploads)- return sendJson(res, 501, { error: "not_configured", message: "direct uploads require S3 and Postgres" });- const body = isObj(ctx.body) ? ctx.body : {};- const actorId = capability?.actorId ?? actor?.p;- if (!actorId) return sendJson(res, 401, { error: "actor_required" });- try {- if (!deps.filesDirectUploadsEnabled && !params.id && pathname !== "/v1/files/upload-client")- return sendJson(res, 503, { error: "uploads_disabled", message: "new direct uploads are disabled" });- if (pathname === "/v1/files/upload-client") {- const script = await readFile(new URL("../../files/upload-client.py", import.meta.url), "utf8");- res.writeHead(200, { "content-type": "text/x-python; charset=utf-8", "cache-control": "private, max-age=300" });- res.end(script);- return;- }- if (!params.id) {- const targetScope =- typeof body.scopeId === "string"- ? (body.scopeId as ScopeId)- : (capability?.scopeId ?? scopeId("personal", actorId));- if ((capability && targetScope !== capability.scopeId) || !(await app.belongsToScope(actorId, targetScope)))- return sendJson(res, 403, { error: "forbidden" });- if (- typeof body.name !== "string" ||- !body.name.trim() ||- body.name.length > 512 ||- (body.mimetype != null && (typeof body.mimetype !== "string" || body.mimetype.length > 256))- )- throw new FileUploadError("name and optional mimetype must be valid strings");- const rate = await deps.rateLimiter?.check(`file-uploads:${actorId}`);- if (rate && !rate.allowed) return sendJson(res, 429, { error: "rate_limited" });- const upload = await uploads.begin({- actorId,- scopeId: targetScope,- name: body.name,- mimetype: typeof body.mimetype === "string" ? body.mimetype : "",- sizeBytes: body.sizeBytes as number,- checksums: body.checksums as string[],- ...(body.requestId != null ? { requestId: body.requestId as string } : {}),- });- audit(deps, { principalId: actorId, action: "file.upload.begin", resource: upload.id, scopeLabel: targetScope });- return sendJson(res, 201, { upload });+type Uploads = NonNullable<ApiCtx["deps"]["fileUploads"]>;+type Upload = NonNullable<Awaited<ReturnType<Uploads["get"]>>>;++const uploadRoute =+ (handle: (ctx: ApiCtx, uploads: Uploads, actorId: string) => Promise<void>) =>+ async (ctx: ApiCtx): Promise<void> => {+ const { res, deps, capability, actor } = ctx;+ const uploads = deps.fileUploads;+ if (!uploads)+ return sendJson(res, 501, { error: "not_configured", message: "direct uploads require S3 and Postgres" });+ const actorId = capability?.actorId ?? actor?.p;+ if (!actorId) return sendJson(res, 401, { error: "actor_required" });+ try {+ return await handle(ctx, uploads, actorId);+ } catch (error) {+ if (error instanceof FileUploadError)+ return sendJson(res, error.status, { error: error.code, message: error.message });+ throw error;}- const upload = await uploads.get(params.id);+ };++const ownedUpload = (handle: (ctx: ApiCtx, uploads: Uploads, upload: Upload, actorId: string) => Promise<void>) =>+ uploadRoute(async (ctx, uploads, actorId) => {+ const { res, app, capability, params } = ctx;+ const upload = await uploads.get(params.id!);if (!upload ||upload.actorId !== actorId ||@@ -58,30 +37,73 @@ async function handleUpload(ctx: ApiCtx): Promise<void> {!(await app.belongsToScope(actorId, upload.scopeId)))return sendJson(res, 404, { error: "not_found" });- if (method === "GET") return sendJson(res, 200, { upload });- if (params.part) return sendJson(res, 200, await uploads.sign(upload.id, Number(params.part)));- if (pathname.endsWith("/complete")) {- const file = await uploads.complete(upload.id);- audit(deps, { principalId: actorId, action: "file.upload", resource: file.path, scopeLabel: upload.scopeId });- return sendJson(res, 200, { file, contentUrl: `/v1/files/${file.id}/content` });- }- await uploads.abort(upload.id);- audit(deps, { principalId: actorId, action: "file.upload.abort", resource: upload.id, scopeLabel: upload.scopeId });- return sendJson(res, 200, { ok: true });- } catch (error) {- if (error instanceof FileUploadError)- return sendJson(res, error.status, { error: error.code, message: error.message });- throw error;- }-}+ return handle(ctx, uploads, upload, actorId);+ });++const uploadClient = uploadRoute(async ({ res }) => {+ const script = await readFile(new URL("../../files/upload-client.py", import.meta.url), "utf8");+ res.writeHead(200, { "content-type": "text/x-python; charset=utf-8", "cache-control": "private, max-age=300" });+ res.end(script);+});++const beginUpload = uploadRoute(async (ctx, uploads, actorId) => {+ const { res, deps, app, capability } = ctx;+ if (!deps.filesDirectUploadsEnabled)+ return sendJson(res, 503, { error: "uploads_disabled", message: "new direct uploads are disabled" });+ const body = isObj(ctx.body) ? ctx.body : {};+ const targetScope =+ typeof body.scopeId === "string"+ ? (body.scopeId as ScopeId)+ : (capability?.scopeId ?? scopeId("personal", actorId));+ if ((capability && targetScope !== capability.scopeId) || !(await app.belongsToScope(actorId, targetScope)))+ return sendJson(res, 403, { error: "forbidden" });+ if (+ typeof body.name !== "string" ||+ !body.name.trim() ||+ body.name.length > 512 ||+ (body.mimetype != null && (typeof body.mimetype !== "string" || body.mimetype.length > 256))+ )+ throw new FileUploadError("name and optional mimetype must be valid strings");+ const rate = await deps.rateLimiter?.check(`file-uploads:${actorId}`);+ if (rate && !rate.allowed) return sendJson(res, 429, { error: "rate_limited" });+ const upload = await uploads.begin({+ actorId,+ scopeId: targetScope,+ name: body.name,+ mimetype: typeof body.mimetype === "string" ? body.mimetype : "",+ sizeBytes: body.sizeBytes as number,+ checksums: body.checksums as string[],+ ...(body.requestId != null ? { requestId: body.requestId as string } : {}),+ });+ audit(deps, { principalId: actorId, action: "file.upload.begin", resource: upload.id, scopeLabel: targetScope });+ return sendJson(res, 201, { upload });+});++const getUpload = ownedUpload(async ({ res }, _uploads, upload) => sendJson(res, 200, { upload }));++const signPart = ownedUpload(async ({ res, params }, uploads, upload) =>+ sendJson(res, 200, await uploads.sign(upload.id, Number(params.part))),+);++const completeUpload = ownedUpload(async ({ res, deps }, uploads, upload, actorId) => {+ const file = await uploads.complete(upload.id);+ audit(deps, { principalId: actorId, action: "file.upload", resource: file.path, scopeLabel: upload.scopeId });+ return sendJson(res, 200, { file, contentUrl: `/v1/files/${file.id}/content` });+});++const abortUpload = ownedUpload(async ({ res, deps }, uploads, upload, actorId) => {+ await uploads.abort(upload.id);+ audit(deps, { principalId: actorId, action: "file.upload.abort", resource: upload.id, scopeLabel: upload.scopeId });+ return sendJson(res, 200, { ok: true });+});export const fileUploadRoutes: ReadonlyArray<Route<ApiCtx>> = [- { method: "GET", path: "/v1/files/upload-client", actor: "query.viewer", auth: "either", handle: handleUpload },- { method: "GET", path: "/v1/files/uploads/:id", actor: "query.viewer", auth: "either", handle: handleUpload },+ { method: "GET", path: "/v1/files/upload-client", actor: "query.viewer", auth: "either", handle: uploadClient },+ { method: "GET", path: "/v1/files/uploads/:id", actor: "query.viewer", auth: "either", handle: getUpload },...withActor("body.principalId", [- { method: "POST", path: "/v1/files/uploads", auth: "either", handle: handleUpload },- { method: "POST", path: "/v1/files/uploads/:id/parts/:part", auth: "either", handle: handleUpload },- { method: "POST", path: "/v1/files/uploads/:id/complete", auth: "either", handle: handleUpload },- { method: "DELETE", path: "/v1/files/uploads/:id", auth: "either", handle: handleUpload },+ { method: "POST", path: "/v1/files/uploads", auth: "either", handle: beginUpload },+ { method: "POST", path: "/v1/files/uploads/:id/parts/:part", auth: "either", handle: signPart },+ { method: "POST", path: "/v1/files/uploads/:id/complete", auth: "either", handle: completeUpload },+ { method: "DELETE", path: "/v1/files/uploads/:id", auth: "either", handle: abortUpload },]),];diff --git a/src/api/routes/keychain.ts b/src/api/routes/keychain.tsindex 5e2d5b4dc..ca04a4f9a 100644--- a/src/api/routes/keychain.ts+++ b/src/api/routes/keychain.ts@@ -11,6 +11,7 @@ import { approvalCardDestination } from "../../credentials/keychain-approval.ts"import { sendJson } from "../http.ts";import { normalizeInboundExpiresAt } from "../expiry.ts";import type { ApiCtx, Route } from "./route.ts";+import type { CapabilityClaims } from "../../auth/capability-token.ts";import { audit, resolveCapabilityDestination } from "./shared.ts";import { swallowAs } from "../../util/errors.ts";import { cronIdOf } from "../../sessions/session-store.ts";@@ -61,239 +62,239 @@ async function resolveScopeNames(return names;}-async function handleKeychain(ctx: ApiCtx): Promise<void> {- const { res, app, deps, pathname, method, body, capability, params } = ctx;- if (!deps.keychain)- return sendJson(res, 503, {- error: "keychain_unavailable",- message: "The keychain isn't set up on this server. An operator needs to set CONNECTOR_SECRET_KEY.",- });- if (!capability)- return sendJson(res, 401, { error: "unauthorized", message: "keychain routes require an agent capability token" });- const kc = deps.keychain;- const actorId = capability.actorId;- try {- if (method === "POST" && pathname === "/v1/keychain/credentials") {- const b = body as {- service?: unknown;- secret?: unknown;- files?: unknown;- envKey?: unknown;- fields?: unknown;- target?: unknown;- host?: unknown;- accountLabel?: unknown;- origin?: unknown;- expiresAt?: unknown;- };- const expiresAt = normalizeInboundExpiresAt(b.expiresAt);- if (!expiresAt.ok) return sendJson(res, 400, { error: "bad_request", message: expiresAt.message });- const files = Array.isArray(b.files)- ? (b.files as unknown[])- .filter(- (f): f is CredentialFile =>- typeof (f as CredentialFile)?.path === "string" &&- typeof (f as CredentialFile)?.contentBase64 === "string",- )- .map((f) => ({ path: f.path, contentBase64: f.contentBase64, rawMode: (f as { mode?: unknown }).mode }))- : undefined;- const badMode = files?.find(- (f) =>- f.rawMode !== undefined &&- (typeof f.rawMode !== "number" || !Number.isInteger(f.rawMode) || f.rawMode < 0 || f.rawMode > 0o777),- );- if (badMode) {- return sendJson(res, 400, {- error: "bad_request",- message: `files[].mode must be an integer between 0 and 511 (octal 0o777); got ${JSON.stringify(badMode.rawMode)} for ${badMode.path}`,- });- }- const cleanFiles: CredentialFile[] | undefined = files?.map(({ path, contentBase64, rawMode }) => ({- path,- contentBase64,- ...(typeof rawMode === "number" ? { mode: rawMode } : {}),- }));- let fields: CredentialFieldInput[] | undefined;- if (b.fields !== undefined) {- if (- !Array.isArray(b.fields) ||- b.fields.length === 0 ||- b.fields.some(- (f) =>- typeof (f as CredentialFieldInput)?.envKey !== "string" ||- typeof (f as CredentialFieldInput)?.value !== "string",- )- ) {- return sendJson(res, 400, { error: "bad_request", message: "each field needs string envKey and value" });- }- fields = b.fields as CredentialFieldInput[];- }- if (typeof b.service !== "string" || (typeof b.secret !== "string" && !files?.length && !fields?.length)) {- return sendJson(res, 400, {- error: "bad_request",- message: "service plus secret, files[], or fields[] required",- });- }- const meta = await kc.save({- ownerId: actorId,- service: b.service,- ...(typeof b.secret === "string" ? { secret: b.secret } : {}),- ...(cleanFiles?.length ? { files: cleanFiles } : {}),- ...(fields?.length ? { fields } : {}),- ...(typeof b.envKey === "string" ? { envKey: b.envKey } : {}),- ...(typeof b.target === "string" ? { target: b.target } : {}),- ...(typeof b.host === "string" ? { host: b.host } : {}),- ...(typeof b.accountLabel === "string" ? { accountLabel: b.accountLabel } : {}),- origin: typeof b.origin === "string" ? b.origin : `agent-session:${capability.scopeId}`,- ...(expiresAt.value !== undefined ? { expiresAt: expiresAt.value } : {}),+const keychainRoute =+ (handle: (ctx: ApiCtx, kc: NonNullable<ApiCtx["deps"]["keychain"]>, capability: CapabilityClaims) => Promise<void>) =>+ async (ctx: ApiCtx): Promise<void> => {+ const { res, deps, capability } = ctx;+ if (!deps.keychain)+ return sendJson(res, 503, {+ error: "keychain_unavailable",+ message: "The keychain isn't set up on this server. An operator needs to set CONNECTOR_SECRET_KEY.",});- audit(deps, {- principalId: actorId,- action: "keychain.save",- resource: `${meta.service}:${meta.id}`,- scopeLabel: capability.scopeId,+ if (!capability)+ return sendJson(res, 401, {+ error: "unauthorized",+ message: "keychain routes require an agent capability token",});- return sendJson(res, 200, { credential: meta });+ try {+ return await handle(ctx, deps.keychain, capability);+ } catch (e) {+ if (e instanceof KeychainError) return sendJson(res, e.status, { error: "keychain", message: e.message });+ throw e;}+ };- if (method === "GET" && pathname === "/v1/keychain/credentials") {- return sendJson(res, 200, { credentials: await kc.listByOwner(actorId) });+const saveCredential = keychainRoute(async ({ res, deps, body }, kc, { actorId, scopeId }) => {+ const b = body as {+ service?: unknown;+ secret?: unknown;+ files?: unknown;+ envKey?: unknown;+ fields?: unknown;+ target?: unknown;+ host?: unknown;+ accountLabel?: unknown;+ origin?: unknown;+ expiresAt?: unknown;+ };+ const expiresAt = normalizeInboundExpiresAt(b.expiresAt);+ if (!expiresAt.ok) return sendJson(res, 400, { error: "bad_request", message: expiresAt.message });+ const files = Array.isArray(b.files)+ ? (b.files as unknown[])+ .filter(+ (f): f is CredentialFile =>+ typeof (f as CredentialFile)?.path === "string" && typeof (f as CredentialFile)?.contentBase64 === "string",+ )+ .map((f) => ({ path: f.path, contentBase64: f.contentBase64, rawMode: (f as { mode?: unknown }).mode }))+ : undefined;+ const badMode = files?.find(+ (f) =>+ f.rawMode !== undefined &&+ (typeof f.rawMode !== "number" || !Number.isInteger(f.rawMode) || f.rawMode < 0 || f.rawMode > 0o777),+ );+ if (badMode) {+ return sendJson(res, 400, {+ error: "bad_request",+ message: `files[].mode must be an integer between 0 and 511 (octal 0o777); got ${JSON.stringify(badMode.rawMode)} for ${badMode.path}`,+ });+ }+ const cleanFiles: CredentialFile[] | undefined = files?.map(({ path, contentBase64, rawMode }) => ({+ path,+ contentBase64,+ ...(typeof rawMode === "number" ? { mode: rawMode } : {}),+ }));+ let fields: CredentialFieldInput[] | undefined;+ if (b.fields !== undefined) {+ if (+ !Array.isArray(b.fields) ||+ b.fields.length === 0 ||+ b.fields.some(+ (f) =>+ typeof (f as CredentialFieldInput)?.envKey !== "string" ||+ typeof (f as CredentialFieldInput)?.value !== "string",+ )+ ) {+ return sendJson(res, 400, { error: "bad_request", message: "each field needs string envKey and value" });}+ fields = b.fields as CredentialFieldInput[];+ }+ if (typeof b.service !== "string" || (typeof b.secret !== "string" && !files?.length && !fields?.length)) {+ return sendJson(res, 400, {+ error: "bad_request",+ message: "service plus secret, files[], or fields[] required",+ });+ }+ const meta = await kc.save({+ ownerId: actorId,+ service: b.service,+ ...(typeof b.secret === "string" ? { secret: b.secret } : {}),+ ...(cleanFiles?.length ? { files: cleanFiles } : {}),+ ...(fields?.length ? { fields } : {}),+ ...(typeof b.envKey === "string" ? { envKey: b.envKey } : {}),+ ...(typeof b.target === "string" ? { target: b.target } : {}),+ ...(typeof b.host === "string" ? { host: b.host } : {}),+ ...(typeof b.accountLabel === "string" ? { accountLabel: b.accountLabel } : {}),+ origin: typeof b.origin === "string" ? b.origin : `agent-session:${scopeId}`,+ ...(expiresAt.value !== undefined ? { expiresAt: expiresAt.value } : {}),+ });+ audit(deps, {+ principalId: actorId,+ action: "keychain.save",+ resource: `${meta.service}:${meta.id}`,+ scopeLabel: scopeId,+ });+ return sendJson(res, 200, { credential: meta });+});- if (method === "GET" && pathname === "/v1/keychain/overview") {- const credentials = await kc.listByOwner(actorId);- const connectorCredentials = (await kc.listConnectorsByOwners([actorId])).get(actorId) ?? [];- const grants = await kc.listGrants({ ownerId: actorId });- const asks = (await kc.listAsks({ ownerId: actorId })).filter((ask) => ask.status === "pending");- const scopeNames = await resolveScopeNames(app, deps, [- ...grants.map((grant) => grant.audienceScopeId),- ...asks.map((ask) => ask.requesterScopeId),- ]);- return sendJson(res, 200, { credentials, connectorCredentials, grants, asks, scopeNames });- }+const listCredentials = keychainRoute(async ({ res }, kc, { actorId }) => {+ return sendJson(res, 200, { credentials: await kc.listByOwner(actorId) });+});- if (method === "DELETE" && pathname.startsWith("/v1/keychain/credentials/")) {- const id = params.id!;- const ok = await kc.remove(actorId, id);- if (ok)- audit(deps, { principalId: actorId, action: "keychain.delete", resource: id, scopeLabel: capability.scopeId });- return ok ? sendJson(res, 200, { ok: true }) : sendJson(res, 404, { error: "not_found" });- }+const keychainOverview = keychainRoute(async ({ res, app, deps }, kc, { actorId }) => {+ const credentials = await kc.listByOwner(actorId);+ const connectorCredentials = (await kc.listConnectorsByOwners([actorId])).get(actorId) ?? [];+ const grants = await kc.listGrants({ ownerId: actorId });+ const asks = (await kc.listAsks({ ownerId: actorId })).filter((ask) => ask.status === "pending");+ const scopeNames = await resolveScopeNames(app, deps, [+ ...grants.map((grant) => grant.audienceScopeId),+ ...asks.map((ask) => ask.requesterScopeId),+ ]);+ return sendJson(res, 200, { credentials, connectorCredentials, grants, asks, scopeNames });+});- if (method === "GET" && pathname === "/v1/keychain/grants") {- const mine = await kc.listGrants({ ownerId: actorId });- const here = await kc.listGrants({ audienceScopeId: capability.scopeId });- const byId = new Map([...mine, ...here].map((g) => [g.id, g]));- return sendJson(res, 200, { grants: [...byId.values()] });- }+const deleteCredential = keychainRoute(async ({ res, deps, params }, kc, { actorId, scopeId }) => {+ const id = params.id!;+ const ok = await kc.remove(actorId, id);+ if (ok) audit(deps, { principalId: actorId, action: "keychain.delete", resource: id, scopeLabel: scopeId });+ return ok ? sendJson(res, 200, { ok: true }) : sendJson(res, 404, { error: "not_found" });+});- if (method === "POST" && pathname.startsWith("/v1/keychain/grants/") && pathname.endsWith("/revoke")) {- const id = params.id!;- const ok = await kc.revokeGrant(actorId, id);- if (ok)- audit(deps, { principalId: actorId, action: "keychain.revoke", resource: id, scopeLabel: capability.scopeId });- return ok ? sendJson(res, 200, { ok: true }) : sendJson(res, 404, { error: "not_found" });- }+const listGrants = keychainRoute(async ({ res }, kc, { actorId, scopeId }) => {+ const mine = await kc.listGrants({ ownerId: actorId });+ const here = await kc.listGrants({ audienceScopeId: scopeId });+ const byId = new Map([...mine, ...here].map((g) => [g.id, g]));+ return sendJson(res, 200, { grants: [...byId.values()] });+});- if (method === "POST" && pathname === "/v1/keychain/asks") {- const b = body as { credential?: unknown; purpose?: unknown; requestedMode?: unknown; expiresAt?: unknown };- const expiresAt = normalizeInboundExpiresAt(b.expiresAt);- if (!expiresAt.ok) return sendJson(res, 400, { error: "bad_request", message: expiresAt.message });- if (- typeof b.credential !== "string" ||- typeof b.purpose !== "string" ||- (b.requestedMode !== undefined && b.requestedMode !== "once" && b.requestedMode !== "standing")- ) {- return sendJson(res, 400, {- error: "bad_request",- message: 'expected { credential, purpose, requestedMode?: "once"|"standing" }',- });- }- const scope = parseScopeId(capability.scopeId);- if (scope.kind !== "channel" && scope.kind !== "personal" && scope.kind !== "group") {- return sendJson(res, 403, { error: "forbidden", message: "asks require a personal or shared conversation" });- }- const cred = await kc.getCredential(b.credential);- if (!cred) return sendJson(res, 404, { error: "not_found", message: "unknown credential" });- const requester = await app.directoryMember(actorId);- if (- !(await app.belongsToScope(actorId, capability.scopeId)) ||- !(await app.belongsToScope(cred.ownerId, capability.scopeId)) ||- (scope.kind !== "personal" &&- (requester?.type !== "internal" || (await app.directoryMember(cred.ownerId))?.type !== "internal"))- ) {- return sendJson(res, 403, {- error: "forbidden",- message: "the requester and credential owner must have current access to this conversation",- });- }- const context = (await app.listContexts(cred.ownerId)).find((c) => c.scopeId === capability.scopeId);- const cronId = cronIdOf(capability.threadRef);- const cron = cronId ? await app.getCron(cronId) : null;- const dest = resolveCapabilityDestination(capability, undefined);- const requesterDestination =- (dest.ok && dest.destination) || (cron?.ownerScopeId === capability.scopeId ? cron.destination : undefined);- const originRun = capability.runId ? await deps.runs?.get(capability.runId) : null;- const requesterSeq = originRun && originRun.sessionId === capability.threadRef ? originRun?.turnUserSeq : null;- const requesterMessageTs =- originRun && originRun.sessionId === capability.threadRef && originRun.request.origin.kind === "human"- ? originRun.request.origin.messageTs- : undefined;- const { ask, existing } = await kc.createAsk({- ...(capability.triggered ? { triggered: true } : {}),- credentialId: cred.id,- requesterId: actorId,- requesterScopeId: capability.scopeId,- ...(requesterSeq != null ? { requesterSeq } : {}),- ...(requesterMessageTs ? { requesterMessageTs } : {}),- ...(requesterDestination ? { requesterDestination } : {}),- ...(capability.threadRef ? { requesterThreadRef: capability.threadRef } : {}),- purpose: b.purpose,- ...(b.requestedMode !== undefined ? { requestedMode: b.requestedMode as GrantMode } : {}),- ...(expiresAt.value !== undefined ? { expiresAt: expiresAt.value } : {}),- });- const notice = renderAskNotice({- ask,- credential: cred,- ...(requester?.displayName ? { requesterName: requester.displayName } : {}),- ...(scope.kind === "channel" && context?.name ? { channelName: context.name } : {}),- ...(scope.kind === "group" && context?.name ? { scopeName: context.name } : {}),- ...(cron?.ownerScopeId === capability.scopeId ? { taskTitle: cron.title ?? cron.id } : {}),- });- const cardDestination = approvalCardDestination(ask);- if (cardDestination)- await deps.deliveries?.enqueue({- destination: cardDestination,- text: notice,- idempotencyKey: `ask:${ask.id}:notice`,- });- if (!existing) {- audit(deps, {- principalId: actorId,- action: "keychain.ask",- resource: `${ask.id} (${cred.service}:${cred.id}→${cred.ownerId})`,- scopeLabel: capability.scopeId,- });- }- return sendJson(res, 200, { ask, existing });- }+const revokeGrant = keychainRoute(async ({ res, deps, params }, kc, { actorId, scopeId }) => {+ const id = params.id!;+ const ok = await kc.revokeGrant(actorId, id);+ if (ok) audit(deps, { principalId: actorId, action: "keychain.revoke", resource: id, scopeLabel: scopeId });+ return ok ? sendJson(res, 200, { ok: true }) : sendJson(res, 404, { error: "not_found" });+});- if (method === "GET" && pathname === "/v1/keychain/asks") {- const all = await kc.listAsks({});- const asks = all.filter(- (a) =>- samePerson(a.requesterId, actorId) ||- samePerson(a.ownerId, actorId) ||- a.requesterScopeId === capability.scopeId,- );- return sendJson(res, 200, { asks });- }- } catch (e) {- if (e instanceof KeychainError) return sendJson(res, e.status, { error: "keychain", message: e.message });- throw e;+const createAsk = keychainRoute(async (ctx, kc, capability) => {+ const { res, app, deps, body } = ctx;+ const actorId = capability.actorId;+ const b = body as { credential?: unknown; purpose?: unknown; requestedMode?: unknown; expiresAt?: unknown };+ const expiresAt = normalizeInboundExpiresAt(b.expiresAt);+ if (!expiresAt.ok) return sendJson(res, 400, { error: "bad_request", message: expiresAt.message });+ if (+ typeof b.credential !== "string" ||+ typeof b.purpose !== "string" ||+ (b.requestedMode !== undefined && b.requestedMode !== "once" && b.requestedMode !== "standing")+ ) {+ return sendJson(res, 400, {+ error: "bad_request",+ message: 'expected { credential, purpose, requestedMode?: "once"|"standing" }',+ });}- return sendJson(res, 404, { error: "not_found" });-}+ const scope = parseScopeId(capability.scopeId);+ if (scope.kind !== "channel" && scope.kind !== "personal" && scope.kind !== "group") {+ return sendJson(res, 403, { error: "forbidden", message: "asks require a personal or shared conversation" });+ }+ const cred = await kc.getCredential(b.credential);+ if (!cred) return sendJson(res, 404, { error: "not_found", message: "unknown credential" });+ const requester = await app.directoryMember(actorId);+ if (+ !(await app.belongsToScope(actorId, capability.scopeId)) ||+ !(await app.belongsToScope(cred.ownerId, capability.scopeId)) ||+ (scope.kind !== "personal" &&+ (requester?.type !== "internal" || (await app.directoryMember(cred.ownerId))?.type !== "internal"))+ ) {+ return sendJson(res, 403, {+ error: "forbidden",+ message: "the requester and credential owner must have current access to this conversation",+ });+ }+ const context = (await app.listContexts(cred.ownerId)).find((c) => c.scopeId === capability.scopeId);+ const cronId = cronIdOf(capability.threadRef);+ const cron = cronId ? await app.getCron(cronId) : null;+ const dest = resolveCapabilityDestination(capability, undefined);+ const requesterDestination =+ (dest.ok && dest.destination) || (cron?.ownerScopeId === capability.scopeId ? cron.destination : undefined);+ const originRun = capability.runId ? await deps.runs?.get(capability.runId) : null;+ const requesterSeq = originRun && originRun.sessionId === capability.threadRef ? originRun?.turnUserSeq : null;+ const requesterMessageTs =+ originRun && originRun.sessionId === capability.threadRef && originRun.request.origin.kind === "human"+ ? originRun.request.origin.messageTs+ : undefined;+ const { ask, existing } = await kc.createAsk({+ ...(capability.triggered ? { triggered: true } : {}),+ credentialId: cred.id,+ requesterId: actorId,+ requesterScopeId: capability.scopeId,+ ...(requesterSeq != null ? { requesterSeq } : {}),+ ...(requesterMessageTs ? { requesterMessageTs } : {}),+ ...(requesterDestination ? { requesterDestination } : {}),+ ...(capability.threadRef ? { requesterThreadRef: capability.threadRef } : {}),+ purpose: b.purpose,+ ...(b.requestedMode !== undefined ? { requestedMode: b.requestedMode as GrantMode } : {}),+ ...(expiresAt.value !== undefined ? { expiresAt: expiresAt.value } : {}),+ });+ const notice = renderAskNotice({+ ask,+ credential: cred,+ ...(requester?.displayName ? { requesterName: requester.displayName } : {}),+ ...(scope.kind === "channel" && context?.name ? { channelName: context.name } : {}),+ ...(scope.kind === "group" && context?.name ? { scopeName: context.name } : {}),+ ...(cron?.ownerScopeId === capability.scopeId ? { taskTitle: cron.title ?? cron.id } : {}),+ });+ const cardDestination = approvalCardDestination(ask);+ if (cardDestination)+ await deps.deliveries?.enqueue({+ destination: cardDestination,+ text: notice,+ idempotencyKey: `ask:${ask.id}:notice`,+ });+ if (!existing) {+ audit(deps, {+ principalId: actorId,+ action: "keychain.ask",+ resource: `${ask.id} (${cred.service}:${cred.id}→${cred.ownerId})`,+ scopeLabel: capability.scopeId,+ });+ }+ return sendJson(res, 200, { ask, existing });+});++const listAsks = keychainRoute(async ({ res }, kc, { actorId, scopeId }) => {+ const all = await kc.listAsks({});+ const asks = all.filter(+ (a) => samePerson(a.requesterId, actorId) || samePerson(a.ownerId, actorId) || a.requesterScopeId === scopeId,+ );+ return sendJson(res, 200, { asks });+});async function handleApproval(ctx: ApiCtx): Promise<void> {const { res, deps, body, params } = ctx;@@ -315,13 +316,13 @@ async function handleApproval(ctx: ApiCtx): Promise<void> {}export const keychainRoutes: ReadonlyArray<Route<ApiCtx>> = [- { method: "POST", path: "/v1/keychain/credentials", actor: "system", auth: "either", handle: handleKeychain },- { method: "GET", path: "/v1/keychain/credentials", auth: "either", handle: handleKeychain },- { method: "GET", path: "/v1/keychain/overview", auth: "either", handle: handleKeychain },- { method: "DELETE", path: "/v1/keychain/credentials/:id", actor: "system", auth: "either", handle: handleKeychain },- { method: "GET", path: "/v1/keychain/grants", auth: "either", handle: handleKeychain },- { method: "POST", path: "/v1/keychain/grants/:id/revoke", actor: "system", auth: "either", handle: handleKeychain },- { method: "POST", path: "/v1/keychain/asks", actor: "system", auth: "either", handle: handleKeychain },- { method: "GET", path: "/v1/keychain/asks", auth: "either", handle: handleKeychain },+ { method: "POST", path: "/v1/keychain/credentials", actor: "system", auth: "either", handle: saveCredential },+ { method: "GET", path: "/v1/keychain/credentials", auth: "either", handle: listCredentials },+ { method: "GET", path: "/v1/keychain/overview", auth: "either", handle: keychainOverview },+ { method: "DELETE", path: "/v1/keychain/credentials/:id", actor: "system", auth: "either", handle: deleteCredential },+ { method: "GET", path: "/v1/keychain/grants", auth: "either", handle: listGrants },+ { method: "POST", path: "/v1/keychain/grants/:id/revoke", actor: "system", auth: "either", handle: revokeGrant },+ { method: "POST", path: "/v1/keychain/asks", actor: "system", auth: "either", handle: createAsk },+ { method: "GET", path: "/v1/keychain/asks", auth: "either", handle: listAsks },{ method: "POST", path: "/v1/keychain/approvals/:id", auth: "source", handle: handleApproval },];diff --git a/src/api/routes/projects.ts b/src/api/routes/projects.tsindex 88f397dd7..86c314c2d 100644--- a/src/api/routes/projects.ts+++ b/src/api/routes/projects.ts@@ -109,12 +109,24 @@ async function clearProjectSlackChannel(ctx: ApiCtx): Promise<void> {export const projectRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/projects", actor: "query.principalId", auth: "either", handle: listProjects },- { method: "PATCH", path: "/v1/projects/:id", auth: "either", handle: renameProject },+ { method: "PATCH", path: "/v1/projects/:id", auth: "either", allowedInStrict: true, handle: renameProject },{ method: "PUT", path: "/v1/projects/:id/slack-channel", auth: "either", handle: setProjectSlackChannel },{ method: "DELETE", path: "/v1/projects/:id/slack-channel", auth: "either", handle: clearProjectSlackChannel },...withActor("body.principalId", [- { method: "POST", path: "/v1/projects", auth: "either", handle: createProject },- { method: "POST", path: "/v1/projects/:id/members", auth: "either", handle: addProjectMember },- { method: "DELETE", path: "/v1/projects/:id/members/:memberId", auth: "either", handle: removeProjectMember },+ { method: "POST", path: "/v1/projects", auth: "either", allowedInStrict: true, handle: createProject },+ {+ method: "POST",+ path: "/v1/projects/:id/members",+ auth: "either",+ allowedInStrict: true,+ handle: addProjectMember,+ },+ {+ method: "DELETE",+ path: "/v1/projects/:id/members/:memberId",+ auth: "either",+ allowedInStrict: true,+ handle: removeProjectMember,+ },]),];diff --git a/src/api/routes/route.ts b/src/api/routes/route.tsindex b5941b786..576b91631 100644--- a/src/api/routes/route.ts+++ b/src/api/routes/route.ts@@ -1,3 +1,4 @@+import type { UNATTENDED_ADMIN_GRANTS } from "../control-service.ts";import type { IncomingMessage, ServerResponse } from "node:http";import { compilePath, findRoute } from "../../../plugins/chassis/src/router.ts";@@ -33,10 +34,18 @@ export type RouteAuth = "either" | "source" | "public" | { aud: string };export type RouteActor = "person" | "system" | `${"query" | "body"}.${string}`;+export interface AdminAccess {+ agent?: "anyone" | { portalOnly: string };+ privateRead?: "always" | "unless-org-scope";+ unattended?: { grant: (typeof UNATTENDED_ADMIN_GRANTS)[number]; summary: string };+}+export type Route<C extends BaseCtx = ApiCtx> = {handle: (ctx: C) => void | Promise<void>;auth: RouteAuth;actor?: RouteActor;+ admin?: AdminAccess;+ allowedInStrict?: true;maxBodyBytes?: number;} & ({ method: string; path: string } | { match: (method: string, pathname: string) => boolean });@@ -44,6 +53,10 @@ export function withActor<C extends BaseCtx>(actor: RouteActor, routes: Route<C>return routes.map((route) => ({ actor, ...route }));}+export function withAdmin<C extends BaseCtx>(routes: Route<C>[]): Route<C>[] {+ return routes.map((route) => ({ actor: "person", admin: {}, ...route }));+}+export async function run<C extends BaseCtx>(route: Route<C>, params: Record<string, string>, ctx: C): Promise<void> {ctx.params = params;await route.handle(ctx);diff --git a/src/api/routes/search.ts b/src/api/routes/search.tsindex 3a124cadb..a1dcc978a 100644--- a/src/api/routes/search.ts+++ b/src/api/routes/search.ts@@ -40,5 +40,5 @@ async function search(ctx: ApiCtx): Promise<void> {return sendJson(ctx.res, 200, result);}export const searchRoutes: ReadonlyArray<Route<ApiCtx>> = [- { method: "POST", path: "/v1/search", auth: "either", handle: search },+ { method: "POST", path: "/v1/search", auth: "either", allowedInStrict: true, handle: search },];diff --git a/src/api/routes/skill-packs.ts b/src/api/routes/skill-packs.tsindex 5027bf690..e0f1d993a 100644--- a/src/api/routes/skill-packs.ts+++ b/src/api/routes/skill-packs.ts@@ -1,5 +1,5 @@import { sendJson } from "../http.ts";-import type { ApiCtx, Route } from "./route.ts";+import { withAdmin, type ApiCtx, type Route } from "./route.ts";import { audit, authorizeAdmin, orgScope } from "./shared.ts";import type { NewSkillPack, SkillPack } from "../../skills/skill-pack-store.ts";import type { PackConfig } from "../../skills/normalize.ts";@@ -181,7 +181,7 @@ async function removePack(ctx: ApiCtx): Promise<void> {sendJson(ctx.res, 200, result);}-export const skillPackRoutes: ReadonlyArray<Route<ApiCtx>> = [+export const skillPackRoutes: ReadonlyArray<Route<ApiCtx>> = withAdmin([{ method: "POST", path: "/v1/admin/skill-packs", auth: "either", handle: registerPack },{ method: "GET", path: "/v1/admin/skill-packs", auth: "either", handle: listPacks },{ method: "GET", path: "/v1/admin/skill-packs/:id/catalog", auth: "either", handle: packCatalog },@@ -189,4 +189,4 @@ export const skillPackRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "POST", path: "/v1/admin/skill-packs/:id/sync", auth: "either", handle: syncPack },{ method: "PATCH", path: "/v1/admin/skill-packs/:id", auth: "either", handle: patchPack },{ method: "DELETE", path: "/v1/admin/skill-packs/:id", auth: "either", handle: removePack },-];+]);diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex bd4764cf3..7627e9e25 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -1,3 +1,4 @@+import type { CapabilityClaims } from "../../auth/capability-token.ts";import { memoryForRequest } from "./memory-access.ts";import type { MemoryEdit, MemoryService } from "../../memory/memory-service.ts";import { suggestedActivityRoutes } from "./suggested-activities.ts";@@ -656,126 +657,137 @@ export function parseFacts(body: unknown): string[] | string {return facts;}-async function agentMemory(ctx: ApiCtx): Promise<void> {- const memory = memoryForRequest(ctx);- const { res, deps, pathname, method, body, capability } = ctx;- if (!capability) return sendJson(res, 401, { error: "unauthorized", message: "agent capability token required" });- if (!memory) return sendJson(res, 404, { error: "not_found" });+type AgentMemoryHandler = (+ ctx: ApiCtx,+ memory: NonNullable<ReturnType<typeof memoryForRequest>>,+ capability: CapabilityClaims,+) => Promise<void>;++const agentMemory =+ (handle: AgentMemoryHandler) =>+ async (ctx: ApiCtx): Promise<void> => {+ const memory = memoryForRequest(ctx);+ const { res, body, capability } = ctx;+ if (!capability) return sendJson(res, 401, { error: "unauthorized", message: "agent capability token required" });+ if (!memory) return sendJson(res, 404, { error: "not_found" });+ if (isObj(body) && ["recipient", "channel", "participants"].some((key) => key in body)) {+ return sendJson(res, 400, {+ error: "bad_request",+ message: "memory can only be changed from its own conversation",+ });+ }+ return handle(ctx, memory, capability);+ };- if (isObj(body) && ["recipient", "channel", "participants"].some((key) => key in body)) {- return sendJson(res, 400, {- error: "bad_request",- message: "memory can only be changed from its own conversation",- });+const searchMemory = agentMemory(async (ctx, memory, capability) => {+ const { res, deps, body } = ctx;+ const b = body as { query?: unknown; limit?: unknown; scope?: unknown };+ if (typeof b.query !== "string" || !b.query.trim()) {+ return sendJson(res, 400, { error: "bad_request", message: "query (string) required" });}-- if (method === "POST" && pathname === "/v1/memory/search") {- const b = body as { query?: unknown; limit?: unknown; scope?: unknown };- if (typeof b.query !== "string" || !b.query.trim()) {- return sendJson(res, 400, { error: "bad_request", message: "query (string) required" });- }- const allowed = capability.memory?.read ?? [];- if (b.scope !== undefined && typeof b.scope !== "string")- return sendJson(res, 400, { error: "bad_request", message: "scope must be a string" });- if (typeof b.scope === "string" && !allowed.includes(b.scope))- return sendJson(res, 403, { error: "forbidden", message: "notebook is not readable here" });- const scopes = typeof b.scope === "string" ? [b.scope] : allowed;- if (scopes.length === 0) {- return sendJson(res, 403, { error: "forbidden", message: "memory recall is not enabled for this conversation" });- }- const results = await searchAcrossScopes(memory, scopes, b.query, typeof b.limit === "number" ? b.limit : 20, {- actorId: capability.actorId,- });- audit(deps, {- principalId: capability.actorId,- action: "memory.agent.search",- resource: "memory",- scopeLabel: scopes.join(","),- });- return sendJson(res, 200, { results });+ const allowed = capability.memory?.read ?? [];+ if (b.scope !== undefined && typeof b.scope !== "string")+ return sendJson(res, 400, { error: "bad_request", message: "scope must be a string" });+ if (typeof b.scope === "string" && !allowed.includes(b.scope))+ return sendJson(res, 403, { error: "forbidden", message: "notebook is not readable here" });+ const scopes = typeof b.scope === "string" ? [b.scope] : allowed;+ if (scopes.length === 0) {+ return sendJson(res, 403, { error: "forbidden", message: "memory recall is not enabled for this conversation" });}+ const results = await searchAcrossScopes(memory, scopes, b.query, typeof b.limit === "number" ? b.limit : 20, {+ actorId: capability.actorId,+ });+ audit(deps, {+ principalId: capability.actorId,+ action: "memory.agent.search",+ resource: "memory",+ scopeLabel: scopes.join(","),+ });+ return sendJson(res, 200, { results });+});- if (method === "GET" && pathname === "/v1/memory/self") {- const requested = ctx.url.searchParams.get("scope");- const read = capability.memory?.read ?? [];- const target =- requested === "org"- ? (capability.memory?.orgWrite ?? read.find((scope) => scope.startsWith("org:")))- : (requested ?? capability.memory?.write ?? capability.scopeId);- if (!target || !canReadNotebook({ ...capability.memory, read }, target)) {- return sendJson(res, 403, { error: "forbidden", message: "notebook is not readable here" });- }- audit(deps, {- principalId: capability.actorId,- action: "memory.agent.read",- resource: "memory",- scopeLabel: target,- });- return sendJson(res, 200, { scopeId: target, facts: await memoryFacts(memory, target) });+const readOwnNotebook = agentMemory(async (ctx, memory, capability) => {+ const { res, deps } = ctx;+ const requested = ctx.url.searchParams.get("scope");+ const read = capability.memory?.read ?? [];+ const target =+ requested === "org"+ ? (capability.memory?.orgWrite ?? read.find((scope) => scope.startsWith("org:")))+ : (requested ?? capability.memory?.write ?? capability.scopeId);+ if (!target || !canReadNotebook({ ...capability.memory, read }, target)) {+ return sendJson(res, 403, { error: "forbidden", message: "notebook is not readable here" });}+ audit(deps, {+ principalId: capability.actorId,+ action: "memory.agent.read",+ resource: "memory",+ scopeLabel: target,+ });+ return sendJson(res, 200, { scopeId: target, facts: await memoryFacts(memory, target) });+});++const writeMemory = (handle: (...args: [...Parameters<AgentMemoryHandler>, write: string]) => Promise<void>) =>+ agentMemory(async (ctx, memory, capability) => {+ const requestedScope = (ctx.body as { scope?: unknown } | undefined)?.scope;+ if (requestedScope !== undefined && requestedScope !== "org") {+ return sendJson(ctx.res, 400, { error: "bad_request", message: 'scope must be "org" when present' });+ }+ const write = requestedScope === "org" ? capability.memory?.orgWrite : capability.memory?.write;+ if (!write) {+ return sendJson(ctx.res, 403, {+ error: "forbidden",+ message:+ requestedScope === "org"+ ? "org memory writes require an org admin"+ : "memory capture is not enabled for this conversation",+ });+ }+ return handle(ctx, memory, capability, write);+ });- const requestedScope =- method === "GET"- ? (ctx.url.searchParams.get("scope") ?? undefined)- : (body as { scope?: unknown } | undefined)?.scope;- if (requestedScope !== undefined && requestedScope !== "org") {- return sendJson(res, 400, { error: "bad_request", message: 'scope must be "org" when present' });- }- const write = requestedScope === "org" ? capability.memory?.orgWrite : capability.memory?.write;- if (!write) {- return sendJson(res, 403, {- error: "forbidden",- message:- requestedScope === "org"- ? "org memory writes require an org admin"- : "memory capture is not enabled for this conversation",- });- }+const captureFacts = writeMemory(async ({ res, deps, body }, memory, capability, write) => {+ const facts = parseFacts(body);+ if (typeof facts === "string") return sendJson(res, 400, { error: "bad_request", message: facts });+ const added = await memory.capture(write, facts, Date.now(), capability.actorId, {+ mode: "explicit",+ actorId: capability.actorId,+ conversationScopeId: capability.scopeId,+ ...(capability.sessionId ? { sessionId: capability.sessionId } : {}),+ });+ audit(deps, {+ principalId: capability.actorId,+ action: "memory.agent.capture",+ resource: "memory",+ scopeLabel: write,+ });+ return sendJson(res, 200, { ok: true, added, scopeId: write });+});- if (method === "POST" && pathname === "/v1/memory/facts") {- const facts = parseFacts(body);- if (typeof facts === "string") return sendJson(res, 400, { error: "bad_request", message: facts });- const added = await memory.capture(write, facts, Date.now(), capability.actorId, {- mode: "explicit",- actorId: capability.actorId,- conversationScopeId: capability.scopeId,- ...(capability.sessionId ? { sessionId: capability.sessionId } : {}),- });- audit(deps, {- principalId: capability.actorId,- action: "memory.agent.capture",- resource: "memory",- scopeLabel: write,- });- return sendJson(res, 200, { ok: true, added, scopeId: write });- }- if (method === "PATCH" && pathname === "/v1/memory/facts") {- const edits = parseEdits(body);- if (typeof edits === "string") return sendJson(res, 400, { error: "bad_request", message: edits });- await memory.edit?.(write, edits, capability.actorId, { conversationScopeId: capability.scopeId });- audit(deps, {- principalId: capability.actorId,- action: "memory.agent.edit",- resource: "memory",- scopeLabel: write,- });- return sendJson(res, 200, { ok: true, scopeId: write });- }- if (method === "DELETE" && pathname === "/v1/memory/facts") {- const ids = parseIds(body);- if (typeof ids === "string") return sendJson(res, 400, { error: "bad_request", message: ids });- await memory.delete?.(write, ids, capability.actorId);- audit(deps, {- principalId: capability.actorId,- action: "memory.agent.delete",- resource: "memory",- scopeLabel: write,- });- return sendJson(res, 200, { ok: true, scopeId: write });- }+const editFacts = writeMemory(async ({ res, deps, body }, memory, capability, write) => {+ const edits = parseEdits(body);+ if (typeof edits === "string") return sendJson(res, 400, { error: "bad_request", message: edits });+ await memory.edit?.(write, edits, capability.actorId, { conversationScopeId: capability.scopeId });+ audit(deps, {+ principalId: capability.actorId,+ action: "memory.agent.edit",+ resource: "memory",+ scopeLabel: write,+ });+ return sendJson(res, 200, { ok: true, scopeId: write });+});- return sendJson(res, 404, { error: "not_found", message: `${method} ${pathname}` });-}+const deleteFacts = writeMemory(async ({ res, deps, body }, memory, capability, write) => {+ const ids = parseIds(body);+ if (typeof ids === "string") return sendJson(res, 400, { error: "bad_request", message: ids });+ await memory.delete?.(write, ids, capability.actorId);+ audit(deps, {+ principalId: capability.actorId,+ action: "memory.agent.delete",+ resource: "memory",+ scopeLabel: write,+ });+ return sendJson(res, 200, { ok: true, scopeId: write });+});async function listSkills(ctx: ApiCtx): Promise<void> {const { res, app, url } = ctx;@@ -1358,19 +1370,11 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/ui-state", auth: "source", handle: getUiState },{ method: "PUT", path: "/v1/ui-state", auth: "source", handle: putUiState },{ method: "GET", path: "/v1/apis", auth: "either", handle: listAgentApis },- {- match: (m, p) =>- (p === "/v1/memory/self" && m === "GET") ||- (p === "/v1/memory/facts" && (m === "POST" || m === "PATCH" || m === "DELETE")) ||- (m === "POST" && p === "/v1/memory/search"),- auth: "either",- handle: agentMemory,- },- {- match: (_m, p) => p === "/v1/memory/self" || p === "/v1/memory/search" || p === "/v1/memory/facts",- auth: "source",- handle: agentMemory,- },+ { method: "GET", path: "/v1/memory/self", auth: "either", handle: readOwnNotebook },+ { method: "POST", path: "/v1/memory/facts", auth: "either", handle: captureFacts },+ { method: "PATCH", path: "/v1/memory/facts", auth: "either", handle: editFacts },+ { method: "DELETE", path: "/v1/memory/facts", auth: "either", handle: deleteFacts },+ { method: "POST", path: "/v1/memory/search", auth: "either", allowedInStrict: true, handle: searchMemory },{ method: "POST", path: "/v1/grants", actor: "system", auth: "source", handle: createGrant },{ method: "POST", path: "/v1/grants/revoke", actor: "system", auth: "source", handle: revokeGrant },{ method: "POST", path: "/v1/share", auth: "either", handle: shareArtifact },@@ -1395,7 +1399,7 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "POST", path: "/v1/skills", auth: "either", handle: createSkill },{ method: "PUT", path: "/v1/skills/:id", auth: "either", handle: updateSkill },{ method: "DELETE", path: "/v1/skills/:id", auth: "either", handle: deleteSkill },- { method: "POST", path: "/v1/skills/:id/restore", auth: "either", handle: restoreSkill },+ { method: "POST", path: "/v1/skills/:id/restore", auth: "either", allowedInStrict: true, handle: restoreSkill },]),...withActor("query.principalId", [{ method: "GET", path: "/v1/resources/search", auth: "source", handle: searchResources },diff --git a/src/api/server.ts b/src/api/server.tsindex 0ae0dee58..58edce589 100644--- a/src/api/server.ts+++ b/src/api/server.ts@@ -26,47 +26,29 @@ import { errMessage } from "../util/errors.ts";import { parseScopeId, scopeId } from "../types.ts";import { canonicalPayload } from "../../plugins/chassis/src/source-auth-sign.ts";import { armBodyDeadline, PayloadTooLargeError, readRawBody, sendJson, verifyOrReject } from "./http.ts";-import { findRoute, run, type ApiCtx, type BaseCtx, type Route } from "./routes/route.ts";+import { findRoute, run, type AdminAccess, type ApiCtx, type BaseCtx, type Route } from "./routes/route.ts";import { apiRoutes, rawRoutes } from "./routes/index.ts";import { proxyDeploymentSubdomain } from "./routes/deployments.ts";import { CAPABILITY_HEADER } from "./contract.ts";import { livePersonCapability } from "./artifact-share.ts";import { canonicalPerson, samePerson } from "../directory/person.ts";-const safeDecode = (s: string): string => {- try {- return decodeURIComponent(s);- } catch {- return "";- }-};-async function capabilityAdminDenied(- method: string,- pathname: string,+ access: AdminAccess,+ params: Record<string, string>,url: URL,claims: CapabilityClaims,config: ServerDeps["config"],): Promise<string | null> {- if (method === "GET" && pathname === "/v1/admin/whoami") return null;+ if (access.agent === "anyone") return null;if (claims.aud !== CONTROL_PLANE_AUD) return "admin routes require the per-turn agent token";- if (!livePersonCapability(claims) && !unattendedAdminReadAllowed(method, pathname, claims)) {+ if (!livePersonCapability(claims) && !(access.unattended && claims.grants?.includes(access.unattended.grant))) {return "admin actions through the agent require a turn the admin started themselves — autonomous turns (crons, webhooks) cannot act as an admin";}- if (pathname.startsWith("/v1/admin/grants")) {- return "admin grant changes (promote/revoke) are portal-only — the agent cannot manage who governs the org";- }- if (pathname.startsWith("/v1/admin/impersonate")) {- return "impersonating a user is portal-only — the agent cannot act as another person";- }- if (pathname.startsWith("/v1/admin/principal-links")) {- return "identity links are portal-only — the agent cannot decide which sign-ins belong to one person";- }- if (method === "GET" && isAdminContentRead(pathname) && parseScopeId(claims.scopeId).kind !== "personal") {- let target = "";- if (pathname.startsWith("/v1/admin/scopes/"))- target = safeDecode(pathname.slice("/v1/admin/scopes/".length).split("/")[0] ?? "");- else if (pathname === "/v1/admin/memory") target = url.searchParams.get("scope") ?? "";+ if (typeof access.agent === "object") return access.agent.portalOnly;+ if (access.privateRead && parseScopeId(claims.scopeId).kind !== "personal") {+ const target =+ access.privateRead === "unless-org-scope" ? (params.scope ?? url.searchParams.get("scope") ?? "") : "";if (parseScopeId(target).kind !== "org" &&(!livePersonCapability(claims) ||@@ -78,63 +60,6 @@ async function capabilityAdminDenied(return null;}-const UNATTENDED_READ_PATHS: Record<string, (pathname: string) => boolean> = {- "admin.sessions.read": (p) =>- p === "/v1/admin/sessions" ||- /^\/v1\/admin\/sessions\/[^/]+$/.test(p) ||- p === "/v1/admin/scopes" ||- p === "/v1/admin/errors" ||- p === "/v1/admin/runs",- "admin.audit.read": (p) => p === "/v1/admin/audit",- "admin.egress.read": (p) => p === "/v1/admin/egress",- "admin.files.read": (p) =>- p === "/v1/admin/files" || p === "/v1/admin/files/read" || p === "/v1/admin/files/download",-};--function unattendedAdminReadAllowed(method: string, pathname: string, claims: CapabilityClaims): boolean {- if (method !== "GET") return false;- return (claims.grants ?? []).some((grant) => UNATTENDED_READ_PATHS[grant]?.(pathname) === true);-}--function isAdminContentRead(pathname: string): boolean {- if (pathname === "/v1/admin/memory" || pathname === "/v1/admin/scopes") return true;- if (pathname === "/v1/admin/keychain") return true;- if (pathname === "/v1/admin/volumes") return true;- if (pathname.startsWith("/v1/admin/scopes/")) return true;- if (pathname.startsWith("/v1/admin/sessions")) return true;- if (pathname.startsWith("/v1/admin/files")) return true;- if (- pathname === "/v1/admin/runs" ||- pathname === "/v1/admin/audit" ||- pathname === "/v1/admin/security/flags" ||- pathname === "/v1/admin/errors" ||- pathname === "/v1/admin/egress"- )- return true;- if (pathname === "/v1/admin/crons" || pathname === "/v1/admin/deployments" || pathname === "/v1/admin/skills")- return true;- if (pathname === "/v1/admin/deliveries/shadow") return true;- if (pathname.startsWith("/v1/admin/slack-mirror")) return true;- if (pathname.startsWith("/v1/admin/ambient-judgments")) return true;- if (pathname.startsWith("/v1/admin/ack-emoji-picks")) return true;- if (pathname.startsWith("/v1/admin/skills/")) return true;- if (pathname.startsWith("/v1/admin/users/")) return true;- return false;-}--function strictPostAllowed(pathname: string): boolean {- if (- pathname === "/v1/surface-context" ||- pathname === "/v1/projects" ||- pathname === "/v1/memory/search" ||- pathname === "/v1/search" ||- pathname.startsWith("/v1/run-signals/")- )- return true;- if (/^\/v1\/projects\/[^/]+(?:\/members(?:\/[^/]+)?)?$/.test(pathname)) return true;- return /^\/v1\/skills\/[^/]+\/restore$/.test(pathname);-}-const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);function capabilityFromHeaders(req: IncomingMessage): string | null {@@ -253,7 +178,8 @@ async function gate(pathname: string,url: URL,raw: string,- route: Pick<Route, "auth" | "actor"> | undefined,+ route: Pick<Route, "auth" | "actor" | "admin" | "allowedInStrict"> | undefined,+ params: Record<string, string>,): Promise<GateResult | null> {const routeAuth = route?.auth;const { deps, secret, auth, requirePortalIdentity, allowUnsignedSourceAuth } = wiring;@@ -271,8 +197,8 @@ async function gate(sendJson(res, 403, { error: "forbidden", message: "capability token audience not valid for this route" });return null;}- if (pathname.startsWith("/v1/admin/")) {- const denied = await capabilityAdminDenied(method, pathname, url, capability, deps.config);+ if (route?.admin) {+ const denied = await capabilityAdminDenied(route.admin, params, url, capability, deps.config);if (denied) {sendJson(res, 403, { error: "forbidden", message: denied });return null;@@ -308,7 +234,7 @@ async function gate(capability &&!requiredAud &&method !== "GET" &&- !strictPostAllowed(pathname) &&+ !route?.allowedInStrict &&deps.config &&(await deps.config.getSecurityPostureDurable(capability.scopeId)) === "strict") {@@ -342,8 +268,7 @@ async function gate(typeof body === "object" &&(body as { surface?: unknown }).surface === "web";const routeActor = route?.actor ?? (WRITE_METHODS.has(method) ? "person" : undefined);- const needsActor =- webTurn || pathname.startsWith("/v1/admin/") || (routeActor !== undefined && routeActor !== "system");+ const needsActor = webTurn || (routeActor !== undefined && routeActor !== "system");if (needsActor) {if (!psecret || !actor) {sendJson(res, 401, { error: "unauthorized", message: "portal identity required" });@@ -421,7 +346,17 @@ function buildFastify(wiring: Wiring, server: Server): { fastify: FastifyInstancconst base = baseCtx(req, res, wiring);const raw = rawBodies.get(req) ?? "";const found = findRoute(matchRoutes, base.method, base.pathname);- const g = await gate(req, res, wiring, base.method, base.pathname, base.url, raw, found?.route);+ const g = await gate(+ req,+ res,+ wiring,+ base.method,+ base.pathname,+ base.url,+ raw,+ found?.route,+ found?.params ?? {},+ );if (!g) return;if (found) {const ctx: ApiCtx = {@@ -477,6 +412,7 @@ function buildFastify(wiring: Wiring, server: Server): { fastify: FastifyInstancurl,raw,request.routeOptions.config.route,+ request.params as Record<string, string>,);if (!result) {reply.hijack();diff --git a/test/agent-api-discovery.test.ts b/test/agent-api-discovery.test.tsindex 83b349172..2233bf91e 100644--- a/test/agent-api-discovery.test.ts+++ b/test/agent-api-discovery.test.ts@@ -9,7 +9,6 @@ import type { AddressInfo } from "node:net";import { createServer } from "../src/api/server.ts";import { buildApp } from "../src/wiring.ts";import { scopeId, type ScopeId } from "../src/types.ts";-import { agentApiMatches } from "../src/api/agent-api-catalog.ts";import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";import { testConfig } from "./support/test-config.ts";@@ -151,11 +150,11 @@ test("a granted autonomous turn discovers only the unattended read family", asynconst { body } = await listApis(s.base, await capFor("admin-alice", { grants: ["admin.sessions.read"] }));const adminPaths = paths(body).filter((path) => path.startsWith("/v1/admin/"));assert.deepEqual(adminPaths, [+ "/v1/admin/scopes","/v1/admin/sessions","/v1/admin/sessions/:id",- "/v1/admin/scopes",- "/v1/admin/errors","/v1/admin/runs",+ "/v1/admin/errors","/v1/admin/whoami",]);assert.ok(body.guidance.some((guidance: string) => guidance.includes("flag any other admin action")));@@ -191,39 +190,6 @@ test("discovery advertises the deployment share endpoint, with guidance", async}});-test("the catalog IS the gate: discovery rows with real paths are admitted, unlisted routes are not", () => {- assert.equal(agentApiMatches("GET", "/v1/apis"), true);- assert.equal(agentApiMatches("POST", "/v1/deployments/abc/share"), true);- assert.equal(agentApiMatches("GET", "/v1/deployments/abc"), true);- assert.equal(agentApiMatches("POST", "/v1/deployments/abc/restore"), true);- assert.equal(agentApiMatches("GET", "/v1/deployments/abc/share"), true, "owners can inspect app grants");- assert.equal(agentApiMatches("DELETE", "/v1/deployments/abc/share"), false, "app grants use GET and POST");- assert.equal(agentApiMatches("POST", "/v1/share"), true, "the uniform share verb is agent-callable");- assert.equal(agentApiMatches("GET", "/v1/share"), false, "share is POST-only");- assert.equal(agentApiMatches("POST", "/v1/crons"), true);- assert.equal(agentApiMatches("POST", "/v1/skills"), true);- assert.equal(agentApiMatches("PUT", "/v1/skills/abc"), true);- assert.equal(agentApiMatches("DELETE", "/v1/skills/abc"), true);- assert.equal(agentApiMatches("GET", "/v1/skills/abc"), true);- assert.equal(agentApiMatches("POST", "/v1/skills/abc/restore"), true);- assert.equal(agentApiMatches("GET", "/v1/crons/abc"), true);- assert.equal(agentApiMatches("POST", "/v1/crons/abc/note"), true);- assert.equal(agentApiMatches("GET", "/v1/crons/abc/note"), false, "note is POST-only");- assert.equal(agentApiMatches("POST", "/v1/webhooks/abc/enable"), true);- assert.equal(agentApiMatches("PATCH", "/v1/memory/facts"), true);- assert.equal(agentApiMatches("PUT", "/v1/memory/self"), false, "notebooks are edited by fact id, not rewritten");- assert.equal(agentApiMatches("PATCH", "/v1/admin/memory"), true);- assert.equal(agentApiMatches("GET", "/v1/admin/whoami"), true);- assert.equal(- agentApiMatches("POST", "/v1/connectors/oauth/revoke"),- true,- "disconnect is the mirror of connect — agent-callable",- );- assert.equal(agentApiMatches("POST", "/v1/turns"), false, "turn ingress stays source-auth only");- assert.equal(agentApiMatches("GET", "/v1/sessions/abc"), false);- assert.equal(agentApiMatches("DELETE", "/v1/webhooks"), false);-});-test("discovery includes admin routes for a verified human thread reply", async () => {const s = await start();try {diff --git a/test/agent-api-parity.test.ts b/test/agent-api-parity.test.tsindex 2adaa22cf..78850d9dd 100644--- a/test/agent-api-parity.test.ts+++ b/test/agent-api-parity.test.ts@@ -1,46 +1,43 @@import { test } from "node:test";import assert from "node:assert/strict";-import { agentApiMatches } from "../src/api/agent-api-catalog.ts";+import { renderAgentApis } from "../src/api/agent-api-catalog.ts";+import { UNATTENDED_ADMIN_GRANTS } from "../src/api/control-service.ts";+import { findRoute } from "../src/api/routes/route.ts";import { apiRoutes, rawRoutes } from "../src/api/routes/index.ts";-import type { BaseCtx, Route } from "../src/api/routes/route.ts";+import type { CapabilityClaims } from "../src/auth/capability-token.ts";-const DEDICATED_AUDIENCE_EITHER = new Set<string>(["POST /v1/blobs", "GET /v1/blobs/:id"]);+const base: CapabilityClaims = { actorId: "U1", scopeId: "personal:U1", exp: Date.now() + 60_000 };-const sample = (p: string) => p.replace(/:[A-Za-z]+/g, "x123");-const hasPath = (r: Route<BaseCtx>): r is Route<BaseCtx> & { method: string; path: string } =>- "path" in r && "method" in r;--const allRoutes: ReadonlyArray<Route<BaseCtx>> = [- ...(rawRoutes as ReadonlyArray<Route<BaseCtx>>),- ...(apiRoutes as unknown as ReadonlyArray<Route<BaseCtx>>),-];--test("every auth:'either' route is admitted by the catalog gate (no parity drift)", () => {- const misses: string[] = [];- for (const r of allRoutes) {- if (r.auth !== "either" || !hasPath(r)) continue;- const key = `${r.method} ${r.path}`;- if (DEDICATED_AUDIENCE_EITHER.has(key)) continue;- for (const method of r.method.split("|")) {- if (!agentApiMatches(method, sample(r.path))) misses.push(`${method} ${r.path}`);- }- }- assert.deepEqual(- misses,- [],- `agent-callable routes the catalog gate rejects (add them to FAMILIES in agent-api-catalog.ts, ` +- `or, if they use a dedicated-audience token, to DEDICATED_AUDIENCE_EITHER here): ${misses.join(", ")}`,+function advertised(): Array<{ method: string; path: string }> {+ const listings = [+ renderAgentApis(+ { ...base, liveAuthor: true, memory: { read: ["personal:U1"], write: "personal:U1" } },+ { isAdmin: true },+ { swarmsEnabled: true },+ ),+ renderAgentApis({ ...base, grants: [...UNATTENDED_ADMIN_GRANTS] }, { isAdmin: false }, { swarmsEnabled: false }),+ ];+ return listings.flatMap((listing) =>+ listing.endpoints.flatMap(({ method, path }) => {+ const [route = ""] = path.split("?");+ const paths = route+ .split("/")+ .slice(1)+ .map((segment) => (segment.startsWith(":") ? ["x1"] : segment.split("|")))+ .reduce<string[]>((acc, options) => acc.flatMap((prefix) => options.map((o) => `${prefix}/${o}`)), [""]);+ return method.split("|").flatMap((m) => paths.map((p) => ({ method: m, path: p })));+ }),);-});+}-test("the catalog gate admits no source-only or public route (no over-exposure)", () => {- const leaks: string[] = [];- for (const r of allRoutes) {- if (!hasPath(r)) continue;- if (r.auth !== "source" && r.auth !== "public") continue;- for (const method of r.method.split("|")) {- if (agentApiMatches(method, sample(r.path))) leaks.push(`${method} ${r.path} (${String(r.auth)})`);- }- }- assert.deepEqual(leaks, [], `internal routes wrongly admitted to the agent surface: ${leaks.join(", ")}`);+test("every endpoint the agent API catalog advertises is served by a route an agent token can call", () => {+ const endpoints = advertised();+ assert.ok(endpoints.length > 100, `expected a full listing, got ${endpoints.length}`);+ const unreachable = endpoints.flatMap(({ method, path }) => {+ const found = findRoute(rawRoutes, method, path) ?? findRoute(apiRoutes, method, path);+ return found && (found.route.auth === "either" || typeof found.route.auth === "object")+ ? []+ : [`${method} ${path} (${found ? String(found.route.auth) : "no route"})`];+ });+ assert.deepEqual(unreachable, []);});diff --git a/test/capability-routes.test.ts b/test/capability-routes.test.tsindex d0ce56506..179458958 100644--- a/test/capability-routes.test.ts+++ b/test/capability-routes.test.ts@@ -530,6 +530,8 @@ describe("capability-token control plane (crons + webhooks + SOUL)", () => {);assert.equal(create.status, 403);assert.match(((await create.json()) as { message: string }).message, /direct control-plane mutations/i);+ const search = await post("/v1/memory/search", { query: "anything" }, { "x-agent-capability": token });+ assert.doesNotMatch(await search.text(), /direct control-plane mutations/i);});it("a capability cannot cancel another user's cron", async () => {diff --git a/test/deployment-layer-routes.test.ts b/test/deployment-layer-routes.test.tsindex 08323464f..553f01f7e 100644--- a/test/deployment-layer-routes.test.ts+++ b/test/deployment-layer-routes.test.ts@@ -9,7 +9,6 @@ import type { AddressInfo } from "node:net";import { createServer } from "../src/api/server.ts";import { signRequest } from "../src/auth/source-auth.ts";import { buildApp } from "../src/wiring.ts";-import { agentApiMatches } from "../src/api/agent-api-catalog.ts";import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";import { scopeId } from "../src/types.ts";import { testConfig } from "./support/test-config.ts";@@ -348,9 +347,6 @@ test("a skill collision racing after validation is accepted degraded and audited});test("a VALID capability token is rejected on the deployment-layer routes (source-auth only)", async () => {- assert.equal(agentApiMatches("GET", PATH), false);- assert.equal(agentApiMatches("PUT", PATH), false);-const srv = start();try {const cap = await mintCapabilityToken(diff --git a/test/public-architecture-docs.test.ts b/test/public-architecture-docs.test.tsindex f5e7c80b5..ca9db638c 100644--- a/test/public-architecture-docs.test.ts+++ b/test/public-architecture-docs.test.ts@@ -53,10 +53,6 @@ test("README names the frameworks the shipped surfaces use", () => {test("Strict posture describes its approval gate, exemptions, and direct-mutation boundary", () => {assert.match(agentTools, /TOOL_APPROVAL_EXEMPT = new Set\(\["finish_silently"\]\)/);- assert.match(- server,- /pathname === "\/v1\/surface-context".*pathname === "\/v1\/memory\/search".*pathname\.startsWith\("\/v1\/run-signals\/"\)/s,- );assert.doesNotMatch(server, /Strict posture permits observation only/);assert.doesNotMatch(adminUi, /every tool call/i);});diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.tsindex 8cacba684..2ea69f653 100644--- a/test/route-auth-conformance.test.ts+++ b/test/route-auth-conformance.test.ts@@ -2,72 +2,19 @@ import { test } from "node:test";import assert from "node:assert/strict";import { apiRoutes, rawRoutes } from "../src/api/routes/index.ts";import { findRoute, type RouteAuth } from "../src/api/routes/route.ts";-import { agentApiMatches } from "../src/api/agent-api-catalog.ts";import { OAUTH_CONSENT_AUD, CREDENTIAL_BROKER_AUD, BROWSER_MODEL_AUD } from "../src/auth/capability-token.ts";-const PUBLIC_ROUTES = new Set<string>([- "POST /v1/slack/managed/installation",- "DELETE /v1/slack/managed/installation",- "POST /v1/slack/managed/events",-]);const AUD_ROUTES = new Map<string, string>([["POST /v1/browser-model/chat/completions", BROWSER_MODEL_AUD],["POST /v1/connectors/oauth/consent/mint", OAUTH_CONSENT_AUD],["POST /v1/credentials/broker", CREDENTIAL_BROKER_AUD],]);-function expectedAuth(method: string, pathname: string): RouteAuth {- if (PUBLIC_ROUTES.has(`${method} ${pathname}`)) return "public";- const aud = AUD_ROUTES.get(`${method} ${pathname}`);- if (aud) return { aud };- if (agentApiMatches(method, pathname)) return "either";- return "source";-}--function synthesize(path: string): string {- return path- .split("/")- .map((seg) => (seg.startsWith(":") ? "sample" : seg))- .join("/");-}-const PATHS = new Set<string>([]);-for (const route of apiRoutes) if ("path" in route) PATHS.add(synthesize(route.path));-for (const p of [- "/v1/crons/sample",- "/v1/memory/self",- "/v1/memory/search",- "/v1/memory/facts",- "/v1/admin/crons",- "/v1/admin/deployments",- "/v1/admin/skills",- "/v1/connectors/oauth/github/start",-])- PATHS.add(p);--const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;--test("for every request the table serves, the matched route's auth matches the pinned contract", () => {- let probed = 0;- for (const pathname of PATHS) {- for (const method of METHODS) {- const found = findRoute(apiRoutes, method, pathname);- if (!found) continue;- probed++;- assert.deepEqual(- found.route.auth,- expectedAuth(method, pathname),- `${method} ${pathname} resolves to a route whose auth ${JSON.stringify(found.route.auth)} disagrees with the pinned contract`,- );- }- }- assert.ok(probed > apiRoutes.length, `expected to probe more combos than routes, only hit ${probed}`);-});-test("every pinned dedicated-audience route actually resolves in the table", () => {for (const key of AUD_ROUTES.keys()) {const [method, pathname] = key.split(" ") as [string, string];const found = findRoute(apiRoutes, method, pathname);assert.ok(found, `${key} is pinned but no route serves it`);- assert.deepEqual(found.route.auth, expectedAuth(method, pathname), `${key} resolves with unexpected auth`);+ assert.deepEqual(found.route.auth, { aud: AUD_ROUTES.get(key) }, `${key} resolves with unexpected auth`);}});@@ -88,19 +35,3 @@ test("raw routes keep their declared auth contracts (front enforces capability aassert.ok(route.auth !== undefined, "every raw route must declare its auth contract");}});--test('"either" is exactly the agent-callable surface the catalog advertises', () => {- for (const pathname of PATHS) {- for (const method of METHODS) {- const found = findRoute(apiRoutes, method, pathname);- if (!found) continue;- const auth = found.route.auth;- if (typeof auth === "object" || auth === "public") continue;- assert.equal(- auth === "either",- agentApiMatches(method, pathname),- `${method} ${pathname}: auth "${String(auth)}" vs catalog ${agentApiMatches(method, pathname)}`,- );- }- }-});diff --git a/test/swarm-api.test.ts b/test/swarm-api.test.tsindex 39890e028..201e04709 100644--- a/test/swarm-api.test.ts+++ b/test/swarm-api.test.ts@@ -7,7 +7,6 @@ import { mintCapabilityToken } from "../src/auth/capability-token.ts";import { mintPortalIdentity } from "../src/auth/portal-identity.ts";import { signedRequestHeaders } from "../plugins/chassis/src/source-auth-sign.ts";import { swarmFixture } from "./support/swarm-fixture.ts";-import { agentApiMatches } from "../src/api/agent-api-catalog.ts";test("swarm HTTP rejects body identity selectors and completed capabilities while allowing arbitrary context keys", async () => {const fixture = await swarmFixture();@@ -94,9 +93,6 @@ test("authenticated swarm API binds agent operations to the token and human operawait new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;try {- assert.ok(agentApiMatches("GET", "/v1/swarm"));- assert.ok(agentApiMatches("POST", "/v1/swarm"));- assert.ok(!agentApiMatches("POST", `/v1/sessions/${fixture.root.id}/swarm`));if (fixture.caller.kind !== "agent") throw new Error("wrong caller");const token = await mintCapabilityToken(fixture.caller.claims, capabilitySecret);const headers = { "x-agent-capability": token, "content-type": "application/json" };