MingaClaudeBridge.Session (minga_claude_bridge v0.1.0)

Copy Markdown View Source

One Claude Code process serving one Minga conversation.

The session owns a MingaClaudeBridge.Transport and a pure MingaClaudeBridge.Session.State. It decodes each line from the transport, applies it to the state, and performs the effects the state asks for: writing lines, sending events to the subscriber, and starting or stopping timers.

Lifecycle

start_link/1 starts the transport, writes the initialize control request, and waits for its answer (see MingaClaudeBridge.Session.State). A prompt that arrives during startup is written once startup completes. If the answer does not arrive within :startup_timeout, is an error, or reports an unsupported version, the transport is stopped before any prompt is written. info/1 returns the account and models from the answer.

Each query's system/init frame must pass the tool check before any model output is accepted. On failure the session stops the transport, dies, and finishes the request with {:error, {:unexpected_tools, names}} before it forwards any event of that query.

Every failure leaves the session in {:dead, reason}: the transport is stopped, the running request (if any) finishes with {:error, reason}, and every later request/3 returns {:error, {:session_dead, reason}}. The session process stays alive so callers can read that reason; the owner of the session replaces it. In :idle only, the session stops normally after :idle_timeout.

The session is restart: :temporary and traps exits; terminate/2 stops the transport.

Requests and events

request/3 starts a request and returns its ref. The subscriber then receives {ref, event} messages (see MingaClaudeBridge.Session.Event), ending with exactly one {ref, {:finish, reason}}. A tool-results request whose ids do not match the awaited calls is accepted, and its subscriber receives only {:finish, {:error, {:invalid_tool_results, detail}}}; nothing is written for it.

The session monitors the subscriber of the running request. If the subscriber exits before the finish, the session aborts the request.

Abort

abort/2 writes interrupt, answers every held tool call with JSON-RPC error -32800, and sends the subscriber {:finish, {:error, :aborted}} at once. Events already sent stay valid. Claude Code then has :interrupt_timeout milliseconds to end the turn with a result frame, after which the session is idle again. Otherwise the session stops the transport and dies with :interrupt_timeout.

Rate limits

Each rate_limit_event is forwarded to the :on_rate_limit target without waiting: a pid receives {:claude_bridge_rate_limit, session_pid, %MingaClaudeBridge.Wire.RateLimit{}}, and a one-argument function runs in a separate unlinked task.

Logging

The session logs frame types and lifecycle changes only, never payloads.

Summary

Types

The subscriber of the request that has not finished yet.

Where rate-limit events go.

t()

Functions

Aborts the request ref: the running request, or the last one when it ended with tool calls. Returns {:error, :unknown_request} for any other ref and {:error, {:invalid_phase, tag}} when nothing can be aborted.

Waits until startup completes. Returns {:ok, info} (see info/1) once Claude Code answered initialize, or {:error, reason} when the session died first. Exits when timeout passes, like GenServer.call/3.

Returns a specification to start this module under a supervisor.

Sends a client-initiated control request to Claude Code and returns the response object of its answer.

Returns what Claude Code reported in its initialize answer: %{account, models, claude_code_version}, or nil before startup completed. account holds the account email; never log it.

Returns the launch settings the process was started with (:model, :effort, :resume, :persist_session).

Returns the current phase tag, for diagnostics.

Records what this Claude Code process has seen after a completed request. The caller builds history with MingaClaudeBridge.History.record/2.

Starts a request. subscriber receives the request's events as {ref, event} messages, where ref is request.ref.

Returns the history digests this Claude Code process has seen (see MingaClaudeBridge.History). A new session has seen nothing.

Starts a session without linking it to the caller. A failed start returns {:error, reason} instead of exiting the caller. Pass :owner so the session stops when the caller exits.

Starts a session.

Types

active()

@type active() :: %{ref: reference(), subscriber: pid(), monitor: reference()}

The subscriber of the request that has not finished yet.

rate_limit_target()

@type rate_limit_target() ::
  pid() | (MingaClaudeBridge.Wire.RateLimit.t() -> term()) | nil

Where rate-limit events go.

t()

