Api reference

From raphaeltm/simple-agent-manager · View interactive version

Api reference is an AI agent skill from the GitHub repository raphaeltm/simple-agent-manager. Full API endpoint reference for SAM. Use when working on API routes, adding endpoints, writing API tests, or understanding the API surface.

How to use this skill

Skill file

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

Workspace Management

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

Default Capacity Pools

Chat Sessions (Project Scoped)

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)

Search Input Limits

Member event subscriptions

MCP Orchestration

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)

Agent Sessions

VM Agent direct execution protocol (node-management JWT)

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

Notifications

Automation Triggers (Project Scoped)

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)

VM Communication (Callback Endpoints)

VM Agent snapshot relay (busy legacy node compatibility)

Terminal Access

Git Integration (VM Agent direct — browser calls via ws-{id} subdomain)

File Browser (VM Agent direct — browser calls via ws-{id} subdomain)

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

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

Client Error Reporting

Authentication (BetterAuth)

Credentials

GCP

The service-account flow ignores uploaded endpoint fields and exchanges RS256 assertions only at SAM's fixed Google token endpoint.

GitHub Integration

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).

SAM Connector

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

Workload identity

Full notification questions

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.