Terminal API
Local HTTP interfaces for terminals, agent sessions, dispatch queues, screen waits, layouts, and automation. The published 1.24 API keeps terminal persistence separate from app services.
Setup and security
Enable Settings > Remote Control > Terminal API and generate a token. The server binds to 127.0.0.1, using port 3037 in production and 3036 in development by default. TERMINAL_API_PORT can override this; confirm the actual origin with termdock hostinfo --json or Settings. The general API is disabled by default. Keep it on loopback; it is not a public remote-access server.
Authorization: Bearer $TERMINAL_API_TOKEN
Content-Type: application/jsonJSON success responses use { success: true, data: ... }; failures use { success: false, error: { code, message, reason?, details? } }. Branch on error.code. The general limit is 120 requests per 60 seconds per IP/method/path; exceeding it returns 429 RATE_LIMITED. Bootstrap challenge and webhook ingress are authentication exceptions described below.
Confirm the connection and target
The running app provides the API. A live broker does not keep HTTP, schedules, dispatch, or bot services available. List workspaces and sessions, then choose an explicit target instead of assuming the first workspace is correct. TOKEN, IDs, and /path/to/... values in examples are placeholders, not credentials.
Use the CLI if you do not need raw HTTPWorkspaces and sessions
GET /api/terminal/workspaces
Returns data.workspaces with id, name, and rootPath.
{ "success": true, "data": { "workspaces": [
{ "id": "ws_123", "name": "my-project", "rootPath": "/path/to/project" }
] } }POST /api/terminal/sessions
Required: workspaceId. Optional: name, cols (80–500, default 80), rows (24–100, default 24), logPolicy: "persist", background (default false), paneId, stealFocus. Returns data.session with id, applied name, workspaceId, status, isActive, and background. Creation starts at the workspace root.
For agent automation, set background: true to avoid taking a tab or pane. Foreground sessions can target paneId and use stealFocus: false; placement options cannot be combined with background: true (INVALID_PLACEMENT).
GET /api/terminal/sessions
Optional query workspaceId filters sessions and returns data.sessions; this filter is not a workspace-scoped authorization token. Broker-owned local terminals (1.23+) and peer terminals (1.24+) can survive app quit/crash/update. Explicit destruction, process exit, host sign-out, or shutdown ends them. App-owned fallback and SSH terminals have different lifetimes.
PATCH /api/terminal/sessions/:id
Body: { name }. Returns data.sessionId and data.name. Collisions add -2, -3, etc.; use the returned name. Names are limited to 200 characters.
Session path targets accept an id or unique tab name; URL-encode names. An id wins over a matching name. Unresolved or ambiguous names return SESSION_NOT_FOUND; resolution failure returns SESSION_RESOLVE_FAILED. Resolve to an id for automation that must remain stable across renames. SSE resolves once when subscribing.
GET /api/terminal/sessions/:id/status
Includes activity, readiness, hasPrompt, waitingForInput, and prompt.kind (shell, confirm, select, password, open). Check readiness === "idle" before the next command; activity alone is insufficient.
GET /api/terminal/sessions/:id/log
For sessions created with logPolicy: "persist". Returns sessionId, logPath, content under data. Persisted files can outlive the session.
GET /api/terminal/sessions/:id/ports
Returns data.sessionId and data.ports: [{ pid, port, protocol, address }].
DELETE /api/terminal/sessions/:id
Destroy the terminal session and release its resources. For a regular broker terminal, this ends the process and waits for acknowledgement; it is not the same as quitting the app.
Input
POST /api/terminal/sessions/:id/input
Required JSON string data, or a text/plain body. Options in JSON or query: appendEnter, submitKey, queueUntilReady, readyTimeoutMs, agentSessionId. submitKey overrides appendEnter and follows the /keys names. Text and the submit key are written separately.
{ "data": "npm test", "appendEnter": true, "queueUntilReady": true, "readyTimeoutMs": 30000 }queueUntilReady waits for readiness "idle". A readiness timeout returns TERMINAL_NOT_READY without writing. Invalid data returns 400 INVALID_INPUT_DATA; an invalid submitKey writes nothing. Input handling returns data.requestId on success or error.details.requestId on failure, except requests rejected before input handling.
POST /api/terminal/sessions/:id/submit
JSON { data, settleMs?, queueUntilReady?, readyTimeoutMs?, agentSessionId? }. Use when already at an interactive prompt, rather than after every shell command.
POST /api/terminal/sessions/:id/keys
JSON { key }. Supported keys: enter, up, down, left, right, tab, esc, ctrl+c, ctrl+d.
POST /api/terminal/sessions/:id/interrupt
Send Ctrl+C without destroying the session.
A session held by a remote peer rejects /input, /submit, /keys, and /interrupt with 409 SESSION_HELD_BY_PEER. Take it over on this host before writing. Do not retry unchanged refusals.
Output and SSE
GET /api/terminal/sessions/:id/output
Query: mode, lines, since, chromeProfile, ifHash, source, waitForChange, timeoutMs. text strips ANSI while preserving visible text; raw keeps ANSI; content filters TUI chrome on a best-effort basis; screen reads the current screen, not history.
Responses include data.sessionId, mode, lines, cursor, nextCursor, hasMore, truncated, windowStart, windowEnd, and lineCount. Reuse nextCursor as since for incremental reads. screen has no since support; it prefers headless state. App-owned terminals may use DOM fallback when a pane is visible, but broker terminals have no DOM source. source=headless or source=dom requests that source and can fail when unavailable. For content, chromeProfile accepts claude-code, default, or none.
Screen responses include outputHash and unchanged. Send ifHash on the next screen read; a matching hash returns unchanged: true with empty lines. waitForChange=true enables long polling; data.wait includes changed, timedOut, and optional reason: "LONGPOLL_TIMEOUT".
GET /api/terminal/sessions/:id/events
SSE frames contain TerminalSessionOutputEvent JSON: { type: "output.new", sessionId, timestamp, payload }. payload has the /output shape. Query: mode=raw|text|content, since, lines (clamped to 1–500), chromeProfile, timeoutMs (at least 1000 ms). screen returns 400 INVALID_TERMINAL_SSE_QUERY. Without since the stream starts at the current tail.
Terminal SSE does not replay a retained backlog. Recover missed history with /output?since=... before subscribing, then advance using payload.nextCursor. Slow readers can be disconnected.
Screen condition waits
POST /api/terminal/sessions/:id/wait
{ "condition": { "kind": "text", "value": "Ready" },
"timeoutMs": 30000, "workspaceId": "REPLACE_WORKSPACE_ID" }kind is text, gone, or regex; value is required. text matches text on the current screen; gone means that text is absent, not that the session exited. regex accepts i and m flags. timeoutMs defaults to 30000, has a 120000 maximum, and 0 checks once.
Returns data.sessionId, kind, matched, timedOut, and observation. This observes the current screen, not full history or semantic task success. Handle workspace/authority changes, ended targets, unavailable screens, and timeouts from the response instead of polling forever.
Dispatch queue
POST /api/terminal/dispatches?workspaceId=WORKSPACE_ID
GET /api/terminal/dispatches?workspaceId=WORKSPACE_ID&sessionId=SESSION_ID
GET /api/terminal/dispatches/:appInstanceId/:dispatchId?workspaceId=WORKSPACE_ID
PATCH /api/terminal/dispatches/:appInstanceId/:dispatchId?workspaceId=WORKSPACE_ID
POST /api/terminal/dispatches/:appInstanceId/:dispatchId/wait?workspaceId=WORKSPACE_ID
POST /api/terminal/dispatches/:appInstanceId/:dispatchId/cancel?workspaceId=WORKSPACE_IDProvide workspaceId on every call, or the x-termdock-workspace-id header. Enqueue body is { target, payload, requestKey, queueTimeoutMs }; target is a session ID or resolvable unique name, and queueTimeoutMs is 1–86400000. Returns data.accepted and data.dispatch, including handle, version, state, blockReason, and outcome.
{ "target": "REPLACE_SESSION_ID",
"payload": "Review README.md; report only.",
"requestKey": "REPLACE_UNIQUE_TASK_KEY",
"queueTimeoutMs": 60000 }PATCH takes { payload, expectedVersion } and edits queued work only; cancel also only cancels queued work before sending. wait takes { waitTimeoutMs } from 0–120000; inspect waitOutcome and state. Exhausting this wait budget does not cancel the dispatch.
Automatic safe sending currently supports local macOS Claude/Codex, including broker terminals. Other platforms/providers and peer/SSH can remain blocked as unsupported-signal until expiry, without an unsafe send fallback. accepted is not submitted; completed records an observed turn end, while outcome may be unknown. App shutdown cancels queued work and can mark non-final in-flight work unknown. Do not use an old handle to guess work in a new app instance.
Dispatch CLI examplesExact workspace reads and read-only integrations
Add x-termdock-workspace-id to GET status or GET output?mode=text to require an exact session ID in that workspace, without tab-name fallback. Guarded output requires text mode and does not accept waitForChange. A workspaceId filter on the normal session list is not an authorization boundary.
The separate termdock-readonly-mcp adapter offers only workspace listing, session listing, status, and output reads, with its own config, allowlist, and dedicated token. It is distinct from Code Graph MCP. Its read-only restrictions do not turn the underlying terminal service token into a read-only token.
MCP integration boundariesTool Runtime
GET /api/tools
POST /api/tools/:name?workspaceId=WORKSPACE_ID&sessionId=SESSION_IDGET lists tool name, category, isReadOnly, isConcurrencySafe, and isAvailable. POST supplies the tool’s input body; URL-encode the name. Each tool retains its schema, workspace, and invocation-origin restrictions. Discovery is not authorization and does not let HTTP callers perform desktop-only actions such as approving a tmux socket. Do not guess flags or treat an arbitrary shell command as a tool name.
Layout
GET /api/terminal/layout
Returns data.layout. Use ?full=true for contentType/contentId bindings, pane geometry, and activePanelId; the default slim format carries id and terminalId.
POST /api/terminal/layout
JSON { type, sessionIds? }, for example { "type": "horizontal-2", "sessionIds": ["build", "test"] }.
POST /api/terminal/layout/panes/:paneId/assign
JSON { sessionId }; null clears a pane. Returns data.paneId and resolved data.terminalId.
POST /api/terminal/layout/panes/:paneId/activate
Focus a pane.
POST /api/terminal/layout/panels/:panelId/activate
Activate a tab-layer panel, including one without a pane binding.
POST /api/terminal/layout/restore
Body is the data.layout snapshot from ?full=true. Unavailable content is reported in restored.skipped; unresolved targets appear in restored.unresolvedTargets when present. A slim snapshot leaves panes empty and reports SLIM_PANE.
curl -s -H "Authorization: Bearer $TERMINAL_API_TOKEN" \
"http://127.0.0.1:3037/api/terminal/layout?full=true" | jq .data.layout > layout.json
curl -s -X POST -H "Authorization: Bearer $TERMINAL_API_TOKEN" \
-H "Content-Type: application/json" -d @layout.json \
http://127.0.0.1:3037/api/terminal/layout/restoreKeep-alive and notifications
GET /api/terminal/sessions/:id/keepalive
List rules.
PUT /api/terminal/sessions/:id/keepalive
JSON { rule: { id, enabled, schedule, message, promptRef? } }. Creates or replaces rule.id. Schedule: interval/intervalMs, idle/thresholdMs, daily/time (HH:mm), once/atMs. Idle rules require a local session.
DELETE /api/terminal/sessions/:id/keepalive/:ruleId
Remove a rule. All three keep-alive operations return the resulting rule list, including nextFireAt (null when disabled).
{ "rule": { "id": "review", "enabled": true,
"schedule": { "kind": "interval", "intervalMs": 1800000 },
"message": "continue" } }At most 10 enabled rules per session. To read a live Prompt Library entry at each trigger, set message: "" and promptRef: { slug: "review", scope: "project" } (or scope: "global"). References and inline text are mutually exclusive; prompts must have no variables. Project references use the target’s local workspace. Invalid prompts skip the trigger. Rules are removed when the session is destroyed.
POST /api/terminal/notify
JSON { message, sessionId?, title? }. Requires Remote Control, push notifications, and a connected provider. Message: 1–4000 trimmed characters; title: 1–100, only for the first Discord thread creation. Limit: 6 messages per minute per session.
When sessionId is present and Discord supports session threads, the push targets Discord. Otherwise it uses connected remote providers. Without a session it goes to connected remotes. Success means at least one provider accepted delivery; an undelivered push returns a non-2xx response.
Agent sessions
This surface manages provider sessions and structured transcripts, separate from raw terminal sessions. Accepted provider values are claude, codex, gemini, agy, duo, and opencode. For POST /api/agent-sessions (create), gemini is normalized to agy before provider dispatch, and the created session reports agy. Resolve can still return gemini, and attach preserves the requested provider. Use the resolved provider when attaching an existing session; do not rewrite gemini to agy.
POST /api/agent-sessions
JSON { provider, cwd, prompt, env?, settingSources? }. Returns data.session; its identifier is sessionId. env is provider-filtered; interactive Claude does not apply per-request env. Set credentials in the shell environment before app launch. settingSources is stored but not forwarded to the CLI.
GET /api/agent-sessions
Optional query cwd. Returns data.sessions.
POST /api/agent-sessions/resolve
JSON { cwd, shellPid? }. Returns data.target for attaching to an existing provider session.
POST /api/agent-sessions/attach
JSON { provider, sessionId, cwd }. Returns data.session. Attach accepts a Termdock run sessionId or the provider conversation id (metadata.aiSessionId). Use the returned run sessionId for later operations.
GET /api/agent-sessions/:id
Returns data.status with session (including session.lifetime), dispatch, bufferedEventCount, lastEventSequence, hasRenderedView, renderedEntryCount, lastRenderedSequence, and canRestart.
POST /api/agent-sessions/:id/input
JSON { input, env? }. Returns data.sessionId after provider send. A dispatch timeout can leave delivery uncertain; reconcile before resending.
POST /api/agent-sessions/:id/interrupt
Soft-interrupt the current turn when the provider supports it; returns data.sessionId.
POST /api/agent-sessions/:id/restart
Restart using cached create input. Returns data.session; unavailable cached input yields AGENT_SESSION_RESTART_UNAVAILABLE.
DELETE /api/agent-sessions/:id
Stop the agent and return data.sessionId. Retained events can remain until session.lifetime.evictsAt.
GET /api/agent-sessions/:id/events
SSE lifecycle, assistant, tool, result, and error events. Query since is an exclusive sequence cursor. The newest 200 events are retained; detect gaps and resync from /rendered.
GET /api/agent-sessions/:id/rendered
Returns data.view, a rendered transcript snapshot, not a terminal screenshot.
GET /api/agent-sessions/:id/rendered/stream
SSE transcript snapshots and updates. Treat bounded snapshots as replacements, not append-only history.
POST /api/agent-sessions/hooks
Ingest provider hooks for Workstream. Prefer CLI hooks setup and hook ingest for provider-specific payloads and replies.
POST /api/agent-sessions/:id/callbacks
Required source, eventKind, message; optional dedupeKey and JSON-object metadata. Limits: source/eventKind 256 characters, dedupeKey 512, message 32768. Unknown fields are rejected. Returns data { sessionId, deliveryId, createdAt }.
Callbacks target an existing AgentSession id or its terminal id/unique name. They never create or attach an agent and do not answer permission prompts. Keys do not deduplicate automatically; metadata is caller-supplied, not authenticated identity. Success acknowledges provider send, not task completion.
Service tokens
UI tokens have full access. Service tokens scope access to terminal and/or agent-session; omitting scopes grants both. Bootstrap provisioning works while the general API is disabled, but terminal and agent endpoints still return 403 DISABLED.
POST /api/auth/bootstrap-challenge
No bearer token. JSON { nonce } (32–256 characters). Returns data.proof: hex HMAC-SHA256(bootstrapSecret, "<nonce>|<port>"). Verify locally with a constant-time comparison before sending the secret; a missing or mismatched proof must stop provisioning.
POST /api/auth/service-tokens
JSON { name, scopes? }. Authenticate using the UI token or X-Termdock-Bootstrap-Token from ~/.termdock/config/terminal-api-bootstrap.json. Returns data.serviceToken including the token once; store it securely.
POST /api/auth/service-tokens/:id/rotate
JSON { graceSeconds? }. A service token can rotate only itself; the UI token can administer tokens. Old token expiry is previousTokenExpiresAt.
DELETE /api/auth/service-tokens/:id
Revoke with the UI token or the service token itself.
Webhook ingress
POST /api/webhooks/:id/:secret
Create the URL in Settings > Automation > Webhooks for a local workspace and tab name. It requires no bearer token and works while the general API is disabled. JSON must contain exactly { message, submit }. message is one line of 1–4096 UTF-16 characters with no ASCII controls. submit is a boolean. Body limit: 8 KiB; 10 requests per 60 seconds per webhook.
The URL is shown once and is a secret. The target must be an agent waiting at its input composer. Busy, missing, ambiguous, non-agent, or unreadable-screen targets fail without writing or creating a session. submit: true also sends Enter. Success is { success: true, data: { delivered: true } }.
For external senders, configure a TLS-enabled tunnel or reverse proxy exposing only /api/webhooks/... and keep secrets out of access logs. Never expose the other Terminal API routes. Revoke URLs in Settings.
Automation setupExample: background terminal
This example uses a POSIX shell and curl. Configure TERMINAL_API_TOKEN privately and adjust BASE to the actual port. List workspaces first, choose a test workspace, then replace WORKSPACE_ID. Never paste a real token into documentation or bug reports.
BASE="http://127.0.0.1:3037"
AUTH="Authorization: Bearer $TERMINAL_API_TOKEN"
curl -sS -H "$AUTH" "$BASE/api/terminal/workspaces"
curl -sS -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"workspaceId":"WORKSPACE_ID","background":true,"name":"api-check"}' \
"$BASE/api/terminal/sessions"Check success is true, replace SESSION_ID with data.session.id, then send a read-only directory check. queueUntilReady waits if the shell is still initializing. Diagnose errors before resending.
curl -sS -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"data":"pwd","appendEnter":true,"queueUntilReady":true,"readyTimeoutMs":30000}' \
"$BASE/api/terminal/sessions/SESSION_ID/input"
curl -sS -H "$AUTH" \
"$BASE/api/terminal/sessions/SESSION_ID/output?mode=text&lines=20"After testing, call DELETE /api/terminal/sessions/SESSION_ID only when no needed process remains in that terminal. Reading output does not prove another long-running task has finished.
CLI command reference