@type t() :: %MingaClaudeBridge.Session{
  active: active() | nil,
  controls: %{required(String.t()) => {GenServer.from(), reference()}},
  handle: MingaClaudeBridge.Transport.handle() | nil,
  idle_timeout: timeout_ms(),
  interrupt_timeout: non_neg_integer(),
  last_ref: reference() | nil,
  launch: keyword(),
  next_id: pos_integer(),
  on_rate_limit: rate_limit_target(),
  owner_monitor: reference() | nil,
  ready_waiters: [GenServer.from()],
  seen: MingaClaudeBridge.History.t(),
  state: MingaClaudeBridge.Session.State.t(),
  timer: {atom(), reference()} | nil,
  transport: module(),
  transport_ref: reference()
}

timeout_ms()

@type timeout_ms() :: non_neg_integer() | :infinity

Functions

abort(session, ref)

@spec abort(GenServer.server(), reference()) ::
  :ok
  | {:error, :unknown_request | MingaClaudeBridge.Session.State.invalid_phase()}

Aborts the request ref: the running request, or the last one when it ended with tool calls. Returns {:error, :unknown_request} for any other ref and {:error, {:invalid_phase, tag}} when nothing can be aborted.

await_ready(session, timeout \\ 30000)

@spec await_ready(GenServer.server(), timeout()) ::
  {:ok, MingaClaudeBridge.Session.State.info()} | {:error, term()}

Waits until startup completes. Returns {:ok, info} (see info/1) once Claude Code answered initialize, or {:error, reason} when the session died first. Exits when timeout passes, like GenServer.call/3.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

control(session, request, timeout)

@spec control(GenServer.server(), map(), non_neg_integer()) ::
  {:ok, map()} | {:error, term()}

Sends a client-initiated control request to Claude Code and returns the response object of its answer.

request is the request object with a string "subtype", for example %{"subtype" => "get_usage", "skip_behaviors" => true}. Only an idle session accepts it. Returns {:error, {:invalid_phase, tag}} otherwise, {:error, {:control_error, message}} when Claude Code answers with an error, {:error, :timeout} after timeout milliseconds, {:error, :session_down} when the session process is gone, and {:error, reason} when the session dies first.

info(session)

Returns what Claude Code reported in its initialize answer: %{account, models, claude_code_version}, or nil before startup completed. account holds the account email; never log it.

launch(session)

@spec launch(GenServer.server()) :: keyword()

Returns the launch settings the process was started with (:model, :effort, :resume, :persist_session).

phase(session)

Returns the current phase tag, for diagnostics.

remember(session, history)

@spec remember(GenServer.server(), MingaClaudeBridge.History.t()) :: :ok

Records what this Claude Code process has seen after a completed request. The caller builds history with MingaClaudeBridge.History.record/2.

request(session, request, subscriber)

Starts a request. subscriber receives the request's events as {ref, event} messages, where ref is request.ref.

Returns {:error, {:session_dead, reason}} on a dead session and {:error, {:invalid_phase, tag}} when the session cannot take this kind of request now, for example while another request runs.

seen(session)

Returns the history digests this Claude Code process has seen (see MingaClaudeBridge.History). A new session has seen nothing.

start(opts)

@spec start(keyword()) :: GenServer.on_start()

Starts a session without linking it to the caller. A failed start returns {:error, reason} instead of exiting the caller. Pass :owner so the session stops when the caller exits.

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()

Starts a session.

Options:

  • :transport (required) - {module, opts} where module implements MingaClaudeBridge.Transport.
  • :system_prompt - sent with initialize.
  • :model, :effort, :resume, :persist_session - passed to the transport as :launch settings (see MingaClaudeBridge.Launch). :resume is a Claude Code session id or nil.
  • :tools - the tool declarations for tools/list until the first request.
  • :min_version - the lowest supported claude_code_version, or nil to skip the check.
  • :on_rate_limit - a pid or a one-argument function. See the module documentation.
  • :idle_timeout - milliseconds in :idle before the session stops, or :infinity. Defaults to 15 minutes.
  • :interrupt_timeout - milliseconds Claude Code has to end a turn after interrupt. Defaults to 1000.
  • :startup_timeout - milliseconds to finish startup. Defaults to 30000.
  • :owner - a pid. When it exits, the session stops normally, which stops Claude Code. Use it with start/1 for a session that must not outlive the process that uses it.
  • :name - a GenServer name.