SAM API Endpoint Reference
Private SAM account assistant
These endpoints require an authenticated, approved account and resolve the SamSession Durable Object by that user's identity. Settings are off by default. Enabling is additionally subject to the installation kill switch; assistant turns and actions require both gates. No caller-supplied project ID selects the private conversation's owner.
| Method | Endpoint | Contract |
| ------ | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET | /api/sam/settings | Returns { enabled, available }; enabled is the saved user preference, available reflects installation availability. |
| PATCH | /api/sam/settings | Body { enabled: boolean }; returns the saved settings. Disabling fences further assistant effects and preserves history and already-dispatched project work. |
| GET | /api/sam/turns | Returns { conversationId, backingTaskId, legacyHistoryAvailable, turns, nextCursor, work }. Pass the opaque nextCursor unchanged as before to load older turns. Each page is chronological; the first page contains the newest bounded window. |
| POST | /api/sam/fork | Body { requestKey }; returns { conversationId, backingTaskId, replayed }. Creates and selects a private branch with copied user/assistant history and a new backing-task identity linked to its parent. Requires no active turn; retry the same key after a lost response. Does not copy project actions or grant project access. No fork button is exposed in the launch UI. |
| POST | /api/sam/turns | Body { requestKey, message }; returns { turn, accepted, replayed }, with 202 for new acceptance or 200 for a replay. Reuse the same key and identical message after a lost response. Acceptance is not completion. |
| GET | /api/sam/turns/:id/stream | Server-sent events for the running turn: a snapshot (phase, elapsedMs, published text, one-line thinking, tool activity), then phase, text (at offset), draft-reset, thinking, tool and a final done. 204 when the turn is not running in the server object; 429 above the reader cap. Live text is only what passes the receipt guard; the stored turn stays authoritative. |
| POST | /api/sam/turns/:id/cancel | Stops an accepted/running assistant turn; returns { turn }. This does not stop a project task already dispatched. |
| POST | /api/sam/actions/:id/confirm | Body { approved: boolean }; approves or declines the exact stored action and returns { action }. Repeating confirmation does not repeat its external effect. |
| POST | /api/sam/actions/:id/reconcile | Checks the existing reservation for an uncertain sam_chat_start action; returns { action }. This is reconciliation, not permission to dispatch replacement work. |
| POST | /api/sam/updates/:id/seen | The ID is the dispatch action ID. Marks its retained event references communicated after current authorization checks; returns { seen: true }. It does not answer an agent request. |
| GET | /api/sam/conversations | Lists retained private conversations. |
| GET | /api/sam/conversations/:id/messages | Returns { messages, nextCursor }; optional limit and before sequence cursor. Returns a chronological page from the newest remaining window. The assistant UI shows earlier history read-only and suppresses operator: message IDs already rendered as rich turns. |
Turns include id, request_key, message, state, response, error, actions and created_at; the running turn also carries live, the same snapshot the stream sends first. Action receipts include id, operation, input_json, state, result_json, and optional available. Read-operation receipts project input_json as the string "{}" and result_json as null; retained resource payloads are not a visibility grant. A mutating action whose current resource access cannot be verified has available: false, redacted input, and an explanatory result; clients hide its confirmation controls. Treat uncertain as unresolved, not successful or safe to repeat. An explicit rejectedBeforeEffects: true error permits correcting the rejected input; absence of that flag does not prove that no effect occurred.
work contains authorized source task/session references, project/task labels, observed status and timestamp, attention flags, and coalesced unread update metadata. New events do not automatically generate assistant messages. Read transport acknowledgement and user-visible communication are separate records.
The old POST /api/sam/chat inference path is closed: enabled clients receive 409 client_update_required and must use durable turns. Sources: apps/api/src/routes/sam.ts and apps/api/src/durable-objects/sam-session/operator/. Public contract: apps/www/src/content/docs/docs/reference/api.md.
Node Management
POST /api/nodes— Create node (201). At the caller's per-person managed workspace-node limit in the selected pool, returns409 CAPACITY_POOL_NODE_LIMITwith guidance to delete an idle node or ask the pool owner to raise the limit in Infrastructure; no node is created or provisioning scheduled (services/nodes.ts:createNodeRecord,routes/nodes.ts).GET /api/nodes— List user's nodesGET /api/nodes/:id— Get node detailsPOST /api/nodes/:id/stop— Stop nodeDELETE /api/nodes/:id— Delete nodeGET /api/nodes/:id/events— List node events (proxied from VM Agent via control plane)GET /api/nodes/:id/system-info— Full system info (proxied from VM Agent)POST /api/nodes/:id/token— Get node-scoped token for direct VM Agent access
Workspace Management
POST /api/workspaces— Create workspaceGET /api/workspaces— List user's workspacesGET /api/workspaces/:id— Get workspace detailsPATCH /api/workspaces/:id— Rename workspace display namePOST /api/workspaces/:id/sleep— Strictly checkpoint and sleep a persistent session; verified VM snapshots are resumable on a replacement workspacePOST /api/workspaces/:id/stop— Permanently stop a running workspace and delete retained session snapshot statePOST /api/workspaces/:id/restart— Restart a stopped, errored, or evicted workspace. Cancellation is allowed only before a deletion attempt is claimed; exact workspace identity/status is rechecked before the VM request.POST /api/workspaces/:id/rebuild— Rebuild a running, recovering, or errored workspace. Returns202; uses the same claimed-deletion and final VM-request identity fences as restart.DELETE /api/workspaces/:id— Request permanent workspace deletion. Returns confirmed success only after VM absence/success proof or an explicit strict provider/container termination marker and terminal finalization; returns202withdeletionStatus: "pending"when durable retry is armed, the same exact attempt is already in flight, or proof-bearing finalization must converge after a concurrent state write. An identity/status fence without retained retry returns409withdeletionStatus: "rejected". Retained snapshot/session state is removed only after confirmation.
The control plane uses the VM-agent capability path DELETE /workspaces/:id/physical-deletion, with exact workspace generation, owner, node ID and runtime incarnation plus explicit/automatic deletion authority. Automatic authority includes the verified snapshot expiry. Confirmation requires an exact identity echo and both success: true and physicalDeleted: true; a legacy agent's 404 or generic 2xx is pending, never physical proof. The older destructive path is not sent to legacy agents.
Project Management
POST /api/projects— Create projectGET /api/projects— List user's projects (supportslimitandcursor)GET /api/projects/:id— Get project detail (includes task status counts and linked workspace count). Recent sessions/activity are empty by default; pass?include=recentfor bounded best-effort recent data (the CLI requests this).GET /api/projects/:projectId/comments— List project-wide comment inbox across chat and library threads (supportsstatus=open|sent|resolved,limit)GET /api/projects/:id/capacity-pools/defaults— Read default capacity pool context for the current project/user context. Requires projectproject:read; every active member receives the redactedeffectiveSummaryplus safeplacementSettingsresource defaults/settings. Raw project/user summaries require projectsecret:read, raw installation summaries are superadmin-only, and encrypted credential material is never returned.?ensure=truereconciles only for callers that also have projectsecret:read; non-superadmins never reconcile installation credentials through this route.POST /api/projects/:id/capacity-pools/defaults/reconcile— Explicitly reconcile visible default capacity pool metadata from existing credentials and return the same safe summary payload. Non-superadmins reconcile project/user scopes only.PATCH /api/projects/:id/capacity-pools/defaults— Update only the project-owned default pool policy (workspace strategy, deployment strategy, exhaustion policy, or maximum nodes), candidate statuses, provider-nativecatalogAdditions, orsourceOrder(provider order, most preferred source first;null/[]clears; unknown ids → 400missingSourceIds); requires projectsecret:writeand never mutates user or installation fallback pools.PATCH /api/projects/:id— Update project metadata (name,description,defaultBranch)DELETE /api/projects/:id— Delete project (cascades project tasks/dependencies/events)- Insights (project members;
?range=7d|30d|90d, default30d, else 400; each a thin adapter over itspackages/operations/src/insights-*.tsop,routes/project-insights.ts):GET /api/projects/:projectId/insights/flow(projectFlow),.../insights/accounts(projectAccounts,private, no-store),.../insights/people(projectPeople,private, no-store: waiting-on by assignee with private items reduced to their age, review pickup median/p90 frompull_request_review_requests, first-person answer share; reassign goes through the Inbox.../inbox/items/:ref/reassignroute). Run receipt:GET /api/projects/:projectId/tasks/:taskId/receipt
Default Capacity Pools
GET /api/capacity-pools/defaults— Read the authenticated user's default compute pool summaries. Hidden project/installation scopes are represented structurally and are not rendered as user-facing placeholder rows. Pass?ensure=truefor idempotent user-scope reconciliation before returning. Existing installation metadata may appear only through redactedeffectiveSummary; this route never reconciles installation credentials.POST /api/capacity-pools/defaults/reconcile— Explicitly reconcile the authenticated user's default compute pool metadata from their cloud credentials.PATCH /api/capacity-pools/defaults— Update only the authenticated user's owned default pool policy (including separate workspace and deployment strategies), candidate statuses, provider-nativecatalogAdditions, orsourceOrder(provider order, most preferred source first;null/[]clears; unknown ids → 400missingSourceIds).GET /api/admin/capacity-pools/defaults— Superadmin-only read for the SAM installation default compute pool summaries; reveals non-secret metadata about platform cloud credentials.POST /api/admin/capacity-pools/defaults/reconcile— Superadmin-only explicit reconciliation for installation default pool metadata from platform cloud credentials.PATCH /api/admin/capacity-pools/defaults— Superadmin-only update for the installation-owned default pool policy (including separate workspace and deployment strategies), candidate statuses, provider-nativecatalogAdditions, orsourceOrder(provider order, most preferred source first;null/[]clears; unknown ids → 400missingSourceIds).GET /api/providers/catalog— Return concrete provider-native offering catalogs available to the authenticated context. Omittedscopeis personal/user-only; project catalogs requirescope=project&projectId=...plus projectsecret:read; installation catalogs require superadmin. The response isCache-Control: private, no-storeand includes non-secret metadata only.
Chat Sessions (Project Scoped)
GET /api/projects/:projectId/sessions— List chat sessions for a project, newest message first (limit≤ 100,offset,status,scope=my|all).include=liveon an unfiltered first page also appends every in-scopeactiveandsleepingsession the page left out (up tolimitper status, with sessions that carry an attention marker ranked separately);total/hasMorestill describe the page. Reads are served from the D1session_summariesindex when its coverage is fresh;consistency=authoritativereads the ProjectData DO instead (the web app's catch-up read after a project socket subscribes, because the index lags the DO by the summary sync debounce)GET /api/projects/:projectId/sessions/:sessionId— Get chat session detail with recent messages (before/aftertake the same cursors as the message list below; anafter-only request reads forward so a client can drain newer messages page by page)GET /api/projects/:projectId/sessions/:sessionId/retained-snapshot/:artifact— Browser owner-only private attachment download of the canonical retainedmanifestor exactwip; requires approved active account, original project access, session creator and snapshot owner. No HOME/keys/list/signed URL; stopped/no-workspace supported, missing/foreign/expired/inconsistent artifacts uniformly 404. Read-only; rechecks generation, ownership, expiry and full length/SHA-256 before streaming.GET /api/projects/:projectId/sessions/:sessionId/state— Get lightweight ACP activity state for a chat sessionGET /api/projects/:projectId/sessions/:sessionId/messages— List persisted session messages (supportsroles,before,after,limit,compact,order=asc|desc).before/afteraccept an exact[createdAt,sequence,id]cursor taken from a page's edge row — required to resume inside a group of rows sharing one timestamp — or a legacy millisecond timestamp that excludes every row at that time. Withoutorder, anafter-only request reads ascending; anything else reads newest-first. Pages are always returned oldest-first.GET /api/projects/:projectId/sessions/:sessionId/messages/:messageId/tool-content— Lazy-load stored tool content for compact messages, falling back to the private R2 archive when inline payloads have been strippedGET /api/projects/:projectId/sessions/:sessionId/resource-timeline— Whole-session resource timeline index: every retained chunk (ascending) with its summary and per-minuterollup,runsper workspace withreservation,omittedChunkCountpastWORKSPACE_RESOURCE_TIMELINE_MAX_CHUNKS, andcollection(collected/pending/unsupported/expired) explaining an empty timelineGET /api/projects/:projectId/sessions/:sessionId/resource-timeline/chunks/:chunkId— One chunk's 5-second samples and tool spans, scoped to the path's project and session (foreign chunk → 404)GET /api/projects/:projectId/sessions/:sessionId/comments— List message-anchored comment threads (supportsmessageId,status=open|sent|resolved,afterSequence,limit)POST /api/projects/:projectId/sessions/:sessionId/comments— Create a message-anchored comment thread ({ messageId, body, quote?, mentions?: [{ userId }], clientMutationId? })GET /api/projects/:projectId/sessions/:sessionId/comments/:threadId/context— One thread with the chat around its anchored message, for the Comments page reader (task:read):{ thread, session: { id, topic }, viewerAccess, anchor: { messageId, found }, messages, hasMoreBefore, hasMoreAfter }.messagesholds the whole anchored message (a streamed agent reply is many rows; a thread may be on any of them) pluscollaboration.commentContextMessagesdisplayed messages each side, at mostcollaboration.commentContextMaxRowsrows per side; page on with.../messagescursors. Another chat's or project's thread → 404POST /api/projects/:projectId/sessions/:sessionId/comments/:threadId/replies— Append a comment reply ({ body, mentions?, clientMutationId? })POST /api/projects/:projectId/sessions/:sessionId/comments/:threadId/send— The explicit "Send to agent" action, the only way a comment reaches the agent: queues one idempotent comment directive through ProjectData prompt delivery and marks the threadsent({ body?, clientMutationId? };202, or200when already sent). Authorized by the agent-wake policy (authorizeAgentWake; today session writers only, owner or active grantee); the delivery recordsmetadata.wakePOST /api/projects/:projectId/sessions/:sessionId/comments/:threadId/resolve— Mark a threadresolved({ clientMutationId? })POST /api/projects/:projectId/sessions/:sessionId/comments/:threadId/reopen— Reopen a thread toopen({ clientMutationId? })POST /api/projects/:projectId/sessions/:sessionId/prompt— Send a follow-up prompt to the active agent sessionPOST /api/projects/:projectId/sessions/:sessionId/attention/:markerId/resolve— Validate, forward, and record one structured human-input answer ({ answer })GET /api/inbox,GET /api/inbox/count,GET /api/projects/:projectId/inbox[/count]— inbox list (filter,limit,cursor) and counts acrossasks, attention markers (viasession_summaries.attention_json), secret requests and approvals (routes/inbox.ts)GET /api/projects/:projectId/inbox/items/:ref[?context=true],POST .../items/:ref/answer,POST .../items/:ref/archive— one item, answer through its store's existing path, archive (silent); writes need the exact app origin + JSONPOST /api/projects/:projectId/inbox/items/:ref/reply—{content, attachments?}→ 202{ref,sessionId,status:'queued',messageId,deliveryId}. Same authorized chat send/wake path,sourceKind:'inbox_reply', transcript metadatainboxRef; header only in delivered text. Pending permission selects its reject option first; all other statuses unchanged. List/count hide items awaiting agent action, team-wide; Archived exposeswithAgentandlatestReply. Detail addsconversationwith canonical chat replies, anchored agent responses,nextReplyCursor/nextResponseCursor(replyCursor/responseCursorquery parameters). Settled permission conversations aredone,canAct:false,canReply:true.- Human tasks (
ask:<id>, kindtask):POST .../items/:ref/steps/:index{done},.../comments{body, threadId?, mentions?},.../claim,.../reassign{assigneeUserId}|{team:true},.../done{note?},.../reopen;GET .../items/:refaddstask(steps, assignee, claim, activity, discussion). Routes:apps/api/src/routes/inbox-tasks.ts - MCP
inbox_write(ask,review,result,assign,comment,attach,respond,resolve,update,cancel) andinbox_read(list,get) — the agent's side of the inbox (routes/mcp/inbox-tools.tsoverpackages/operations/src/inbox-agent-core.ts/inbox-agent-reads.ts): filesasksrows from the token's chat and task, links checked as the project's,idempotencyKey→dedupe_key agent:<chat>:<key>, similar open items returned; respond stores an anchored comment and returns the item to the inbox; resolve closes a question/review/result with its latest reply message id (never a secret, approval or human task); update also returns the item. update/cancel bind project, chat and kind (question/review/result/task). Aresultanswered with no text ("Got it") closes withnotified_atset and wakes no one; a reply wakes the agent.request_human_inputis a blockingaskalias. Only a blocking question pauses a chat (readers filterblocking = 1). POST /api/projects/:projectId/sessions/:sessionId/stop— Stop a chat sessionGET /api/projects/:projectId/sessions/:sessionId/access— Shared-access summary:viewerAccess(owner/grantee/reader), owner, active grants (expiresAt,durationMinutes),undelivered(messages cancelled because their sender's access ended, newest first, at most 100,{ messageId, reason }) andserverTime. The session detail carries the same summaryPOST /api/projects/:projectId/sessions/:sessionId/access/grants— Share the chat with an active member, or (owner only) renew ({ userId, durationMinutes: 5|10|30|60, acknowledgeSharedCredentials: true }; no default duration;201new,200existing). ItsaccessomitsundeliveredDELETE /api/projects/:projectId/sessions/:sessionId/access/grants/:userId— Revoke now (cascades to grants that member issued and fails their undelivered prompts); returns{ revokedGrantIds, cancelledDeliveryIds, access }POST /api/projects/:projectId/sessions/:sessionId/sleepandPOST /api/projects/:projectId/sessions/:sessionId/agent-sessions/:agentSessionId/resume— Sleep or resume the chat (session writers; resources resolve as the owner)
Comment threads are scoped to the ProjectData Durable Object addressed by projectId; route authorization requires project task:read for list and project-wide inbox reads, and task:write for mutations; .../send also requires a session writer. Every route that drives a chat (prompt, cancel, stop, archive, comment send, idle reset, answering agent requests, sleep, resume, grant management) goes through requireSessionWriter (apps/api/src/services/session-access.ts): the owner, or a member with an unexpired grant, both active task:write members; others get 403. Grants end at expiresAt by server time. Full contract: apps/www/src/content/docs/docs/reference/api.md (Shared chat access). The DO rejects missing sessions, missing messages, and cross-session message anchors. Mutations return { thread, idempotent } or { thread, reply, idempotent }; successful first writes use HTTP 201 for create/reply and 200 for status transitions. Project session WebSocket listeners receive { type: "comment.thread.changed", payload: { sessionId, thread, reason } } with reason in thread_created | reply_created | marked_sent | resolved | reopened.
Task Management (Project Scoped)
POST /api/projects/:projectId/tasks— Create taskGET /api/projects/:projectId/tasks— List tasks (supportsstatus,minPriority,sort,limit,cursor)GET /api/projects/:projectId/tasks/:taskId— Get task detail (includes dependencies + blocked state)PATCH /api/projects/:projectId/tasks/:taskId— Update task fields (title,description,priority,parentTaskId)DELETE /api/projects/:projectId/tasks/:taskId— Delete taskPOST /api/projects/:projectId/tasks/:taskId/provider-limit/start-anyway— Owner-onlytask:writeoverride of a waiting admission hold (202 starting) or saved callback hold (202 waking, same account/profile and retained claim). The saved-session notice calls this Resume anyway. Snapshot/generation/authority/expiry are rechecked; changed waits return409.POST /api/projects/:projectId/tasks/:taskId/provider-limit/resume— Owner approves a blocked provider wait and resumes its retained snapshot or first-dispatch admission. Requirestask:write;202waking,409if no longer blocked or snapshot unavailable.POST /api/projects/:projectId/tasks/:taskId/status— Transition task statusPOST /api/projects/:projectId/tasks/:taskId/status/callback— Trusted callback status update for delegated tasksPOST /api/projects/:projectId/tasks/:taskId/build-started— VM-agent callback JWT endpoint that tells the TaskRunner a queued workspace build has started so it can reset the workspace-ready timeoutPOST /api/projects/:projectId/tasks/:taskId/dependencies— Add dependency edge (dependsOnTaskId)DELETE /api/projects/:projectId/tasks/:taskId/dependencies?dependsOnTaskId=...— Remove dependency edgePOST /api/projects/:projectId/tasks/:taskId/delegate— Delegate ready+unblocked task to owned running workspaceGET /api/projects/:projectId/tasks/:taskId/events— List append-only task status events
Search Input Limits
- The
ideas_readmethodsearch,tasks_readmethodsearch,knowledge_readmethodsearch, andsessions_readmethodsearchMCP tools search every retained term separately.SEARCH_QUERY_MAX_LENGTH(default4096) andSEARCH_QUERY_MAX_TERMS(default40, higher values clamp to the safe D1 parameter ceiling) are total-input guardrails;SEARCH_QUERY_MAX_TERM_LENGTH(default48) keeps each escaped LIKE term under SQLite's pattern budget. They return the effectivequery,queryTruncated, andqueryLimits. tasks_readmethodlistandtasks_readmethodsearchaccept any sharedTASK_STATUSESvalue asstatus(includingsleepingandready). Workspace-agent responses includehasMoreandnextCursor; passcursorto read the next page (operations/task-core.ts:listTasks).GET /api/projects/:projectId/knowledge/search?q=...,GET /api/sam/search?query=..., andGET /api/projects/:projectId/agent/search?query=...apply the same limits and return the same metadata alongside their results.- Oversized queries are simplified before FTS5 or LIKE evaluation, preventing SQLite pattern/parser errors while keeping all retained terms searchable.
Member event subscriptions
GET /api/projects/:projectId/event-subscriptions— Requires projecttask:read. Returns{ subscriptions, hasMore }, acceptingstate=active|cancelled|expired|any, boundedlimit, and optionalsessionId. Session filtering happens before the result limit.GET /api/projects/:projectId/event-subscriptions/:subscriptionId— Requires projecttask:read; returns{ subscription }within the authorized project.GET /api/projects/:projectId/event-subscriptions/:subscriptionId/deliveries— Requires projecttask:read; returns bounded{ deliveries, hasMore }with actual transport state/method, timestamps and terminal reason. Accepts only optional positivelimit, capped by event limits. Does not expose event payloads or match identities. Transport receipt and explicit acknowledgment remain distinct from agent action.POST /api/projects/:projectId/event-subscriptions/:subscriptionId/cancel— Requires projecttask:write; accepts only optional{ reason }. Cancels human/agent subscriptions through canonical cancellation, derivescancelledByfrom the authenticated human, and returns{ subscription, idempotent, changed }. System, policy and standing-watch subscriptions must be managed through their owning controls. Cancellation requests use the configured event metadata byte cap and reason limit. No platform caller identity is granted to members.
MCP Orchestration
start_workflow_run(requestKey, plan)/get_workflow_run(runId)— Single-owner durable VM-agent DAG runs. Explicit step profiles and prerequisite keys; idempotent submission, stable task/session identities, bounded predecessor handoffs, current membership/admission checks, and sharedsam.workflowlifecycle events. Failed prerequisites block dependents; runs reportneeds_attentionrather than false success. Project members read runs throughGET /api/projects/:projectId/workflows[/:runId](Automation → Workflows). See durable workflow contract for the full shape and Phase 0 limits.
tasks_readmethodagentslists active tasks (queued, delegated, in_progress, sleeping; superseded predecessors and the caller excluded) withbranch(output branch),workspaceBranchandoutputPrUrl. OptionalprHeadBranch/prUrlreturn only a PR's owners: output or workspace branch equals the head, or output PR URL equals the URL, or the description cites the URL (any link matches;services/agent-activity.ts:appendPullRequestOwnerCondition). A filtered response echoesfilter; malformed values returnINVALID_PARAMSand query failures return an error, never an empty list. Call it before merging, or dispatching work for, a PR another agent may own.send_message_to_subtaskandsend_durable_messageaccept same-project sleeping targets through durable prompt delivery; when that rollout is disabled, they return an explicit refusal instead of attempting a live-node send.send_durable_messagealso takesdeliveryIntent(queuedefault, orsteerfor classesnotify/deliveronly): a steer is added to the recipient's running turn without stopping it when its runtime can steer, and otherwise falls back visibly to an ordinary queued message. The chat composer routePOST /api/projects/:id/sessions/:sessionId/promptaccepts the samedeliveryIntent(see the public API doc's Live steering section).stop_subtaskallows direct-parent cancellation of a sleeping child without contacting its released runtime. Live-caller authorization and terminal-target exclusions remain enforced.
wait_for_subtasks— Task-agent-only tool that registers one durable wait for unique same-project task IDs.waitKeyis a required stable workflow-step idempotency key and must be reused after a lost response.conditionisall(default) orany; optionalwakeAfterSecondsis positive and server-capped. Persist workflow state before calling, then end the turn. ProjectData wakes the caller through exact-once durable prompt delivery when the condition or finite deadline resolves.dispatch_task— Create a direct child task subject to project dispatch depth and concurrency limits. AcceptsresourceRequirementsfor modern workload sizing and deprecatedvmSizefor legacy compatibility.resourceRequirementsis VM-only and conflicts withruntime: "cf-container". OptionalcoordinationChannel(a project channel name;agent-dm.reserved) is inherited by every descendant when omitted, copied byretry_subtaskand session recovery, added to the child description, and returned astask.coordinationChannelbyget_instructions.tasks_readmethodget/tasks_readmethodoutput— Read authoritative child status and output after a durable wake.sessions_readmethodtool_payloads— Retrieve ProjectData tool-call payload JSON that has been archived to private R2 and stripped from message rows. AcceptsmessageId,sessionId, orstartTime/endTimewith boundedlimit; returns payloads through the Worker without exposing R2 keys.sessions_readmethodresource_history— Read bounded workspace resource history for a session, task, or workspace through the current project scope. Returns a D1 summary/chunk index by default; the summary includes nullable, server-resolvedagentProfileId,skillId, andagentTypefrom records scoped to the same project and workspace. OptionalchunkIdlazy-loads downsampled R2 samples and sanitized tool-span correlation. Tool spans are correlation windows, not causal per-process attribution, and payloads omit prompts, commands, tool arguments/output, paths, environment, and secrets.create_project_event_subscription/list_project_event_subscriptions/get_project_event_subscription/cancel_project_event_subscription— Task-agent-only ProjectData event-subscription tools. The server derives project, owner, task, workspace, chat session, and agent-session identity from the MCP token; callers cannot supplyprojectId,owner,ownerScope, orcancelledBy. Creates are short-lived and capped by the MCP token lifetime. Filters are v1 exact/set matches forsource,eventType,subjectType,subjectId, andseverity. Requested delivery policy is recorded separately from matching/routing:existing_session_prompt,runtime_interruptandruntime_steerresolve toqueued_for_prompt_delivery(runtime_interruptwith theinterruptmailbox class, so its wakes may stop an in-flight turn — stop-and-deliver;runtime_steerwith thesteerdelivery intent, so a busy chat gets the batch inside its running turn without stopping it, and an idle or sleeping chat gets an ordinary wake;runtime_steeris the default whenrequestedDeliveryis omitted and the mode of SAM-managed agent-message subscriptions); other non-record-only modes resolve torecorded_not_injecteduntil their adapters are enabled. OptionalminWakeIntervalSeconds(waking modes only, at most the wake subscription lifetime, raised to the platform cooldown) wakes the chat at most once per interval, counted from when the previous wake reached the agent; events in between are bundled. The subscription returns the effectiveminWakeIntervalMs. The pull tools never steer runtimes or spawn tasks. Missing get/cancel requests error by default;required=falsereturnssubscription:null.list_subscription_events— Cursor-paginate missed or queued ProjectData event deliveries for one active, unexpired subscription visible to the calling task agent. Use it immediately aftercreate_project_event_subscription, after wake/resume, and during bounded polling. Responses include compact summaries, delivery IDs, delivery state, and an opaquenextCursor; they intentionally omit event payloads and raw payload references. Cursors are bound to the subscription and are bounded byPROJECT_EVENT_SUBSCRIPTION_EVENT_CURSOR_MAX_LENGTH; page size usesPROJECT_EVENT_LIST_LIMIT/PROJECT_EVENT_LIST_MAX.get_event— Fetch one durable ProjectData event by stable event ID when it is visible through an active, unexpired subscription owned by or targeted at the calling task agent. Use this after alist_subscription_eventssummary identifies work that needs full stored details such as normalized metadata, display data, raw payload reference, delivery key, payload fingerprint, and conflict counters.ack_event_delivery— Idempotently acknowledge a ProjectData pull delivery after the agent has processed it. Use thedeliveryIdreturned bylist_subscription_eventsorget_event. Repeated acks on the same delivery return the existingackedstate. Acks are scoped by the verified MCP token plus active/unexpired subscription visibility; missing or unauthorized event, subscription, and delivery reads use nondisclosing not-found-or-not-visible errors.list_incident_queue/get_incident/claim_incident/resolve_incident— Operations-project-only incident backlog tools (listed intools/listonly to Operations-project tokens). The server derives scope from the MCP token and the effective Operations project setting (feedback.projectId) (Admin → Integrations runtime value first, thenPLATFORM_FEEDBACK_PROJECT_IDfallback); agents cannot pass a project id. Claim/resolve require a task-scoped token and use bounded leases/CAS tokens. Returned evidence is allowlisted, bounded, recursively redacted, and labelled as untrusted; agents must not copy machine-generated diagnostics or feedback into public GitHub issues.ops_get_access_status— Operations-project debugger-tool gate report:operations.debuggerToolsmode (omitted outside the Operations project), allowed capabilitiesread/act, and denial reasons. Everyops_*tool must callrequireOperationsAccess(services/operations-access.ts): dial allows the capability, token project is the Operations project, token is task-scoped, task owner is an active superadmin in D1 now. Denials surface as JSON-RPC-32602withdata.reason. Gatedops_*calls are audited inoperations_audit_log(purged daily peroperations.auditRetentionDays; a failed retention read skips the purge).ops_get_access_statusis exempt from the per-call rule: it records task-scoped calls inside the Operations project only, not calls from other projects or tokens without a task.ops_*tools are listed only to the Operations project while the mode is notoff.- Read-only
ops_*tools (capabilityread, all throughrunOpsReadToolinroutes/mcp/ops-tool-runner.ts: gate, audit, untrusted envelope):ops_find_anomalies,ops_list_nodes,ops_get_node,ops_get_session_story,ops_timeline,ops_search_errors,ops_query_worker_logs(shares thecf-log-queryper-user rate limit withPOST /api/admin/observability/logs/queryviaservices/worker-log-query.ts),ops_node_logs,ops_node_system_info,ops_node_events,ops_node_containers,ops_workspace_agent_sessions,ops_capture_debug_package(library/debug-packages/<nodeId>/, purged daily afteroperations.debugPackageRetentionDays). Services:services/fleet-ops/; node calls shareservices/node-diagnostics-access.tswith the ownerGET /api/nodes/:id/{logs,system-info,events,containers,debug-package}routes. - Operations telemetry read tools (capability
read,routes/mcp/ops-telemetry-tools.ts):ops_why_is_node_alive(services/operations-node-liveness.ts:explainNodeLiveness, readsnode_lifecycle_decisions) andops_get_node_log_capture(services/node-log-capture-read.ts:readNodeLogCapture, gunzips the R2 black box capture, server-sidesource/containsfilter).ops_timelineincludesnode_lifecycle_decisions,node_log_capturesandsession_snapshot_traces(services/fleet-ops/timeline-sources-telemetry.ts);ops_get_nodereturnslogCaptures;ops_get_session_storyreturnssnapshotTracesbesidesnapshots. - Operations actions (capability
act,runOpsActTool,routes/mcp/ops-action-tools.ts):ops_request_action(action, targetId, reason, evidence?)creates anoperations_action_approvalsrow (auto-approved only forretry_snapshot/rerun_node_cleanupinread_auto_safe) and notifies the task owner (operations_approvalnotification).ops_execute_action(approvalId, action, targetId)claims the row with one CAS (approved→executed; guards: unexpired, same action, target, project and task authorityrecovery_source_task_id ?? id) and runs the executor (services/operations-actions/executors.ts, reusing the UI service functions as the resource owner). Decisions:GET /api/admin/operations/approvals,GET /api/admin/operations/approvals/:id,POST /api/admin/operations/approvals/:id/decision({decision: 'approve'|'deny', note?}, active superadmin; 409 when already decided/expired); delivered to the requesting chat as prompt source kindoperations_decision. override_task_state— requires a task-scoped token and re-checks the caller's currenttask:writecapability (same gates asstop_subtask).
wait_for_subtasks rejects conversation/direct-workspace agents, cross-project task IDs, terminal callers, duplicate IDs, mismatched caller sessions, invalid wait keys, and installations where durable prompt delivery is disabled. Reusing the same waitKey and intent is idempotent even after resolution; using a key for a different intent is rejected. Automatic wake prompts contain only trusted task IDs/statuses—peer-authored summaries, errors, and URLs must be fetched explicitly and treated as untrusted data.
Project event pull loop: create a subscription with the narrowest useful filter, call list_subscription_events until hasMore=false, call get_event only for summaries that require full stored details, process the work, then call ack_event_delivery for each returned delivery. The canonical storage is the ProjectData project_event_* schema; do not add or depend on parallel event_bus_* tables.
Administration (Superadmin Only)
GET|PUT|DELETE /api/admin/ai-allowance/:userId— Per-user AI allowance: budget ceilings plusallowedModelTiers(null= every tier, else a subset oflow-cost/standard/premium; unknown names are400). The AI proxy enforces the tiers on every platform-credential route (packages/ai-proxy/src/ai-model-tier-gate.ts): out-of-tier or untiered models get403 permission_error, an unreadable allowance fails closed; BYO-key passthrough is not restrictedGET /api/admin/health-cost?range=7d|30d|month— Superadmin Admin Health & cost read (installationHealthinpackages/operations): compute spend per currency, reuse, density, new-machine reasons, lifecycle latency, andcloudflare(the Cloudflare account's estimated USD cost this month from the daily snapshot)POST /api/admin/health-cost/cloudflare/refresh— Superadmin "Refresh now": runs the Cloudflare cost snapshot (runCloudflareCostSnapshot);429insideinsights.cloudflareCostRefreshMinSeconds; Cloudflare failures return200with a recorded statusGET /api/admin/tasks/stuck— List tasks currently in transient statesGET /api/admin/tasks/:taskId/reconciliation-diagnostics— Read the TaskRunner probe, task-scoped runtime liveness, eligibility threshold, reconciliation decision, and whether/where the bounded cursor page selects the task, without mutating task stateGET /api/admin/tasks/recent-failures— List recent failed tasks with error detailsGET /api/admin/observability/errors— Query platform errors; VM error rows include their same-installation diagnostic incident summaryGET /api/admin/observability/errors/:errorId/incident— Read one diagnostic incident summary and redacted previewGET /api/admin/observability/errors/:errorId/incident/artifacts/:artifactId/download— Stream one private diagnostic artifact through the authenticated Worker; R2 keys and URLs are never exposedGET /api/admin/project-events/:projectId/inspector— Superadmin-only read view for one project's ProjectData event subscriptions, recent normalized events, matches, delivery batches, attempts, and storage accounting. The response is bounded bylimitand intentionally omits raw payload references, event metadata, idempotency keys, and raw model/event content beyond normalized untrusted display summaries.GET /api/admin/project-data/storage— List latest per-project ProjectData storage telemetry from D1 (projectId,status,limitfilters), including growth forecast, cleanup health, reclaimable bytes, category breakdown JSON, and last alert reasonGET /api/admin/project-data/storage/history— List append-only ProjectData storage telemetry history from D1 (projectId,status,cleanupHealth,limitfilters) for growth and cleanup-health trendsGET /api/admin/project-data/storage/:projectId/archive-sharding/state— D1-only archive-sharding rollout summary for one project, optionally scoped bysessionId, including complete journal/session-location state counts, project circuit breaker state, bounded recent migrations/session locations,recentMigrationsHasMore/locationsHasMore, and bounded row-fault warnings for malformed read rowsGET /api/admin/project-data/storage/archive-sharding/problem-migrations— Bounded D1 list of failed, poisoned, or frozen archive-sharding migrations, optionally filtered byprojectIdandsessionId; malformed read rows are skipped and returned as bounded warnings; rows that need a human (failed,poisoned, operator-frozen) sort before self-healingprecopy_refusedrows. Afrozenrow witherror_code = precopy_refusedis a session the root object refused before any copy (itserror_messagecarries the invariant, e.g.active_session_state: ...); its location is already back atroot, it needs no abandon, and the unscoped sweep skips it forPROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MSPOST /api/admin/project-data/storage/:projectId/archive-sharding/canary— Superadmin-only scoped manual archive-sharding dry-run/canary. Defaults to{ dryRun: true }; dry-runs do not requirePROJECT_DATA_ARCHIVE_SHARDING_ENABLED=trueorPROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED=trueand select only the requested project plus optionalsessionId. Non-dry runs requirereasonand fail closed unless exact archive routing is active. The unscoped scheduled sweep has its own fail-closedPROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLEDgate.POST /api/admin/project-data/storage/:projectId/archive-sharding/freeze— Freeze non-terminal archive migrations for one project, freeze migrating session locations, and set the project archive circuit breaker tofrozenwith an explicitreasonPOST /api/admin/project-data/storage/:projectId/archive-sharding/circuit-breaker— Set the project archive circuit breaker toclosed,open, orfrozenwith an explicitreason; closing allows future work but does not thaw existing frozen migrationsPOST /api/admin/project-data/storage/:projectId/archive-sharding/unfreeze— Alias for closing the project archive circuit breaker with an explicitreason; frozen migrations remain frozen until copy-back (source already deleted) or abandon (source intact) resolves themGET /api/admin/project-data/storage/:projectId/archive-sharding/frozen-intents— Bounded inspection of failed/poisoned/frozen migrations using existing source/target DO inspection helpers; malformed journal rows are skipped with bounded warnings; detail inspection defaults to 5 rows and rejects limits above 10 to cap hot ProjectData DO fan-out;frozen/precopy_refusedrows are excluded because a pre-copy refusal created nothing on either object to inspectPOST /api/admin/project-data/storage/:projectId/archive-sharding/migrations/:migrationId/copy-back— Invoke the existing safe archive copy-back helper for a migration that belongs to the project; requires explicitreasonand exact archive routing to be enabled. Only for migrations whose source transcript was already deleted (source_deleted/published)POST /api/admin/project-data/storage/:projectId/archive-sharding/migrations/:migrationId/abandon— Abandon a migration that never reached source deletion (candidate..recovery_manifest_persisted,failed,poisoned,frozen): drops the partial shard copy and the root source intent, freezes the journal asoperator_abandonedwithout opening the project circuit breaker, and returns the session location torootso the session reads again. Reserves the journal lease (epoch bump) before touching any object, removes the root source intent under the source transcript lock BEFORE dropping the shard copy, and releases the reservation if a step fails. Requires explicit non-blankreason(400 otherwise); refuses with 400 once the source was deleted (use copy-back), while an in-flight migration still holds a live lease (wait forPROJECT_DATA_ARCHIVE_LEASE_MSor freeze the project first), on a project mismatch, or for an unknown migration. Idempotent on rerunPOST /api/admin/project-data/storage/:projectId/measure— Force one ProjectDatadatabaseSizemeasurement and D1 telemetry upsertPOST /api/admin/project-data/storage/:projectId/relief-measure— Run one strictly bounded, cursor-resumable ProjectData storage-relief measurement slice for grouped/FTS derived rows, legacy tool payload stock, and staleoversizedattempts now below the archive cap; never performs the old full hot-object scanPOST /api/admin/project-data/storage/:projectId/tool-payload-cleanup— Superadmin-only explicit manual ProjectData tool-payload archival cleanup slice for one project. RequiresreasonandidempotencyKey, accepts optionalbatchRows,batchBytes, andwallTimeMscapped by env-backed hard maxima, bypasses automatic cleanup enablement, reuses archive-confirmed-before-delete cleanup semantics, and returns termination/reclaim/cooldown telemetry. Completed same-key retries replay the stored result; crashed in-progress same-key retries are held until cooldown and then can retry.POST /api/admin/project-data/storage/:projectId/grouped-fts-cleanup— Run one explicitly enabled, production-disabled canary slice that removes old terminal-session grouped message rows and external-content FTS entries while preserving rawchat_messagesPOST /api/admin/project-data/storage/:projectId/grouped-fts-wall-recovery— Superadmin storage relief that still works at the hard per-object cap: prunes grouped/FTS search rows of terminal sessions older than the grouped/FTS minimum age, largest first and delete-first, never touchingchat_messages. Requiresreason,dryRun,maxRows,maxBytes,maxSessions(bounded byPROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_*ceilings); optionalskipSessionIdsbypasses a session whose page keeps failing;dryRun: truereports without writingPOST /api/admin/project-data/storage/:projectId/emergency-purge— Run a bounded ProjectData emergency purge of oldestactivity_eventsandacp_session_eventsrows only
Agent Sessions
GET /api/workspaces/:id/agent-sessions— List workspace agent sessionsPOST /api/workspaces/:id/agent-sessions— Create agent session (optionalworktreePathbinds session to a worktree)PATCH /api/workspaces/:id/agent-sessions/:sessionId— Rename agent session labelPOST /api/workspaces/:id/agent-sessions/:sessionId/stop— Stop agent session
VM Agent direct execution protocol (node-management JWT)
GET /workspaces/:workspaceId/agent-capabilities— Discover VM execution protocol version, durable receipt support, checkpoint-rollover support, configured timing bounds, andsessionRuntimeContract: { supported: true, version: 1 }. Contract-aware restore requires this live capability before POST restore.POST /workspaces/:workspaceId/agent-sessions/:sessionId/start— Start a session; optional protocol-v1deliveryIddurably guards the initial promptPOST /workspaces/:workspaceId/agent-sessions/:sessionId/prompt— Send a follow-up; optional protocol-v1deliveryIddurably guards agent invocationGET /workspaces/:workspaceId/agent-sessions/:sessionId/prompt-receipts/:deliveryId— Reconcileaccepted,in_flight,completed, or cross-runtimeambiguousdelivery statePOST /workspaces/:workspaceId/agent-sessions/:sessionId/checkpoint-rollovers— Submit an idempotent protocol-v1 graceful/forced strict same-session rollover operationGET /workspaces/:workspaceId/agent-sessions/:sessionId/checkpoint-rollovers/:operationId— Reconcile rollover state
All direct routes require the workspace-scoped node-management Bearer token. Omitting new version/delivery fields preserves the legacy start/prompt behavior. Automatic rollover remains disabled until a control-plane caller invokes it.
Agent Profiles and Skills
Agent profile and skill create/update surfaces accept resourceRequirements as an object and resourceRequirementsJson as a compatibility JSON string/null. Modern object input takes precedence inside the same request body. Known fields use the same bounded client/API validation contract as task submit; unknown JSON metadata is preserved for compatibility. Deprecated vmSizeOverride remains accepted without client-side tier-to-hardware expansion.
Agent Settings
GET /api/agent-settings/:agentType— Get user's agent settingsPUT /api/agent-settings/:agentType— Upsert agent settings (model, permissionMode)DELETE /api/agent-settings/:agentType— Reset agent settings to defaults
Notifications
GET /api/notifications— List notifications (supportscursor,limit,filter,type,projectId,sessionId)GET /api/notifications/unread-count— Get unread notification countPOST /api/notifications/:id/read— Mark a notification as readPOST /api/notifications/read-all— Mark all notifications as readPOST /api/notifications/:id/dismiss— Dismiss a notificationGET /api/notifications/preferences— Get notification preferencesPUT /api/notifications/preferences— Update a notification preferencePOST /api/notifications/push/subscriptions— Add or refresh the authenticated browser's PushSubscriptionGET /api/notifications/push/subscriptions— List the authenticated user's PushSubscriptionsDELETE /api/notifications/push/subscriptions— Remove the authenticated user's matching endpoint ({ endpoint })GET /api/notifications/ws— WebSocket upgrade for real-time notification deliveryGET /api/config/vapid-public-key— Public runtime VAPID key used when creating a browser PushSubscription
Automation Triggers (Project Scoped)
POST /api/projects/:projectId/triggers— Create a cron, GitHub, generic webhook, or private incident trigger. Webhook creation requiresagentProfileIdandwebhookConfig. A token (sam_bearer) webhook's response includes a one-timewebhookCredential; a signed webhook's does not: save the provider's signing secret withPUT .../webhook/signing-secret(or on the trigger page viawebhookConfig.setup.secretEntryUrl). Incident triggers are intended for the configured private Operations project and fire from the scheduled incident backlog sweep.GET /api/projects/:projectId/triggers— List triggers with safe source configuration. Webhook tokens are redacted totokenLastFour.GET /api/projects/:projectId/triggers/:triggerId— Get trigger details and recent execution history.PATCH /api/projects/:projectId/triggers/:triggerId— Update common trigger settings or source-specific GitHub/webhook configuration. Resuming starts a fresh auto-pause failure window while retaining execution history.DELETE /api/projects/:projectId/triggers/:triggerId— Delete a trigger and cascading source configuration, delivery audit, and execution history.POST /api/projects/:projectId/triggers/github/filter-preview— Read-only bounded draft-filter test against same-repository/installation/event deliveries. Accepts GitHub config; returns metadata and nullable match results (payload unavailable is distinct). Requires project task-read permission; no replay or execution.POST /api/projects/:projectId/triggers/:triggerId/test— Preview the cron template context.POST /api/projects/:projectId/triggers/:triggerId/run— Submit a manual trigger execution. Webhook triggers accept optional{ payload, headers }preview context.POST /api/projects/:projectId/triggers/:triggerId/webhook/preview— Render a webhook template and evaluate configured filters without creating an execution.POST /api/projects/:projectId/triggers/:triggerId/webhook/rotate— Rotate the webhook bearer token and return the replacement once.GET /api/projects/:projectId/triggers/:triggerId/webhook/deliveries— List redacted webhook delivery audit metadata (limit,cursor).POST /api/webhooks/ingest— Public generic webhook ingress. RequiresAuthorization: Bearer <token>,Content-Type: application/json, and a JSON object body. Supports optionalIdempotency-Key.POST /api/webhooks/in/:triggerId— Public address of one signed webhook trigger (slack_v0,hmac_sha256_body). Verifies the sender's HMAC over the raw body with the trigger's stored signing secret, answers Slackurl_verificationwith the challenge, uses the sender's event ID as the duplicate key, and commits a verified event to the durable trigger queue before answering202. A202does not always mean queued: onlyqueued: truedoes;duplicate,filtered,inactiveandignored(missing_event_id,repeated_body) are answered202without a run.401bad or stale signature,503no secret saved or unreadable conditions,429rate limited or queue full. Errors are{ accepted: false, error, message }.PUT /api/projects/:projectId/triggers/:triggerId/webhook/signing-secret— Save or replace a signed trigger's signing secret ({ secret }, project write access). Write-only: stored encrypted and never returned.
Trigger create/update accepts resourceRequirements or resourceRequirementsJson and persists normalized JSON on the trigger layer. Omitted fields inherit lower layers; explicit null clears the trigger-layer JSON. Deprecated vmSizeOverride remains accepted as small, medium, large, or null.
The MCP create_trigger tool creates cron, GitHub, and webhook triggers in the token’s current project. Omitting sourceType defaults to cron for existing callers. For GitHub, use sourceType: "github" and githubConfig: { eventType, filters } without cron fields; supported events are issues, issue_comment, pull_request, and push. update_trigger and REST PATCH can replace GitHub event/filter configuration on existing GitHub triggers; send filters: {} to clear filters. Cron fields only apply to cron triggers, and source type cannot be changed. Webhook creation requires an explicit project-local agentProfileId and webhookConfig. It returns webhookClaim metadata, never the credential. Redeem its expiring URL with POST /mcp/webhook-claims/:claimId using the originating workspace/session MCP bearer token and current project write membership. The atomic redemption returns non-cacheable plain text and persists only the credential hash. Rotation revokes pending claims. Incident creation, webhook filter management, preview, and rotation remain on the authenticated UI/REST surface. For a signed webhook (webhookConfig.verification.scheme slack_v0 or hmac_sha256_body) create_trigger returns webhookConfig.endpointUrl and webhookConfig.setup.secretEntryUrl instead of a claim and refuses a signing secret argument; the secret is saved by a person through the REST route above. get_trigger reads one trigger with its redacted webhook configuration, setup state, last refusal and recent calls.
Workflow Runs (Project Scoped)
GET /api/projects/:projectId/workflows— List workflow runs newest first for active members withtask:read(status=active|completed|needs_attention,limitdefault 20 / max 50, opaquecursor). Returns{ runs, nextCursor }; list step reasons are cut to 300 characters.GET /api/projects/:projectId/workflows/:runId— One workflow run as{ run: WorkflowRunDetail }: steps with instructions, prerequisites, profile, task/chat IDs, timing, outputs and reasons, plus retained activity. Non-disclosing 404 for runs outside the project. Shapes inpackages/shared/src/types/workflow.ts; see durable workflow contract.
VM Communication (Callback Endpoints)
POST /api/nodes/:id/ready— Node Agent ready callbackPOST /api/nodes/:id/heartbeat— Node Agent heartbeat callbackPOST /api/nodes/:id/errors— VM agent error report batch. An optional stable ULIDincidentIdmakes persistence idempotent; error-level entries create the same-installation diagnostic incident before acknowledgment.POST /api/nodes/:id/diagnostic-incidents/:incidentId/artifacts— Register bounded, redacted VM evidence metadata using the node callback JWTPUT /api/nodes/:id/diagnostic-incidents/:incidentId/artifacts/:artifactId/content— Stream the registered gzip artifact into private R2 storage using the node callback JWTPOST /api/workspaces/:id/ready— Workspace ready callbackPOST /api/workspaces/:id/provisioning-failed— Workspace provisioning failure callback (sets workspace toerror)POST /api/workspaces/:id/heartbeat— Workspace activity heartbeat callbackGET /api/workspaces/:id/runtime— Workspace runtime metadata callback (repository/branch for recovery)POST /api/workspaces/:id/callback-token/renew— Renew a workspace callback token before it expires. Two proofs: the current, unexpired workspace token inAuthorization, and{ nodeId, nodeToken }(the hosting node's node-scoped token) in the body. The workspace must becreating/running/recovery, bound to that VM node (never an Instantcf-containernode), owned by the node's user, and on a non-terminal node; otherwise 401/403/410 (NODE_CALLBACK_UNAUTHORIZED/NODE_CALLBACK_FORBIDDENwhen only the node proof failed). Authenticated attempts count againstRATE_LIMIT_CALLBACK_TOKEN_RENEWALper workspace per window (429RATE_LIMIT_EXCEEDEDwithRetry-After). A token younger thanCALLBACK_TOKEN_REFRESH_THRESHOLD_RATIOof its lifetime gets{ renewed: false }; otherwise{ renewed: true, token, expiresAt }, where the token keeps the chain's firstiatasgen_iat. Responses carryCache-Control: no-storePOST /api/workspaces/:id/mcp-token/rotate— VM agent callback after a restart or rebuild rotated the workspace's credential generation.Authorizationcarries the new runtime's workspace callback token; the body is{ mcpToken }, an agent session's retired SAM MCP token. Returns{ token }: a replacement with the same context andcreatedAt(so the same hard lifetime) for the current generation, and the old token is revoked; an already-current token is returned unchanged. 401 for a retired or invalid callback token, 403 when the MCP token belongs to another workspace, user or project, 404 for an unknown or expired MCP token, 410 when the workspace is not active.Cache-Control: no-storePOST /api/workspaces/:id/boot-log— Workspace boot progress log callbackPOST /api/workspaces/:id/agent-settings— Workspace agent settings callback (model, permissionMode)POST /api/projects/:id/workspaces/:workspaceId/eviction— VM-agent callback JWT endpoint that validates node/workspace/runtime-generation identity and successful container stop, atomically marks the workspaceevictedand its exact captured snapshot sleeping while closing usage/agent sessions, sleeps the bound chat before replay-safe ProjectData finalization through NodeLifecycle, then starts the normal snapshot wake on another VM. An uncaptured snapshot or unstopped container returns 409 without mutation; a stale generation returns 410; failed finalization is retryable. Explicit restart requires renewed capacity admission and rotates the runtime generationPOST /api/workspaces/:id/session-snapshot/prepare— Prepare deterministic R2 artifact uploads for the workspace-scoped chat snapshotPOST /api/workspaces/:id/session-snapshot/artifacts/:artifact/upload-url— Authorize a short-lived, exact-length/checksum-bound private-R2 PUT forhomeorwip. Requires the workspace callback bearer; current-agent relays additionally present their independent node-scoped callback identity.PUT /api/workspaces/:id/session-snapshot/artifacts/:artifact— Upload a bounded HOME tar or Git WIP bundle with a workspace callback tokenPOST /api/workspaces/:id/session-snapshot/complete— Verify artifact metadata and commit the snapshot manifestPOST /api/workspaces/:id/session-snapshot/failure— Persist a generation-scoped VM-agent capture failure so sleep fallback can degrade with the real capture errorGET /api/workspaces/:id/session-snapshot/restore— Fetch strict restore metadata and signed artifact pathsPOST /api/workspaces/:id/session-snapshot/restore-result— Persist the VM Agent's strict restore resultPOST /api/bootstrap/:token— Redeem one-time bootstrap token (credentials + git identity)POST /api/agent/ready— VM agent ready callbackPOST /api/agent/activity— VM agent activity report
VM Agent snapshot relay (busy legacy node compatibility)
PUT /session-snapshot-upload-relay?authorizationPath=...— A current same-user managed VM streams a busy legacy agent's bounded snapshot to the checksum-bound R2 URL returned by the control plane. The relay supplies independent workspace- and node-scoped callback credentials, accepts only the exact relative snapshot authorization route, uses the configurable snapshot-operation deadline, and forwards neither bearer to R2.
Terminal Access
POST /api/terminal/token— Get terminal WebSocket token
Git Integration (VM Agent direct — browser calls via ws-{id} subdomain)
GET /workspaces/:id/worktrees— List git worktrees for the workspacePOST /workspaces/:id/worktrees— Create a git worktreeDELETE /workspaces/:id/worktrees?path=...&force=true|false— Remove a git worktreeGET /workspaces/:id/git/status?worktree=...— Git status (staged, unstaged, untracked files)GET /workspaces/:id/git/diff?path=...&staged=true|false&worktree=...— Unified diff for a single fileGET /workspaces/:id/git/file?path=...&ref=HEAD&worktree=...— Full file content
File Browser (VM Agent direct — browser calls via ws-{id} subdomain)
GET /workspaces/:id/files/list?path=.&worktree=...— Directory listingGET /workspaces/:id/files/find?worktree=...— Recursive flat file index
With confine=workdir, the VM agent's list, raw, download, git file and git diff endpoints accept only relative paths, resolve symlinks inside the workspace, refuse anything outside the working tree or in any .git directory (404, .. included, although the control plane already rejects ./.. segments with 400), and answer X-SAM-Path-Confinement: workdir (packages/vm-agent/internal/server/file_confinement.go). The control plane sends it for a grantee's reads through /api/projects/:projectId/sessions/:sessionId/files/* and /git/*, and returns 409 when an older agent does not confirm it. Session file upload stays owner-only.
Agent Model Calls
GET /api/agent-models/catalog— Cloudflare-hosted Workers AI model catalog (any signed-in user); cached peraiModels.catalogCacheSecondsGET /api/projects/:projectId/agent-models— Project's model selection, monthly budget, and this month's usage (active members)PUT /api/projects/:projectId/agent-models— Change the project's model selection (models) or monthly budget (monthlyBudgetUsd);nullresets either to the default (requiresproject:update: owners and admins)
MCP tools list_ai_models / run_ai_model (routes/mcp/agent-model-tools.ts, services in services/agent-models/) let a running agent call Cloudflare-hosted Workers AI models besides its own chat model. Access resolves skill → profile → project → SAM defaults (the most specific non-null selection wins; [] turns calls off, null inherits — agent_models_json on skills, agent_profiles, and projects). Each call reserves its estimated cost atomically before running and settles after, against a per-project, per-UTC-month budget (agent_model_monthly_usage, agent_model_usage_by_model); a call that times out after the model ran is charged its reservation. Websocket-only models and stream: true are refused. Files pass through the workspace only: {"$file": path} in an input, {"$savedFile": {path, contentType, sizeBytes}} under .ai-outputs/ (or outputDirectory) in an output. Twelve aiModels.* admin settings gate and bound the feature (Admin → Settings → AI models). The MCP profile and skill tools do not accept agentModels, so agents cannot change their own access. Public guide: apps/www/src/content/docs/docs/guides/ai-models-for-agents.md.
Voice Transcription
POST /api/transcribe— Transcribe audio via Workers AI (Whisper). Rate-limited per user (RATE_LIMIT_TRANSCRIBE, default 30 perRATE_LIMIT_TRANSCRIBE_WINDOW_SECONDS= 60)
Client Error Reporting
POST /api/client-errors— Receive batched client-side errors for Workers observability logging
Authentication (BetterAuth)
POST /api/auth/sign-in/social— GitHub OAuth loginGET /api/auth/session— Get current sessionPOST /api/auth/sign-out— Sign out
Credentials
GET /api/credentials— Get the user's cloud provider connections. GCP returns safeauthType, project, service-account email, zone, optional key ID metadata, andapiIssues(required Google APIs that are off, refused, or never enabled by setup); encrypted source credentials are never returned, and malformed rows are isolated.POST /api/credentials— Save a cloud provider credential. New GCP WIF writes use the versionedworkload-identityvariant.DELETE /api/credentials/:provider— Delete the stored cloud provider credential. GCP deletion atomically removes legacy and generated composable copies and cached derivatives; it does not revoke Google-managed keys.POST /api/cc/attachments— Pin one of the caller's accounts as their default (noprojectId) or to a project (replaces their previous pin for that agent; requirestask:write, since it changes only the caller's own runs).GET /api/cc/profile-attachments— The caller's personal profile pins (profile and project names included). Pins never apply to other members.GET /api/cc/profile-attachments/profiles?agentType=— Profiles the caller may pin to: own global profiles plus project profiles where they havetask:write; capped by admin settingchat.profilePinCandidateLimit, returnstruncated/limit.POST /api/cc/profile-attachments—{ configurationId, profileId }; replaces the caller's pin for that profile and agent. Refuses paused accounts and accounts for another agent; missing and foreign profiles both 404. Resolution: profile pin → project pin → default → platform (explainResolution).DELETE /api/cc/profile-attachments/:id— Remove one of the caller's profile pins.
GCP
PUT /api/gcp/service-account— Validate and atomically save or rotate an OAuth-free service-account JSON credential. Body:{ serviceAccountJson, defaultZone }. Verification and the mutation rate limit run before replacement; the response contains safe metadata only.POST /api/gcp/setup— Complete the recommended keyless WIF setup using an OAuth handle and store the versioned WIF credential.POST /api/gcp/projects— List Google Cloud projects for a short-lived infrastructure OAuth handle.POST /api/gcp/verify— Verify the currently stored GCP credential, dispatching to WIF or service-account authentication, then probe Cloud Billing and returnbillingCheckplus the credential'sapiIssues(the Settings "Check again" action).
The service-account flow ignores uploaded endpoint fields and exchanges RS256 assertions only at SAM's fixed Google token endpoint.
GitHub Integration
GET /api/github/installations— List user's GitHub App installationsGET /api/github/repositories— List accessible repositoriesGET /api/github/branches?repository=owner/repo— List branches for a repository
Error Format
All API errors follow this format:
{
error: "error_code",
message: "Human-readable description"
}
Agent event channels
Agents can inspect a channel's subscriber roster with list_channel_subscribers(channel,state?,cursor?,limit?). It requires an active task-backed agent and existing project task:read access; the project comes from the verified token. Results include subscription ID, owner type/ID/name, target session/task/runtime/agent IDs, effective state, expiry and creation time across owners. The default active state excludes elapsed expiry even before cleanup; cancelled, expired and any are also supported. Every filter dimension must match a canonical channel publication (sam.agent_channel, agent.channel.published, subject type agent_channel, the channel name, severity info); omitted dimensions and matching exact/set values count. The roster includes broad subscriptions, not just explicit channel follows, and does not depend on the current channel catalog generation. This is filter eligibility; routing and wake rules still apply.
All matching and state filtering happens before the configured page limit. Continue nextCursor with the same channel and state until hasMore is false; the cursor is project/channel/state-bound and pages reflect current state rather than a frozen snapshot. No subscription reasons, private filters, idempotency keys, event payloads or delivery receipts are returned. A subscription does not prove that an agent read, acknowledged or acted on any message. Existing subscription get/cancel tools remain restricted to the caller's own subscriptions.
Follow defaults to record_only. Follow/catch-up return canonical wakeInstructions
for resolved same-chat prompt delivery; record-only responses return null.
GET /api/projects/:projectId/event-channels lists bounded lifetime catalog summaries (cursor, limit; response channels, nextCursor). GET /api/projects/:projectId/event-channels/:channel/history returns a bounded snapshot (events, cursor, watermark, hasMore, retentionGap). Both use active project task:read membership. Catalog counts are lifetime counts within a generation, never retained-event counts.
MCP names: publish_channel_event(channel,message,idempotencyKey), list_event_channels(cursor?,limit?), get_channel_history(channel,cursor?,limit?), follow_event_channel(channel,idempotencyKey,cursor?,requestedDelivery?,reason?,expiresAt?,minWakeIntervalSeconds?), catch_up_event_channel(subscriptionId,limit?). Source/type/actor/project/target identity are verified/server-derived; publishing/follow/catch-up require task:write and active agent authority. Channel source is sam.agent_channel, type agent.channel.published, subject type agent_channel with stable channel name. Read text is untrusted evidence. Canonical list/read/ack performs delivery after catch-up.
A publication never matches the publisher's own prompt-delivery subscription (live or catch-up), so it never wakes its author; record-only feeds still include own events. publish_channel_event rejects names starting with agent-dm., which are reserved for SAM agent messaging and capped separately (AGENT_MESSAGE_CHANNEL_MAX_CHANNELS).
Managed deployments enable AGENT_MESSAGE_CHANNELS_ENABLED=true; it requires event wakes and durable prompt delivery. With the flag enabled: send_durable_message notify/deliver (except deliveryIntent: "steer", which always goes through durable delivery into the recipient's running turn) and send_message_to_subtask publish to the canonical agent-dm.<pair digest> channel with SAM-managed prompt-delivery subscriptions for both chats in one ProjectData transaction (sendAgentChannelMessage). The recipient gets a SAM-authored IDs-only notice and reads the text with get_event (metadata.actor is server-derived). Responses: accepted: true, delivered: false, transport: "agent_message_channel", channel, eventId, sequence, replayed, idempotencyKey. Optional idempotencyKey replays lost-response retries; changed content conflicts. Urgent classes keep stop-and-deliver. Pair events match only the two participants' subscriptions; follow_event_channel rejects agent-dm. names and subscription keys starting sam-agent-message: are reserved. Managed subscriptions hold at most AGENT_MESSAGE_MAX_ACTIVE_SUBSCRIPTIONS of the project cap (idle ones on other pairs are released; busy ones refuse with outcome: "capacity"). Errors carry outcome recipient_unavailable, conflict, capacity or rejected.
Follow captures the current canonical sequence watermark and live subscription atomically. Catch-up pages insert unique canonical matches and advance only a contiguous page; capacity or retention gaps roll back without skipping events. Cursor generation/scope/expiry are validated; follow replay preserves immutable start and deadline. Catalog reclamation never changes name-based live routing. Retained event key replays bypass admission quota; changed message conflicts; idempotency ends with canonical retention. Rate limiting is a shared fixed project window, so boundary bursts can consume two windows. Configuration is documented in the public configuration reference.
Schedules and standing watches
Authenticated project members can inspect /api/projects/:projectId/schedules and
/standing-watches with GET, and /:id for a single record. Project writers can
POST to create. Schedule POST /:id/reschedule, /:id/cancel, and /:id/reconcile require
expectedVersion; watch POST /:id/update, /:id/pause (with paused boolean),
and /:id/revoke also require a version. A stale version returns conflict.
Schedule list cursors are scoped to project and optional sessionId, including
creator and message-target sessions. Watch contextual lists include message targets.
Task-scoped MCP exposes schedules_write method create, schedules_read method list,
schedules_read method get, schedules_write method reschedule, schedules_write method cancel, and
schedules_write method reconcile.
Creator/project identity comes from the verified caller. Human-owned standing-watch
mutations are deliberately absent from agent tools. A message_session target must be
the creator's own chat, or (REST only, not MCP) a chat shared with them while the grant
lasts; the grant is recorded and re-checked at fire time and before delivery, and revoke or
expiry cancels it. Standing watches may target only chats their creator owns, and only the
creator may change a watch's action. Schedule actions are
message_session (sessionId, prompt) or start_session (prompt, optional
agentProfileId/skillId). dueAt and optional expiresAt are UTC epoch milliseconds;
displayTimezone is IANA. Creation requires a reusable idempotencyKey.
Admission is the cancellation boundary. Cancelling after admission reports
actionAlreadyAdmitted; it does not retract a queued prompt or task. Reads report
resulting event/delivery/task/session IDs, attempts and errors. Busy targets queue;
expired authority, archive, finite grace or uncertain receipts are visible outcomes.
Schedule GET/list/create/mutation responses include schedule.execution, a bounded read-only
observation of canonical task/inbox status, separately from schedule admission state.
Reconcile accepts { expectedVersion, retrySubmission?: boolean }; the default reads receipts
without compute wake or prompt replay. Known running receipts restore monitoring; only terminal
receipts release watch concurrency. Explicit task retry requires a matching queued reserved
checkpoint, current creator authority, and the original unexpired submission deadline. It reuses
all reserved identities and immutable intent. Missing/ambiguous receipts are never proof of
completion or permission to replay. The response includes recovery.outcome and
execution.retrySubmissionAllowed; original deadlines cannot be extended by recovery.
Fresh VM boot failure callback
POST /api/nodes/:id/boot-failure accepts { "reason": "origin_ca_bootstrap" } (also vm_agent_download) with an explicit node-scoped callback JWT. Only managed VMs before their first heartbeat/ready signal can record a failure. Returns { "accepted": true } when recorded, { "accepted": false } for a delayed report after startup, 401 for invalid/mismatched identity, 403 for wrong scope or unmanaged runtime, and 410 for terminal/missing nodes. Arbitrary diagnostics are not accepted. TaskRunner polls this signal and confirms failed-node deletion before a bounded fresh-VM replacement (default one).
POST /api/workspaces/:id/lifecycle-timings— Workspace callback JWT; fixed bounded numeric lifecycle phase summary emitted to structured logs only. Seedocs/notes/session-lifecycle-timings.md.
SAM Connector
/connect/mcp— user-level Streamable HTTP MCP, OAuth or PAT bearer authentication; separate from workspacesam-mcp.GET /.well-known/oauth-protected-resource/connect/mcp— resource metadata.GET /.well-known/oauth-authorization-server— authorization-server discovery./oauth/authorize,/oauth/token,/oauth/register,/oauth/revoke— authorization code with PKCE, token exchange/refresh, dynamic registration, revocation.GET /api/connector/settings— public-to-session Connector availability and URL.GET /api/connector/consent?<OAuth query>— authenticated consent preview with bound handle;POST{handle, approve}returns{redirectTo}.GET /api/connector/connections,DELETE /api/connector/connections/:id— own grants and revoke.GET/PATCH /api/admin/connector/settings— effective setting values with source/update metadata and runtime overrides. PATCH only changed keys; anullvalue removes that key’s override and restores its environment fallback or built-in default.GET /api/admin/connector/connections,DELETE /api/admin/connector/connections/:id— all grants and admin revoke.GET /api/admin/connector/clients,PATCH /api/admin/connector/clients/:id{blocked}— registered clients and block/unblock.
Connector connection/client inventories accept cursor and return nextCursor. Own connections are enumerated through the OAuth provider's grant listing; the admin view uses the D1 grant index. Settings/Admin revocation and client blocking take effect immediately through D1 gates. Refresh-token reuse revokes the entire connection, enforced by atomic D1 admission after provider validation. OAuth protocol revocation is RFC 7009 at /oauth/revoke.
External operational MCP tools
The full external registry (39 tools, 28 read-only) includes sam_chat_interrupt, sam_chat_status,
sam_chat_delivery_get, sam_chat_interactions, sam_work_changes,
sam_chat_jobs_list, and sam_operation_get; transcript reads sam_chat_read (whole messages by
default, unit:"rows" for stored rows) and sam_chat_message_get; sam_team_status; schedules
sam_schedules_list|get|create|update|cancel (one-off DO schedules + cron triggers); channels
sam_channels_list, sam_channel_history, sam_channel_get, sam_channel_subscription_cancel
(no app posting); account monitoring sam_usage_get (provider usage per quota pool, freshness,
exhausted/nextResetAt) with sam_profiles_list.account (state, tier, opaque poolId,
accountName; services/profile-account-bindings.ts over the shared selection in
services/agent-credential-selection.ts, no decryption); sam_chat_start takes a
one-chat model/effort; sam_chats_list rows carry operational task state and
sam_tasks_list rows parentTaskId/executionStep/sessionId. Agent questions (attention markers) appear in sam_chat_read.pendingAttention,
sam_chat_interactions.attention and the inbox. Operational session reads require
current session-writer authority; operation receipts are actor/project scoped.
Interrupt requires a requestKey and preserves the task/workspace. Reads never
contact or wake runtimes. Changes are coalesced snapshots, not a durable event
stream. Job observations cover internal secret-execution responses only; generic
harness history is unsupported. Safe diagnostics return allowlisted categories,
never raw errors/logs/output. Pending and settled interaction reads do not approve
anything; every agent answer still requires explicit user confirmation.
Managed runtime secret execution
exec_with_secrets accepts literal argv OR command + explicit shell (bash/sh), secretNames, optional absolute cwd, nonsecret env, timeoutMs, and idempotencyKey. exec_with_secrets_status(jobId) and exec_with_secrets_cancel(jobId) are scoped to the caller's verified workspace and agent session. See specs/001-mvp/contracts/api.md and public guide guides/secret-execution.md for the lifecycle and compatibility scope.
Private VM-agent node-management routes: POST /workspaces/:workspaceId/mcp/secret-exec; GET /workspaces/:workspaceId/mcp/secret-exec/:jobId?agentSessionId=...; POST /workspaces/:workspaceId/mcp/secret-exec/:jobId/cancel?agentSessionId=.... Direct browser/workspace auth is insufficient. Ordinary managed secret environment delivery uses named placeholders; selected values go only into the job's framed stdin environment, with bounded redacted results persisted in existing VM job storage.
Dynamic admin settings
GET /api/admin/settings— fresh revision and typed settings with effective/default/source metadata and value-free history; active approved superadmin only; secrets return configured state, never plaintext.PATCH /api/admin/settings—{expectedRevision,changes:[{name,value}]}; null resets to fallback. Atomic revision/audit+settings/encryptedcredential writes,409conflict and sanitized failure errors. Existing setup authorization remains separate.
Workload identity
GET /oidc/.well-known/openid-configurationandGET /oidc/.well-known/jwks.json— public provider-neutral workload issuer discovery and active public key. Separate from legacy GCP/internal JWT issuer.GET /api/projects/:projectId/sessions/:sessionId/agent-credential— Which account the chat's agent ran on:credentialSource,credentialScope(profile/project/user/platform), andaccountName(only for the session's own user); plusruntime— the session's frozen effectivemodel,effort,permissionMode,opencodeProviderandskillName(personal skills only to the runner), null for pre-contract sessions.GET /api/projects/:projectId/sessions/:sessionId/workload-identity— authenticated project-member read-only current workload metadata (issuer, subject, TTL, claims). Never mints a token. Unavailable runtime returns 409.exec_with_secretsaccepts optionaloidc: { audience: string }; privately injects reservedSAM_OIDC_TOKEN, including whensecretNamesis empty. Same-session job status/cancel semantics are unchanged.
Full notification questions
GET /api/projects/:projectId/sessions/:sessionId/attention/:markerId— full saved human-input request, options and resolution/delivery status; projecttask:readrequired.context=trueadds bounded preceding transcript excerpts (messages) and what the agent did since (since); optionallimitdefaults to admin-editablecollaboration.commentContextMessages(6) and uses the existing chat page maximum. Streamed rows are assembled into whole messages; scan/character-limited excerpts are labelled. No runtime contact. Answers still usePOST .../attention/:markerId/resolve.