The pure state machine of one MingaClaudeBridge.Session.
Each transition takes the state and one input, matches the phases where that input is valid, and returns {:ok, state, outcome} with a named outcome the session acts on. An input in any other phase returns {:error, {:invalid_phase, tag}} and leaves the state unchanged. Transitions perform no I/O: they return the lines to write, and the session writes them.
Phases
{:starting, queued}- the process is starting and the session waits for the answer to itsinitializecontrol request.queuedis a prompt request that arrived before that answer, ornil; it is written when startup completes. Claude Code sends the MCPinitializeandtools/listrequests in this phase, and they are answered.:idle- no request is running.{:streaming, turn}- a request is running, andturnaccumulates its reply.{:awaiting_tool_results, calls}- the previous request ended with tool calls.callsmaps eachtool_useid Minga must answer to its tool name.{:interrupting, reason}- the session sentinterruptand waits for Claude Code to end the turn.{:dead, reason}- the process is gone or must not be used. Every later request fails with{:session_dead, reason}.
Tool calls and results
Claude Code may send an MCP tools/call before or after the message_stop of the message that requested it, and it may dispatch the calls of one message one at a time, sending the next call only after the previous one is answered. The state therefore keeps two values next to the phase:
calls- heldtools/callcontrol requests (MingaClaudeBridge.ToolCalls), whatever the phase they arrived in.results- tool results Minga already delivered for calls Claude Code has not sent yet, keyed bytool_useid.
At message_stop, a message with tool_use blocks ends the request with those calls; the state does not wait for the MCP calls to arrive. A tool-results request must answer exactly the calls of the previous request. Each result answers its held call at once, or waits in results until Claude Code sends that call. A tools/call that arrives while no request is running or after an abort is answered with JSON-RPC error -32800 and never held.
Startup
Claude Code 2.1.330 answers initialize without waiting for a prompt, and it sends system/init only when a user message starts a query. Startup therefore completes on a successful initialize answer. That answer's account, models, and claude_code_version are kept and returned by info/1. When a minimum version is configured, a claude_code_version that is missing, unparsable, or lower kills the session with {:unsupported_version, version}.
Tool check (fail closed)
Every query must start with a system/init frame that passes the tool check before any model output is accepted. query is :unchecked from the moment a prompt is written until that frame arrives. Tool results continue the same query, so they keep it :checked.
system_init/2kills the session with{:unexpected_tools, names}whentoolscontains a name without themcp__minga__prefix ormcp_serversnames a server other thanminga.- A stream event,
assistantframe, ortools/callwhile the query is:uncheckedkills the session with:missing_system_init.
Claude Code is therefore stopped before the model's first output reaches Minga, so no tool can run.
Non-streaming fallback
When a stream stalls, Claude Code can ask again without streaming and deliver the reply only as assistant frames under a new message id. assistant/2 forwards those frames through MingaClaudeBridge.Session.Turn. Such a message has no message_stop, so the session calls end_fallback_message/1 before it handles any frame other than assistant; when the fallback message holds tool_use blocks, that call suspends the request exactly as message_stop does.
Summary
Types
What Claude Code reported in its initialize answer. account and models are the raw JSON values. account holds the account email: never log it.
Whether the running Claude Code query passed the tool check of its system/init frame.
Functions
Aborts the running request.
Applies an assistant frame while streaming. Frames of messages that were streamed are ignored by the turn; frames of a non-streaming fallback message yield their text and thinking as {:emit, events} (see MingaClaudeBridge.Session.Turn.apply_assistant/2). Subagent frames and frames while interrupting are :ignored. A frame before the query's system/init kills the session with :missing_system_init.
Accepts a client-initiated control request, such as get_usage or get_context_usage, while no request is running. Returns {:error, {:invalid_phase, tag}} in every other phase, so a control request never interleaves with a turn.
Applies a control_request from Claude Code. Returns {:reply, line} with the answer to write, or :held when a tools/call waits for its result. A tools/call while streaming a query that has not passed its system/init check kills the session with :missing_system_init.
Applies a control_response. A successful answer to the initialize request completes startup after the version check; an error answer kills the session with {:initialize_failed, message}. Other answers (for example to interrupt) are ignored.
Ends a non-streaming fallback message, which has no message_stop. The session calls it before every frame other than assistant. While streaming, a fallback message with tool_use blocks suspends the request ({:suspend, tool_calls, usage}); otherwise the outcome is :unchanged.
The session stayed idle for the idle timeout. Ends it with :idle_timeout.
Returns what Claude Code reported at startup, or nil before startup completed.
Claude Code did not end the turn in time after interrupt. Kills the session with :interrupt_timeout.
Returns a starting state.
Returns the tag of the current phase.
Accepts a request.
Applies the result frame that ends a Claude Code turn.
Startup did not finish in time. Kills the session with :startup_timeout.
Applies a stream event while streaming.
Applies the system/init frame that starts a query. Valid while streaming. A frame that passes the tool check marks the query :checked; any other kills the session with {:unexpected_tools, names}.
The transport exited or failed, or a line could not be decoded. Kills the session with reason from any live phase.
Types
@type finish() :: {:finish, MingaClaudeBridge.Session.Event.usage() | nil, MingaClaudeBridge.Session.Event.finish_reason()}
What Claude Code reported in its initialize answer. account and models are the raw JSON values. account holds the account email: never log it.
@type invalid_phase() :: {:invalid_phase, phase_tag()}
@type phase() :: {:starting, MingaClaudeBridge.Session.Request.t() | nil} | :idle | {:streaming, MingaClaudeBridge.Session.Turn.t()} | {:awaiting_tool_results, %{required(String.t()) => String.t()}} | {:interrupting, term()} | {:dead, term()}
@type phase_tag() ::
:starting
| :idle
| :streaming
| :awaiting_tool_results
| :interrupting
| :dead
@type query() :: :unchecked | :checked
Whether the running Claude Code query passed the tool check of its system/init frame.
@type request_error() :: invalid_phase() | {:session_dead, term()} | {:invalid_tool_results, invalid_tool_results()}
@type startup_outcome() :: :ready | {:ready, {:prompt, MingaClaudeBridge.Session.Request.t()}} | {:dead, term()}
@type suspend() :: {:suspend, [MingaClaudeBridge.Session.Event.tool_call()], MingaClaudeBridge.Session.Event.usage() | nil}
@type t() :: %MingaClaudeBridge.Session.State{ calls: MingaClaudeBridge.ToolCalls.t(), info: info() | nil, initialize_id: String.t(), min_version: Version.t() | nil, phase: phase(), query: query(), results: %{required(String.t()) => MingaClaudeBridge.ToolCalls.result()}, tools: [MingaClaudeBridge.MCP.tool()] }
Functions
@spec abort(t(), term()) :: {:ok, t(), {:interrupt, [MingaClaudeBridge.Wire.line()]} | :dequeued} | {:error, invalid_phase()}
Aborts the running request.
While streaming or awaiting tool results, moves to {:interrupting, reason} and returns {:interrupt, cancel_lines}: every held call is answered with JSON-RPC error -32800, and results waiting for their call are dropped. While starting with a queued prompt, drops the prompt (:dequeued).
@spec assistant(t(), MingaClaudeBridge.Wire.Assistant.t()) :: {:ok, t(), {:emit, [MingaClaudeBridge.Session.Event.t()]} | :ignored | {:dead, term()}} | {:error, invalid_phase()}
Applies an assistant frame while streaming. Frames of messages that were streamed are ignored by the turn; frames of a non-streaming fallback message yield their text and thinking as {:emit, events} (see MingaClaudeBridge.Session.Turn.apply_assistant/2). Subagent frames and frames while interrupting are :ignored. A frame before the query's system/init kills the session with :missing_system_init.
@spec control(t()) :: :ok | {:error, invalid_phase()}
Accepts a client-initiated control request, such as get_usage or get_context_usage, while no request is running. Returns {:error, {:invalid_phase, tag}} in every other phase, so a control request never interleaves with a turn.
@spec control_request(t(), MingaClaudeBridge.Wire.ControlRequest.t()) :: {:ok, t(), {:reply, MingaClaudeBridge.Wire.line()} | :held | {:dead, term()}} | {:error, invalid_phase()}
Applies a control_request from Claude Code. Returns {:reply, line} with the answer to write, or :held when a tools/call waits for its result. A tools/call while streaming a query that has not passed its system/init check kills the session with :missing_system_init.
Only mcp_message requests for the minga server are served. Every other request (can_use_tool, another MCP server, an unknown subtype) is answered with a control error: the bridge never grants Claude Code permissions.
@spec control_response(t(), MingaClaudeBridge.Wire.ControlResponse.t()) :: {:ok, t(), startup_outcome() | :ignored} | {:error, invalid_phase()}
Applies a control_response. A successful answer to the initialize request completes startup after the version check; an error answer kills the session with {:initialize_failed, message}. Other answers (for example to interrupt) are ignored.
@spec end_fallback_message(t()) :: {:ok, t(), suspend() | :unchanged} | {:error, invalid_phase()}
Ends a non-streaming fallback message, which has no message_stop. The session calls it before every frame other than assistant. While streaming, a fallback message with tool_use blocks suspends the request ({:suspend, tool_calls, usage}); otherwise the outcome is :unchanged.
@spec idle_timeout(t()) :: {:ok, t(), {:dead, :idle_timeout}} | {:error, invalid_phase()}
The session stayed idle for the idle timeout. Ends it with :idle_timeout.
Returns what Claude Code reported at startup, or nil before startup completed.
@spec interrupt_timeout(t()) :: {:ok, t(), {:dead, :interrupt_timeout}} | {:error, invalid_phase()}
Claude Code did not end the turn in time after interrupt. Kills the session with :interrupt_timeout.
Returns a starting state.
Options:
:initialize_id(required) - the request id of theinitializecontrol request the session sends.:tools- the tools fortools/listuntil the first request. Defaults to[].:min_version- the lowest supportedclaude_code_version, as a string.nil(the default) skips the check.
Returns the tag of the current phase.
@spec request(t(), MingaClaudeBridge.Session.Request.t()) :: {:ok, t(), :queued | {:prompt, MingaClaudeBridge.Session.Request.t()} | {:tool_results, [MingaClaudeBridge.Wire.line()]}} | {:error, request_error()}
Accepts a request.
- A prompt while idle starts streaming; the outcome
{:prompt, request}tells the session to write it. A prompt while starting is queued (:queued) when no other request is queued. - Tool results while awaiting them answer the held calls; the outcome
{:tool_results, lines}holds the reply lines to write. The results must name every awaited call exactly once, or the request is rejected with{:invalid_tool_results, detail}and the state does not change.
@spec result(t(), MingaClaudeBridge.Wire.Result.t()) :: {:ok, t(), finish() | :interrupted | :abandoned} | {:error, invalid_phase()}
Applies the result frame that ends a Claude Code turn.
- While streaming: returns to
:idlewith{:finish, usage, reason}. - While interrupting: returns to
:idlewith:interrupted. - While awaiting tool results: Claude Code ended the turn without the results. Returns to
:idlewith:abandoned; the awaited calls are dropped.
@spec startup_timeout(t()) :: {:ok, t(), {:dead, :startup_timeout}} | {:error, invalid_phase()}
Startup did not finish in time. Kills the session with :startup_timeout.
@spec stream_event(t(), MingaClaudeBridge.Wire.StreamEvent.t()) :: {:ok, t(), {:emit, [MingaClaudeBridge.Session.Event.t()]} | suspend() | :ignored | {:dead, term()}} | {:error, invalid_phase()}
Applies a stream event while streaming.
Returns {:emit, events} with the text and thinking events to forward, or, at the message_stop of a message with tool_use blocks, {:suspend, tool_calls, usage} and the :awaiting_tool_results phase. Subagent events (a non-nil parent_tool_use_id) and events while interrupting are :ignored. Any event before the query's system/init kills the session with :missing_system_init.
@spec system_init(t(), MingaClaudeBridge.Wire.SystemInit.t()) :: {:ok, t(), :checked | {:dead, term()}} | {:error, invalid_phase()}
Applies the system/init frame that starts a query. Valid while streaming. A frame that passes the tool check marks the query :checked; any other kills the session with {:unexpected_tools, names}.
@spec transport_down(t(), term()) :: {:ok, t(), {:dead, term()}} | {:error, invalid_phase()}
The transport exited or failed, or a line could not be decoded. Kills the session with reason from any live phase.