commandcode-gateway
v0.1.1
Published
Local HTTP + SSE gateway for Command Code, shaped like opencode's server
Maintainers
Readme
Command Code Gateway
A local HTTP + SSE gateway for Command Code, shaped like opencode's server. It lets an iOS app, a web client, or any HTTP client create Command Code sessions, stream reasoning/text/tool output, approve permissions, switch models, and abort turns.
┌──────────────────┐ HTTP JSON + SSE ┌────────────────────────┐ JSON-RPC over stdio ┌──────────────────┐
│ iOS / web app │ ──────────────────► │ Command Code Gateway │ ──────────────────────► │ cmd acp │
│ │ ◄────────────────── │ (Node + TypeScript) │ ◄────────────────────── │ (ACP agent) │
└──────────────────┘ └────────────────────────┘ └──────────────────┘
│ tools, models,
│ taste, skills
▼
your machineThe gateway does not reimplement Command Code. It runs cmd acp as a persistent engine and translates ACP (Agent Client Protocol) into a small REST + Server-Sent Events API. Sessions, auth, tools, taste, and model access stay inside the Command Code CLI you already use.
Why this shape
- One long-lived engine —
cmd acpmultiplexes sessions, so the gateway does not spawn a process per prompt. - Real streaming — reasoning chunks, text deltas, tool calls, usage, and permission requests arrive as SSE events.
- Resumable — session metadata and transcripts are persisted locally; after a gateway restart, sessions reattach with
session/resume(falling back tosession/load). - Existing history included — on connect the gateway calls ACP
session/listand imports prior Command Code CLI/desktop sessions, parsing their JSONL transcripts so old threads appear with tools, reasoning, and usage. - opencode-shaped —
GET /event,GET|POST /session,GET /session/:id/message,GET /permission, andPOST /permission/:id/replyaliases exist alongside the primary/v1API. The schemas are gateway-native, not wire-compatible with the opencode SDK. - App-friendly — bearer token auth, pairing QR, image input, one in-flight prompt per session, and explicit
session_busyerrors.
Requirements
- Node.js 20+
- Command Code CLI, logged in once:
npm i -g command-code cmd login # Windows: cmdc login - macOS, Linux, or Windows. On Windows the default engine command is
cmdc acp; on macOS/Linux it iscmd acp. Tools run on the gateway host, not on the phone.
Quick start
cd commandcode-gateway
npm install
# If your npm config omits dev dependencies (npm config get omit):
# npm install --include=dev
npm run build
npm run check # verifies the CLI, login, and ACP engine
# Bind to the LAN so an iPhone/iPad can connect
node dist/cli.js serve --host 0.0.0.0The gateway prints:
Command Code Gateway 0.1.0
Engine cmd acp
Local http://127.0.0.1:4096
Network http://192.168.1.20:4096
Auth bearer token required
Token <random token>
Docs http://127.0.0.1:4096/doc
Pair URI commandcode-gateway://pair?url=...&token=...&name=...Scan the QR code with the app (it contains {"v":1,"url":"http://…","token":"…","name":"…"}) or enter the URL and token manually. The token is generated once and stored in ~/.commandcode-gateway/token with mode 0600; it stays stable across restarts. Pass --token or CC_GATEWAY_TOKEN to pin your own.
By default the gateway binds to 127.0.0.1. Use --host 0.0.0.0 for the LAN. Do not expose the port directly to the internet; use Tailscale, a VPN, or an SSH tunnel.
API
All endpoints except /, /health, /openapi.json, and /doc require Authorization: Bearer <token>. x-api-key: <token> and ?token= are also accepted (the query form is for SSE clients that cannot set headers). The OpenAPI document is served at /openapi.json and rendered at /doc.
| Method | Path | Purpose |
| --- | --- | --- |
| GET | /health | Gateway + engine status |
| GET | /v1/info | Capabilities and defaults |
| GET | /v1/models | Model catalog |
| GET | /v1/modes | Permission modes |
| GET | /v1/sessions | List gateway + imported Command Code sessions (?refresh=1 forces a history sync) |
| POST | /v1/sessions | Create a session (cwd, title, model, mode, autoApprove) |
| GET | /v1/sessions/:id | Session details |
| PATCH | /v1/sessions/:id | Rename, switch model/mode, toggle auto-approve |
| DELETE | /v1/sessions/:id | Close the session and delete its transcript |
| GET | /v1/sessions/:id/messages | Persisted transcript |
| POST | /v1/sessions/:id/prompt | Send a prompt (async by default; wait: true for sync) |
| POST | /v1/sessions/:id/abort | Cancel the in-flight turn |
| POST | /v1/sessions/:id/mode | Switch permission mode |
| POST | /v1/sessions/:id/model | Switch model |
| GET | /v1/events | SSE stream (all sessions, or ?sessionId=) |
| GET | /v1/sessions/:id/events | SSE stream for one session |
| GET | /v1/permissions | Pending permission requests |
| POST | /v1/permissions/:id/reply | {optionId} or {reply:"once"\|"always"\|"reject"} |
| GET | /pair | Pairing payload (url, token, host, port) |
opencode-style aliases: /event, /session, /session/:id, /session/:id/message, /session/:id/abort, /permission, /permission/:id/reply, /models, /global/health.
Create and prompt
TOKEN=...
BASE=http://127.0.0.1:4096
SESSION=$(curl -s -X POST "$BASE/v1/sessions" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"cwd":"/Users/me/code","title":"Refactor auth"}')
ID=$(echo "$SESSION" | jq -r .id)
curl -s -X POST "$BASE/v1/sessions/$ID/prompt" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"prompt":"Find the auth middleware and explain it","wait":true}'wait: true holds the request until the turn finishes and returns the full assistant message. Without wait, the response is 202 with {sessionId, messageId, userMessageId, status:"started"} and the turn streams over SSE.
Prompts accept a string, an array of content blocks, or opencode-style parts:
{
"prompt": [
{ "type": "text", "text": "What is in this screenshot?" },
{ "type": "image", "mimeType": "image/jpeg", "data": "<base64>" }
],
"model": "claude-sonnet-5-5",
"mode": "default"
}A file block with a data: URL is converted to an image block; other URLs become resource_link blocks.
Stream events
curl -N "$BASE/v1/events?token=$TOKEN&sessionId=$ID"retry: 3000
event: gateway.ready
data: {"type":"gateway.ready","version":"0.1.0","lastSeq":42,"sessions":[...]}
id: 43
event: message.part.delta
data: {"type":"message.part.delta","seq":43,"sessionId":"...","properties":{"messageId":"...","partId":"...","partType":"text","delta":"Hello"}}Event types:
| Event | Meaning |
| --- | --- |
| gateway.ready | Sent once per connection; includes sessions and lastSeq |
| session.created / session.updated / session.deleted | Session lifecycle |
| session.status | idle, busy, error, disconnected |
| message.created | A user or assistant message was added |
| message.part.delta | partType is text or reasoning; append delta |
| message.part.updated | Snapshot of a part, especially tool state |
| message.completed | Full final assistant message (authoritative) |
| usage.updated | Context usage / cost from the engine |
| permission.asked | A tool needs approval; reply via /v1/permissions/:id/reply |
| permission.replied | The request was answered or cancelled |
| session.idle | The turn finished; includes stopReason, usage, totalUsage |
| session.error | The turn failed |
| plan.updated | Agent plan entries |
| engine.exited | The ACP engine process exited; the next prompt restarts it |
Reconnect with the standard Last-Event-ID header or ?since=<seq> to replay missed events from the in-memory ring buffer (last 2,000 events).
Approve a tool
# See pending requests
curl -s "$BASE/v1/permissions?sessionId=$ID" -H "Authorization: Bearer $TOKEN"
# Approve once, always, or reject
curl -s -X POST "$BASE/v1/permissions/9001/reply" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"reply":"once"}'If no client answers, the turn stays blocked. Set "autoApprove": true on a session or start the gateway with --auto-approve for trusted automation.
Existing Command Code sessions
The gateway does not make you recreate old threads. On first use (and on a 5-second cache refresh) it:
- Calls ACP
session/listto get every session's id, workspace, title, and update time. - Reads the matching transcript from
~/.commandcode/projects/<project>/<session-id>.jsonl. - Merges assistant continuations and tool results into normal gateway messages, preserving reasoning, tool inputs/outputs, images (metadata), usage, and cache tokens.
- Exposes those records through the same
/v1/sessionsand/v1/sessions/:id/messagesendpoints.
Imported sessions are not copied into ~/.commandcode-gateway; they are reconstructed on every gateway start. Prompting one attaches through ACP session/resume and appends to the real Command Code transcript. Deleting an imported session hides it via a tombstone in ~/.commandcode-gateway/imported-sessions.json and leaves the original CLI transcript untouched.
Point the gateway at a different transcript root with --history-dir or CC_GATEWAY_HISTORY_DIR.
curl -s "$BASE/v1/sessions?refresh=1" -H "Authorization: Bearer $TOKEN"Because this imports the full CLI history, old /private/tmp and test sessions appear too. Delete them from the app to hide them.
Abort, model, and mode
curl -X POST "$BASE/v1/sessions/$ID/abort" -H "Authorization: Bearer $TOKEN"
curl -X POST "$BASE/v1/sessions/$ID/model" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"model":"claude-sonnet-5-5"}'
curl -X POST "$BASE/v1/sessions/$ID/mode" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"mode":"plan"}'Modes are default, auto-accept, plan, dont-ask, and bypass (the same modes cmd exposes in ACP).
iOS integration
examples/CommandCodeGateway.swift is a small async/await client covering session creation, prompts, permissions, and an SSE AsyncThrowingStream.
ATS blocks cleartext HTTP by default. For local development add this to Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSLocalNetworkUsageDescription</key>
<string>Connect to the Command Code gateway on your local network.</string>Then:
let gateway = CommandCodeGateway(
baseURL: URL(string: "http://192.168.1.20:4096")!,
token: "<token from the QR/pairing payload>"
)
let session = try await gateway.createSession(cwd: "/Users/me/code", title: "iOS session")
let stream = gateway.events(sessionId: session.id)
Task {
for try await event in stream {
if event.type == "message.part.delta" {
let delta = event.properties["delta"] as? String ?? ""
await MainActor.run { transcript += delta }
}
if event.type == "permission.asked",
let permissionId = event.properties["permissionId"] as? String {
try? await gateway.replyPermission(permissionId: permissionId, reply: "once")
}
if event.type == "session.idle" { break }
}
}
_ = try await gateway.prompt(sessionId: session.id, text: "Summarize this project")For remote use, put the gateway behind Tailscale or an SSH tunnel and keep the bearer token enabled. There is no built-in TLS.
CLI reference
commandcode-gateway [serve] [options]
commandcode-gateway check [options]| Flag | Default | Description |
| --- | --- | --- |
| --host | 127.0.0.1 | Bind address; 0.0.0.0 for the LAN |
| --port | 4096 | Port |
| --cwd | current directory | Default workspace for new sessions |
| --data-dir | ~/.commandcode-gateway | State, transcripts, token |
| --history-dir | ~/.commandcode/projects | Existing Command Code transcripts to import |
| --token | generated | Bearer token |
| --no-auth | off | Disable auth (loopback only unless --insecure) |
| --acp-command | cmd acp / cmdc acp on Windows | Engine command |
| --auto-approve | off | Auto-approve every permission request |
| --model | engine default | Default model for new sessions |
| --mode | engine default | Default mode for new sessions |
| --cors | * | Comma-separated allowed origins |
| --log-level | info | debug, info, warn, error |
| --qr / --no-qr | on in a TTY | Print the pairing QR |
| --insecure | off | Allow --no-auth on a non-loopback address |
Environment variables mirror the flags: CC_GATEWAY_HOST, CC_GATEWAY_PORT, CC_GATEWAY_CWD, CC_GATEWAY_DATA_DIR, CC_GATEWAY_HISTORY_DIR, CC_GATEWAY_TOKEN, CC_GATEWAY_ACP_COMMAND, CC_GATEWAY_MODEL, CC_GATEWAY_MODE, CC_GATEWAY_AUTO_APPROVE, CC_GATEWAY_CORS, CC_GATEWAY_LOG_LEVEL, CC_GATEWAY_QR, CC_GATEWAY_INSECURE.
How it works
The gateway is an ACP client:
- Spawns
cmd acpand sendsinitialize. - Calls
session/newwith the requestedcwd, orsession/resume(session/loadfallback) for persisted sessions. - Sends
session/promptwith ACP content blocks and streamssession/updatenotifications. - Translates ACP updates into gateway events:
agent_thought_chunk→reasoningpart deltasagent_message_chunk→textpart deltastool_call/tool_call_update→toolpartsusage_update→ context usageavailable_commands_update,current_mode_update,config_option_update→ session state
- Answers
session/request_permissionfrom the app (or auto-approves). - Calls
session/cancelfor aborts andsession/set_mode/session/set_config_optionfor model and mode changes.
Sessions are keyed by the ACP session id. One prompt may be in flight per session; other sessions can run concurrently on the same ACP process.
Persistence
~/.commandcode-gateway/
├── token
├── imported-sessions.json # tombstones + title overrides for imported history
└── sessions/
└── <session-id>/
├── meta.json # title, cwd, model, mode, usage (0600)
└── transcript.jsonl # completed user/assistant messages (0600)Transcripts contain prompts, tool inputs, and outputs. Treat that directory as sensitive. The gateway strips base64 image bytes from persisted user messages and stores only metadata.
After a restart, sessions load from meta.json; the first prompt reattaches with session/resume. If a CLI version does not support resume, the gateway uses session/load and suppresses the replayed history for a short grace period. If the engine no longer knows the session, the API returns 410 session_gone — create a new session.
Development
npm run typecheck
npm test
npm run build
npm run dev # tsx src/cli.ts serve
npm run openapi # regenerate openapi.jsonTests use a deterministic fake ACP agent (test/fake-acp.mjs), so they do not call Command Code, the network, or your account. The suite covers the JSON-RPC client, process crashes, streaming, permission approval, SSE, abort, persistence, restart/reattach, and importing/transcript parsing (35 tests).
Limitations
- This is an agent session gateway, not an OpenAI
/v1/chat/completionsmodel proxy. The app drives a real Command Code session with tools, permissions, and local context. For raw model access, use Command Code's provider API. - The API is opencode-shaped, not a drop-in replacement for the opencode SDK. Message/part ids and event names are gateway-native.
cmd acpis the supported engine. A different ACP agent may work if it implements the same methods, but only Command Code is tested./v1/modelsis populated fromsession/newand fromcmd --list-modelsfor the default command. With a custom ACP command it may be empty until the first session is created.- No TLS. Use a reverse proxy or private network for anything beyond localhost.
- The gateway holds pending permission requests in memory. If it restarts mid-permission, the turn is lost; the session transcript keeps the partial state.
- Imported history is read-only until prompted; it comes from the CLI transcript format, which is internal and may change. Imported sessions are recreated at startup and are not stored in the gateway state directory.
- Imported sessions include older test/temp workspaces. Delete them in the app to add tombstones, or point
--history-dirat a filtered copy. - Body limit is 30 MB, which bounds image payloads.
Publishing and deployment
See docs/deployment.md for npm publishing, self-hosted Docker, and the extra isolation required for a hosted multi-user service. Read SECURITY.md before exposing a gateway beyond localhost.
The short version: publish it as a CLI so each person runs it against their own Command Code account. A single gateway is single-user and can execute shell commands; do not share one instance across users.
License
MIT.
