agentleFS
littlebearappslittlebearapps/untether/.claude/skills/claude-stream-json/SKILL.md

claude-stream-json

Skill72 starsChanged 4 months agoMITView on GitHub

Claude Code CLI stream-json protocol as consumed by Untether. Covers JSONL event types, content blocks, control channel protocol, permission modes, auto-approve, the outline gate, and ExitPlanMode handling. This is the CONSUMER side — Untether spawns Claude Code as a subprocess.

  • Reads credentials
  • Deletes or force-pushes

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When using --permission-prompt-tool stdio, Claude Code sends control requests as JSONL on stdout and expects responses on stdin.

    line 129
  2. Very specific:

    When Claude requests ExitPlanMode:

    line 194
  3. Distinctive:

    After outline is written, post-outline buttons appear: Approve Plan / Deny / Let's discuss

    line 197
  4. Very specific:

    After "Pause & Outline Plan", mark_outline_pending(session_id) arms a purely TEXT-based gate: ExitPlanMode is auto-denied until …

    line 203

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Claude Code stream-json Protocol (Consumer)

Untether spawns Claude Code CLI as a subprocess and consumes its JSONL output. This skill covers the protocol from Untether's perspective.

Key files

FilePurpose
src/untether/runners/claude.pyClaudeRunner — subprocess management, PTY, control channel, event translation
src/untether/schemas/claude.pymsgspec structs for Claude JSONL events
src/untether/runners/tool_actions.pytool_kind_and_title() — tool name to ActionKind mapping
docs/reference/runners/claude/runner.mdFull runner specification
docs/reference/runners/claude/stream-json-cheatsheet.mdJSONL event shapes with examples
docs/reference/runners/claude/untether-events.mdClaude JSONL to Untether event mapping

CLI invocation

Non-interactive mode (-p)

claude -p --output-format stream-json --input-format stream-json --verbose -- <prompt>
  • -p / --print: non-interactive, prompt as positional arg after --
  • --verbose: required for full stream-json output
  • --input-format stream-json: enables JSON input on stdin
  • Prompt passed after -- to protect prompts starting with -

Interactive permission mode

claude --output-format stream-json --input-format stream-json --verbose \
  --permission-mode plan --permission-prompt-tool stdio
  • No -p flag — prompt sent via stdin as JSON user message
  • --permission-prompt-tool stdio: enables bidirectional control channel
  • --permission-mode plan|tool: determines what needs approval

Common flags

  • --resume <session_id>: resume a previous session
  • --model <name>: model override (sonnet, opus, haiku)
  • --allowedTools "<rules>": auto-approve specific tools

JSONL event types

One JSON object per line on stdout. Required field: type.

system (init)

{"type":"system","subtype":"init","session_id":"...","cwd":"/repo","model":"sonnet",
 "permissionMode":"auto","tools":["Bash","Read","Write"],"mcp_servers":[...]}
  • Emitted once at stream start
  • session_id: opaque string (do NOT assume UUID format)
  • Untether emits StartedEvent here

assistant / user messages

{"type":"assistant","session_id":"...","message":{"id":"msg_1","role":"assistant",
 "content":[...],"usage":{...}}}

Content blocks in message.content[]:

Block typeFieldsUntether mapping
texttextStored as fallback answer; no action emitted
tool_useid, name, inputActionEvent(phase="started")
tool_resulttool_use_id, content, is_errorActionEvent(phase="completed")
thinkingthinkingOptional note action or ignored

result

{"type":"result","subtype":"success","session_id":"...","is_error":false,
 "result":"Done.","total_cost_usd":0.01,"usage":{...},
 "duration_ms":12345,"duration_api_ms":12000,"num_turns":2}
  • is_error: authoritative error indicator
  • result: final answer string
  • Untether emits exactly one CompletedEvent here
  • Lines after result are dropped

Fields NOT in Untether's StreamResultMessage schema (silently ignored by msgspec):

  • error, permission_denials, modelUsage

Tool name to ActionKind mapping

Tool nameActionKindTitle source
Bashcommandinput.command
Edit, Write, MultiEdit, NotebookEditfile_changeinput.file_path or input.path
ReadtoolRead <path>
Glob, Greptoolpattern from input
WebSearchweb_searchinput.query
WebFetchweb_searchURL from input
TodoWrite, TodoReadnote"update todos"
AskUserQuestionnote"ask user"
Task, Agenttooltool name
KillShellcommandtool name
(other)tooltool name

