MingaClaudeBridge.Session.State (minga_claude_bridge v0.1.0)

Copy Markdown View Source

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 its initialize control request. queued is a prompt request that arrived before that answer, or nil; it is written when startup completes. Claude Code sends the MCP initialize and tools/list requests in this phase, and they are answered.
  • :idle - no request is running.
  • {:streaming, turn} - a request is running, and turn accumulates its reply.
  • {:awaiting_tool_results, calls} - the previous request ended with tool calls. calls maps each tool_use id Minga must answer to its tool name.
  • {:interrupting, reason} - the session sent interrupt and 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 - held tools/call control requests (MingaClaudeBridge.ToolCalls), whatever the phase they arrived in.
  • results - tool results Minga already delivered for calls Claude Code has not sent yet, keyed by tool_use id.

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/2 kills the session with {:unexpected_tools, names} when tools contains a name without the mcp__minga__ prefix or mcp_servers names a server other than minga.
  • A stream event, assistant frame, or tools/call while the query is :unchecked kills 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.

t()

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

finish()

info()

@type info() :: %{
  account: map() | nil,
  models: [map()],
  claude_code_version: String.t() | nil
}

What Claude Code reported in its initialize answer. account and models are the raw JSON values. account holds the account email: never log it.

invalid_phase()

@type invalid_phase() :: {:invalid_phase, phase_tag()}

invalid_tool_results()

@type invalid_tool_results() ::
  {:duplicate_tool_use, [String.t()]}
  | {:unknown_tool_use, [String.t()]}
  | {:missing_tool_results, [String.t()]}

phase()

@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()}

phase_tag()

@type phase_tag() ::
  :starting
  | :idle
  | :streaming
  | :awaiting_tool_results
  | :interrupting
  | :dead

query()

@type query() :: :unchecked | :checked

Whether the running Claude Code query passed the tool check of its system/init frame.

request_error()

@type request_error() ::
  invalid_phase()
  | {:session_dead, term()}
  | {:invalid_tool_results, invalid_tool_results()}

startup_outcome()

@type startup_outcome() ::
  :ready
  | {:ready, {:prompt, MingaClaudeBridge.Session.Request.t()}}
  | {:dead, term()}

suspend()

t()

@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

abort(state, reason)

@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).

assistant(state, frame)

@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.

control(state)

@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.

control_request(state, control_request)

@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.

control_response(state, control_response)

@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.

end_fallback_message(state)

@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.

idle_timeout(state)

@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.

info(state)

@spec info(t()) :: info() | nil

Returns what Claude Code reported at startup, or nil before startup completed.

interrupt_timeout(state)

@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.

new(opts)

@spec new(keyword()) :: t()

Returns a starting state.

Options:

  • :initialize_id (required) - the request id of the initialize control request the session sends.
  • :tools - the tools for tools/list until the first request. Defaults to [].
  • :min_version - the lowest supported claude_code_version, as a string. nil (the default) skips the check.

phase_tag(state)

@spec phase_tag(t()) :: phase_tag()

Returns the tag of the current phase.

request(state, request)

@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.

result(state, result)

@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 :idle with {:finish, usage, reason}.
  • While interrupting: returns to :idle with :interrupted.
  • While awaiting tool results: Claude Code ended the turn without the results. Returns to :idle with :abandoned; the awaited calls are dropped.

startup_timeout(state)

@spec startup_timeout(t()) ::
  {:ok, t(), {:dead, :startup_timeout}} | {:error, invalid_phase()}

Startup did not finish in time. Kills the session with :startup_timeout.

stream_event(state, stream_event)

@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.

system_init(state, 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}.

transport_down(state, reason)

@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.