Claude Code to Untether event mapping (spec)
This document describes how the Claude Code runner translates Claude Code CLI JSONL events into Untether events.
This document describes how the Claude Code runner translates Claude Code CLI JSONL events into Untether events.
Authoritative source: The schema definitions are in
src/untether/schemas/claude.pyand the translation logic is insrc/untether/runners/claude.py. When in doubt, refer to the code.
The goal is to make a Claude Code runner feel identical to the Codex runner from the bridge/renderer point of view while preserving Untether invariants (stable action ids, per-session serialisation, single completed event).
1. Input stream contract (Claude Code CLI)
The Claude Code CLI emits one JSON object per line (JSONL) when invoked with
--output-format stream-json.
Non-interactive invocation:
claude -p --output-format stream-json --input-format stream-json --verbose -- <query>
Permission mode invocation (bidirectional control channel):
claude --output-format stream-json --input-format stream-json --verbose --permission-mode plan --permission-prompt-tool stdio
Notes:
--verboseis required forstream-jsonoutput (CLI may otherwise drop events).--input-format stream-jsonenables JSON input on stdin.- In
-pmode, the prompt is passed as a positional argument after--. - In permission mode, the prompt is sent via stdin as a JSON user message (no
-p). - Resuming uses
--resume <session_id>. -- <query>safely passes prompts that start with-.
2. Resume tokens and resume lines
- Engine id:
claude - Canonical resume line (embedded in chat):
`claude --resume <session_id>`
Runner must implement its own regex because the resume format is
claude --resume <session_id>. Suggested regex:
(?im)^\s*`?claude\s+(?:--resume|-r)\s+(?P<token>[^`\s]+)`?\s*$
Note: Claude Code session IDs should be treated as opaque strings.
Resume rules:
- If a resume token is provided to
run()(other than a/continuetoken, which names no session), the runner MUST verify that anysession_idobserved in the stream matches it. - If the stream yields a different
session_id, emit a fatal error and end the run.
3. Session lifecycle + serialisation
Untether requires serialisation per session id:
- For new runs (
resume=None), do not acquire a lock until asession_idis observed (usually the firstsystem.initevent). - Once the session id is known, acquire a lock for
claude:<session_id>and hold it until the run completes. - For resumed runs, acquire the lock immediately on entry.
- A
/continuetoken carries no session id, so it is handled like a new run: the lock is taken on the id named by its firststartedevent (#817).
This matches the Codex runner behaviour in untether/runners/codex.py.
4. Event translation (Claude Code JSONL -> Untether)
4.1 Top-level system events
Claude Code emits a system init event early in the stream:
{"type":"system","subtype":"init","session_id":"...", ...}
Mapping:
- Emit a Untether
startedevent as soon assession_idis known. - Populate
metafromsystem.initfields:cwd,model,tools,permissionMode,output_style,apiKeySource,mcp_servers(whichever are present), pluseffortwhen a reasoning override is set. ThemodelandpermissionModefields are used by the bridge to render the🏷footer line on final messages. - The first
system.initper run produces thestartedevent. A latersystem.initnever re-emitsstarted; in a live session (#776) one that arrives while no turn is open opens a follow-up turn (see 4.5). A manual/compactalso re-emitsinitmid-command. - #751: on the first
initonly, apermissionModethat differs from the requested mode adds a warningnoteafterstarted(⚠️ Asked for <mode> mode — Claude Code is running <mode>) and, when the effective mode is a prompting one, re-arms the stage-6 approval gate. - Background-task subtypes (
task_started,task_progress,task_updated,task_notification,background_tasks_changed) emit no Untether events; they maintain the native task map (ClaudeStreamState.tasks). Atask_updatedpatch withis_backgrounded: true(the CLI moved a running foreground task to the background) marks the task backgrounded, as does a snapshot listing a known parent-owned foreground task, or its notification reaching an idle parent (claude.task.backgrounded, #876). system/api_retry(#792) emits onenoteaction per retry sequence, updated in place (🔁 API error 529 (overloaded) — retrying in 8s (attempt 2/10); levelwarningon the final attempt) and latches an expected wait so the stall monitor stays quiet during the back-off.- Hook lifecycle subtypes (
hook_started,hook_progress,hook_response; only with--include-hook-events, #812) emit no Untether events. They pair byhook_idintoClaudeStreamState.pending_hooks, which drives the live-session async-hook hold, and an idlehook_response{outcome:"error", exit_code:2}from a hook that started in an earlier turn arms thehook_rewakeattribution for the next turn (4.5); any other exit 2 (a background subagent’s sync denial, aUserPromptSubmitblocker) logsclaude.hook.blocking_exitinstead (#828). An exit 2 from a hook that started and ended while idle after running ≥ 1 s (a background subagent’sasyncRewakehook) logsblocking_exit rewake_candidate=Trueand arms a weak, open-only hint: a turn opening ≤ 3 s later ishook_rewake(#923). The base runner does not let them overwritelast_event_type. system/informational(#814): the safeguard notice (”…‘s safeguards stopped the response above · continuing once …”) feeds the per-turn safeguard tally (outcomeretried, see 4.2). Any other banner at levelwarning/noticeemits onenoteaction (⚠️/ℹ️+ the first line ofcontent; one row pertool_use_id);info/suggestionare logged only (claude.informational).system/model_refusal_fallback/model_refusal_no_fallback(#814) feed the safeguard tally with outcomeswitched/not_retried;model_refusal_fallbackalso updates the session model unlessscope == "local".system/model_fallback(not a safeguard stop) emits anoteaction↪️ Switched model <a> → <b> (<trigger>)and logsclaude.model_fallback.system/statuswith a stringpermissionMode(#383) emits no Untether event; it updatesClaudeStreamState.effective_permission_mode(as does everysystem.init.permissionModeand the ack of Untether’s ownset_permission_mode, request idut_plan_rearm_…). Seeingplanclears the session’s_PLAN_EXIT_APPROVED; a plan chat seeing any other mode recordsplan_exited_at/plan_exit_turn.TurnEvent(started).detail["plan_deferred"] = {"agents": N}(#383 C4): the turn runs unplanned because the plan re-arm is deferred while background agents launched in the plan-exit turn still work — set on a follow-up / idle steer written during the deferral and, inplanchats, on a wake turn opened during it. The bridge adds⚠️ Not re-planned: the approved plan's background agents are still running. Plan mode resumes when they finish.under the turn header (the whole header for a follow-up).- Optional: emit a
noteaction summarising tools/MCP servers (debug-only).
A top-level control_request (control-channel mode) is answered on stdin.
Housekeeping subtypes and the tool requests the mode doesn’t route to the
user (#749) are approved silently and emit nothing; a request that needs the
user emits a started warning action (claude.control.<n>) whose
detail.inline_keyboard carries the Telegram buttons (Approve / Deny, plan
buttons for ExitPlanMode, option buttons for AskUserQuestion) and
detail.request_id. See the runner spec, “Permissions” and “Permission
modes”. A control_response from the CLI emits nothing; the ack of
Untether’s own set_permission_mode updates the effective mode (see the system/status bullet above).
The top-level control_cancel_request line (#684) — the CLI withdrawing a
pending permission request — writes no reply and retires the request: one
action.completed (kind warning, ⏹️ Permission request withdrawn — Claude Code no longer needs an answer) for the request’s action, which drops its
keyboard; nothing for an unknown or already-answered id. The base runner keeps
it out of last_event_type (control traffic) and treats it as resolving an
approval wait in the ring-buffer fallback.
The top-level rate_limit_event line (#790) is a quota snapshot, not a
throttle notice: allowed emits nothing; allowed_warning emits at most one
note per window (⚠️ 5h limit N% used — resets HH:MM, rendered without a ✓ prefix, #868); only rejected not
covered by overage emits a ⏳ Rate limited until … note and latches the wait
until resetsAt. Bare events emit nothing. Every snapshot is stashed on ClaudeStreamState.rate_limit_windows; with
the usage footer off, the final’s ≥70 % 5h warning is built from it, with no login-token read
(#1150). Decision table:
stream-json cheatsheet.
4.2 assistant / user message events
Claude Code messages include a message object with a content[] array. Each content
block can represent text, tool usage, or tool results.
For each content block:
A) type = "tool_use"
Mapping: emit action with phase="started".
action.id=content.idaction.kind= map from tool name (see section 5)title:- if kind=
command: useinput.commandif present - else: tool name or derived label
- if kind=
detailincludesname(tool name),input(tool input),parent_tool_use_id(if provided) and, forfile_change,changes.server_tool_useblocks (#489) are translated the same way.
B) type = "tool_result"
Mapping: emit action with phase="completed".
action.id=content.tool_use_idok:- if
content.is_errorexists and is true ->ok=False - else
ok=True
- if
detailis the started action’s detail plustool_use_id,result_preview(the normalised content),result_lenandis_error.advisor_tool_resultblocks (#489) are translated the same way.
The runner SHOULD keep a small in-memory map from tool_use_id -> tool_name
(learned from tool_use) so the completed action title can match the started
action title.
C) type = "text"
Mapping:
- Default: do not emit an action (avoid duplicate rendering).
- Store the latest assistant text as a fallback final answer if
result.resultis empty or missing.
D) type = "thinking" or other block types
Mapping: a non-empty thinking block emits a completed note action
(claude.thinking.<n>, title = the thinking text, detail.signature when
present). image / document blocks (#597) and other types emit nothing.
E) Safeguard stops (message.stop_reason == "refusal", #814)
A main-thread assistant frame (no parent_tool_use_id) whose
message.stop_reason is "refusal" counts one safeguard stop, deduped on
message.id. With the informational notice and the refusal-fallback
subtypes (4.1) it feeds one per-turn tally, so a paired stop counts once.
Mapping: one note action per turn, id claude.safeguard.<turn>,
updated in place: 🛡️ <model> safeguards stopped a response · <outcome> (×N), ok=True (level warning only when not retried). If no CLI reaction
arrives by the turn’s result, the outcome is retried when more output
followed the refusal, else not_retried. The result then carries
usage["safeguard"] = {stops, outcome, outcome_label, category, model, fallback_model?}, and claude.safeguard_stop is logged once per resolved
stop. A stop never sets ok=False.
4.3 result events
The terminal event looks like:
{"type":"result","subtype":"success", ...}
Mapping: emit a single Untether completed event:
ok = !event.is_erroranswer = event.result(fallback to last assistant text if empty); on success an approvedExitPlanModeplan body is prepended as📋 Plan (approved)when the answer is brief (#508/#793)error(only whenis_error): built by_extract_errorfrom the result text (or subtype), a diagnostic line and the #438 stream-idle classification; a resumed run’s line shows its own cost (the session’s earlier total from the cost ledger, else the resume guard’s absorbed baseline) plussession cost:, and a figure with no baseline is labelledsession cost:/session api:(#889)resume = ResumeToken(engine="claude", value=event.session_id)usage: see section 6- Emit exactly one
completedevent per run. With live sessions off (or in legacy-pmode) trailing lines are ignored; with live sessions on (#776) reading continues and later results close follow-up turns (4.5). total_cost_usdis cumulative per session, across--resumetoo; the bridge derives per-run/per-turn deltas (#778).terminal_reason(#806):aborted_streaming/aborted_toolsmean the turn was interrupted. The runner setsusage["terminal_reason"], and the bridge renders that turn ascancelled(never onsubtype/is_error).origin.kind == "task-notification"marks a turn the CLI started itself; it confirms ahook_rewaketurn at its result (4.5).- No-query results (#928): in a live session, a successful result with
num_turns == 0,duration_api_ms == 0, an emptyresult, nostructured_outputorlocal_command, no abortedterminal_reasonandorigin.kind == "task-notification"is the CLI’s no-query result. With no turn open (and no pendingcommand_lifecycle) it is absorbed: no events, INFOclaude.turn.no_query opened=False. If aninitalready opened anunknown(orhook_rewake) turn with no model request or text, that turn closes asTurnEvent(completed, reason="no_query")— the bridge drops it silently — and a hook hint it spent is restored. Every liveclaude.turn.completedline logsorigin_kind. usage["safeguard"]is added when the turn had a safeguard stop (4.2 E).usage["background"](#821) names the background agents active since the previous result (agents,agents_live,agents_ended,task_ids,since_s) — their spend is in this result’s cost delta; absent when none.- Resume guard: on a resumed run, a 0-turn result (
num_turns == 0,duration_api_ms == 0) that follows a replayedtask_notification{stopped}before any assistant output is absorbed — nocompleted; the next result is the answer.
Supplementary started event after result (✓ turn complete)
Every successful result (i.e. is_error=false) MAY also emit a supplementary started event carrying late-arriving meta — meta={"complete": "✓ turn complete"} (#333). This is the supported pattern for late-arriving meta documented in runner-development.md: ProgressTracker.note_event merges meta idempotently so the marker shows up in the footer (format_meta_line) alongside model / effort / permission / trigger without duplicating the StartedEvent. Errored results do not emit the marker — no false “complete” tag on a failure.
The runner emits this supplementary event only for the result that closes the run. Later turns of a live session (#776) end in a TurnEvent(phase="completed") instead, so the bridge adds the marker itself: handle_message’s _deliver_final adds meta["complete"] (the shared untether.model.TURN_COMPLETE_MARKER) to the final’s snapshot for every ok=True turn, whatever started it (follow-up, queued follow-up, background-task wake, Monitor tick, scheduled wake-up). The turn’s tracker is left alone, so the turn’s in-flight progress message never shows the marker; failed and interrupted turns don’t get it (#798).
Permission denials
Not yet implemented. The upstream Claude Code CLI may include
result.permission_denialswith blocked tool calls, but Untether’sStreamResultMessageschema does not capture this field and the runner does not emit warning actions for denials. This is a candidate for future work.
4.5 Follow-up turns in a live session (#776)
After the run’s completed, each later turn in the same process is emitted as
TurnEvent(phase="started", turn=N, reason=…) → ActionEvent* → TurnEvent(phase="completed", turn=N, ok, answer, usage)
built with EventFactory.turn_started / turn_completed. The turn opens on the
first post-result system.init, system/status{"status":"compacting"} (a
/compact follow-up, #819), assistant message, or non-tool-result user
message; reason comes from what preceded it: an injected line’s
command_lifecycle.command_uuid (followup), a task_notification
(task_finished), a fresh (≤ 10 s) idle hook_response with exit code 2
from a background hook that outlived its turn (hook_rewake, #812/#828;
detail.hook / hook_event), or a hook that started while idle, ran ≥ 1 s
and exited 2 just before the turn opened (≤ 3 s, open-time only; hook_rewake
with detail.hook_started_idle, #923),
a command_lifecycle(started) with an unknown uuid (scheduled_wakeup), or a
live Monitor task (monitor_event). A turn that opened unknown becomes
hook_rewake at its result when an earlier turn’s hook exited 2 during it
(or a stale idle hint ≤ 60 s old was carried in) and the result’s origin.kind
is task-notification
(detail.retro_attributed). The bridge always pushes a hook_rewake final
(🪝 Hook feedback — <event>) and never folds it. A turn closed by the CLI’s
no-query result completes with reason="no_query" (#928): never rendered,
delivered, accounted, folded or exported. Assistant/user
events tagged parent_tool_use_id (a background subagent) never open a turn.
command_lifecycle lines emit nothing themselves, with one exception (#775):
a started for a line Untether injected (a steer or a follow-up) while a
turn is still open means the CLI folded it into that turn, and emits a
↪️ steer received: … (or ↪️ follow-up received) note
(detail.absorbed_command_uuid).
Attribution (#785): a task_notification only labels the next turn when the
task is top-level background work (is_backgrounded and not
owned_by_subagent); others are logged claude.turn.notification_ignored.
A turn that opened unknown (the CLI often starts it on a background agent’s
result before any task event) completes as task_finished if a top-level task
ends during it (detail.retro_attributed), or is paired with a task ending
within 30 s after it. The task’s own notification turn that follows carries
detail.already_announced and the bridge delivers it without a push. A
top-level task that ends while a task_finished turn is open is appended to
that turn’s detail.tasks / task_ids at completion and listed in
detail.late_tasks (#825); the bridge re-heads the final with every name.
TurnEvent(completed) carries the turn’s detail; a task’s own
notification turn also carries detail.announced_turns, the wake turn(s) its
end was paired with, so the bridge files an unattributed ack under the right
task (#813).
A turn ended by an interrupt (result terminal_reason aborted, or the bridge
closing the run with reason cancel mid-turn) is rendered cancelled, not as
an error; its cost delta is still accounted first (#806).
4.4 Error handling / malformed lines
- If a JSONL line is invalid JSON, or valid JSON that doesn’t match the schema:
emit nothing and continue. The base runner logs invalid JSON
(
jsonl.parse.invalid); a schema mismatch logs WARNjsonl.msgspec.invalid. - If the subprocess exits non-zero or the stream ends without a
resultevent: emitcompletedwithok=Falseanderrorexplaining the failure. - Emit exactly one
completedevent per run.
5. Tool name -> ActionKind mapping heuristics
Claude Code tool names can evolve. The runner SHOULD map based on tool name and input shape. Suggested rules:
The implemented mapping is tool_kind_and_title in runners/tool_actions.py
(paths from input.file_path, else input.path):
| Tool name pattern | ActionKind | Title logic |
|---|---|---|
Bash, Shell, KillShell | command | input.command |
Write, Edit, MultiEdit, NotebookEdit | file_change | the path |
Read | tool | read: `<path>` |
Glob / Grep | tool | glob: `<pattern>` / grep: <pattern> |
WebSearch / WebFetch | web_search | input.query / input.url |
TodoWrite / TodoRead | note | update todos / read todos |
AskUserQuestion | note | ask user |
Task, Agent | subagent | input.description, else input.prompt |
| (default) | tool | tool name |
For file_change, emit detail.changes = [{"path": <path>, "kind": "update"}]
(always update; creation is not distinguished).
If a tool name is unknown, map to tool and include the full input in detail.
6. Usage mapping
Untether completed.usage (and a live turn’s TurnEvent(completed).usage) is
a dict built from the result: total_cost_usd, duration_ms,
duration_api_ms, num_turns, subtype (when present) and the raw
result.usage object under usage. Extra keys are added when they apply:
safeguard (4.2 E), terminal_reason (4.3), context and compaction
(6.1). modelUsage is not copied; it is read only to learn each model’s
context window.
6.1 Context-window use (#819)
| Claude frame | Untether event |
|---|---|
main-thread assistant with int message.usage input fields | ActionEvent(kind="telemetry", id="claude.context", phase="updated", detail={context_pct, context_used, context_window, model}) — only when the integer % changes and the model’s window is known |
result.modelUsage.<model>.contextWindow | learned into the window cache (seeded for current models, persisted to context_windows.json); a first-known value is emitted as the same telemetry event before the supplementary StartedEvent{complete} / CompletedEvent; usage["context"] = {pct, used, window, model} (log field) |
system/status {"status":"compacting"} | ActionEvent(kind="note", id="claude.compaction.<n>", phase="started", title="🗜️ Compacting context…"); a repeat (the 30 s heartbeat) is phase="updated" on the same id. Live session with no turn open (a /compact follow-up): a TurnEvent(started) first |
system/status {"status":null,"compact_result":"success"} | phase="completed", 🗜️ Context compacted, ok=True |
system/status {"status":null,"compact_result":"failed"} | phase="completed", 🗜️ Compaction failed · <compact_error>, ok=False, level="warning" |
system/status {"status":null} with a row open / none open | 🗜️ Compaction skipped / nothing (#383’s permissionMode frame) |
system/compact_boundary | the same row re-completed as 🗜️ Context compacted · <pre> → <post> tokens (<trigger>) (one step), then telemetry with context_pct: None (segment hidden until the next response) |
result after a compaction | usage["compaction"] = {count, trigger, pre_tokens, post_tokens, result, manual_success} on the CompletedEvent / live TurnEvent(completed) |
live TurnEvent(started) | followed by the current value (the turn’s tracker starts empty) |
Subagent (parent_tool_use_id) and <synthetic> frames never change the value.
ProgressTracker keeps telemetry out of its actions (no step, no running tool, never
exported). Full rules: runner spec → “Context usage” and “Compaction”.
7. Implementation checklist (v0.3.0)
Claude Code runner implementation summary (no Untether domain model changes):
- Create
untether/runners/claude.pyimplementingRunnerand (custom) resume parsing. - Define
BACKENDinuntether/runners/claude.py:install_cmd: install command for theclaudebinarybuild_runner: read[claude]config + construct runner
- Add new docs (this file +
stream-json-cheatsheet.md). - Add fixtures in
tests/fixtures/(see below). - Add unit tests mirroring
tests/test_codex_*but for Claude Code translation and resume parsing (recommended, not required for initial handoff).
8. Suggested Untether config keys
A minimal TOML config for Claude Code:
untether config
untether config set claude.model "sonnet"
untether config set claude.allowed_tools '["Bash", "Read", "Edit", "Write", "WebSearch"]'
untether config set claude.dangerously_skip_permissions false
untether config set claude.use_api_billing false
toml
[claude]
# model: opus | sonnet | haiku
model = "sonnet"
allowed_tools = ["Bash", "Read", "Edit", "Write", "WebSearch"]
dangerously_skip_permissions = false
use_api_billing = false
Untether only maps these keys to Claude Code CLI flags; other options should be configured in Claude Code settings.
If allowed_tools is omitted, Untether defaults to ["Bash", "Read", "Edit", "Write"].
When use_api_billing is false (default), Untether strips ANTHROPIC_API_KEY from the Claude Code subprocess environment to prefer subscription billing.