Mapping implemented in src/untether/runners/tool_actions.py.

Control channel protocol

When using --permission-prompt-tool stdio, Claude Code sends control requests as JSONL on stdout and expects responses on stdin.

Control request (stdout)

{"type":"assistant","session_id":"...","message":{"content":[
  {"type":"tool_use","id":"toolu_ctrl_1","name":"PermissionPromptTool",
   "input":{"type":"control_request","request_id":"req_1",
            "tool_name":"Bash","tool_input":{"command":"rm -rf /"}}}
]}}

Control response (stdin)

{"type":"control_response","request_id":"req_1","approved":true}

Or with denial:

{"type":"control_response","request_id":"req_1","approved":false,
 "denial_message":"Not allowed — explain your plan first."}

ControlInitializeRequest

Sent at session start; auto-approved immediately (no user prompt):

{"type":"control_response","request_id":"req_init","approved":true}

PTY for stdin

ClaudeRunner uses pty.openpty() instead of subprocess.PIPE for stdin:

  • Prevents deadlock when keeping stdin open for control responses
  • Master FD held by the runner; slave FD passed to subprocess
  • tty.setraw(master_fd) for raw byte passthrough
  • Stdin refs captured locally at spawn time (not on self)

Session registries (concurrent sessions)

_SESSION_STDIN: dict[str, anyio.abc.ByteSendStream]   # session_id -> stdin pipe
_REQUEST_TO_SESSION: dict[str, str]                    # request_id -> session_id
  • Registered in _iter_jsonl_events when session_id is first seen
  • Control responses routed via _REQUEST_TO_SESSION lookup
  • Cleaned up when run completes

Auto-approve logic

Non-interactive tools are auto-approved without user prompt:

AUTO_APPROVE_TOOLS = {"Grep", "Glob", "Read", "LS", "Bash", "BashOutput",
                      "TodoWrite", "TodoRead", "WebSearch", "WebFetch", ...}
  • ControlInitializeRequest: always auto-approved
  • Tool requests where tool_name in AUTO_APPROVE_TOOLS: auto-approved silently
  • ExitPlanMode: always shown to user as inline buttons

ExitPlanMode handling

When Claude requests ExitPlanMode:

  1. Inline keyboard shown: Approve / Deny / Pause & Outline Plan
  2. "Pause & Outline Plan" sends a deny with a detailed message asking Claude to write a step-by-step plan
  3. After outline is written, post-outline buttons appear: Approve Plan / Deny / Let's discuss
  4. "Let's discuss" sends a deny asking Claude to discuss the plan (action: chat)
  5. Text-based outline gate: retries without written outline text are auto-denied

Outline gate (#570 retired the progressive cooldown)

  • After "Pause & Outline Plan", mark_outline_pending(session_id) arms a purely TEXT-based gate: ExitPlanMode is auto-denied until max_text_len_since_cooldown >= _OUTLINE_MIN_CHARS (200), then held open behind synthetic Approve/Deny buttons
  • The former time-based progressive cooldown (30/60/90/120s escalation) was a workaround for the v2.1.72–74 immediate-retry-after-denial loop — verified fixed on CLI 2.1.215 and removed (#570)

Early callback answering

Telegram buttons show a spinner until answerCallbackQuery. The Claude control callback handler sets answer_early = True to clear the spinner immediately with a toast ("Approved", "Denied", "Outlining plan...").

write_control_response helper

async def write_control_response(
    session_id: str,
    request_id: str,
    approved: bool,
    deny_message: str | None = None,
) -> None:

Looks up stdin in _SESSION_STDIN[session_id], writes JSON response, handles cleanup.

Config keys ([claude] section in untether.toml)

[claude]
model = "sonnet"
allowed_tools = ["Bash", "Read", "Edit", "Write"]
dangerously_skip_permissions = false
use_api_billing = false
permission_mode = "plan"  # set via /planmode command or ChatPrefsStore
  • use_api_billing = false (default): strips ANTHROPIC_API_KEY from subprocess env
  • permission_mode: overridable per-chat via /planmode command

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.