pub struct SessionRegistry { /* private fields */ }Expand description
The daemon-owned session registry (Axiom 4).
Why: single source of truth for every session’s state, in-memory only
(§12, M1) — see the module docs for the full rationale.
What: see method docs below; new() uses DEFAULT_RING_CAPACITY,
with_capacity lets tests use a tiny buffer to exercise eviction cheaply.
Test: registry_tests::*.
Implementations§
Source§impl SessionRegistry
impl SessionRegistry
Sourcepub fn with_capacity(ring_capacity: usize) -> Self
pub fn with_capacity(ring_capacity: usize) -> Self
Construct an empty registry with an explicit ring-buffer capacity.
Why: unit tests need a small capacity to exercise eviction without pushing 1000 events.
Sourcepub fn create(
&self,
task: String,
agent: Option<String>,
project: Option<String>,
) -> Session
pub fn create( &self, task: String, agent: Option<String>, project: Option<String>, ) -> Session
session.create: register a brand-new session and publish its
lifecycle-start events.
Why: the sole entry point that mints a session id and puts a
Session into the registry.
What: builds a Session with a fresh UUIDv4 id and
status = Created, inserts it (with a fresh seq = 0 counter),
publishes Event::SessionStarted (assigned seq = 1), then
immediately transitions to Running (M1 has no queue ahead of real
task execution — see session::model docs) which publishes
Event::SessionStatusChanged (seq = 2). Returns the
post-transition snapshot (so the caller sees status: "running",
not the momentary "created").
Test: registry_tests::create_publishes_started_and_status_events.
Sourcepub fn list(&self) -> Vec<Session>
pub fn list(&self) -> Vec<Session>
session.list: snapshot every session currently in the registry.
Why: the read side of the registry for operators/CLI/TUI to enumerate
running sessions.
What: clones every Session snapshot; order is unspecified (backed
by a HashMap).
Test: registry_tests::list_returns_every_created_session.
Sourcepub fn status(&self, id: &str) -> Result<Session, RpcError>
pub fn status(&self, id: &str) -> Result<Session, RpcError>
session.status: snapshot one session by id.
Why: shared by create’s return value and the standalone
session.status method.
What: Ok(Session) if present, Err(RpcError::session_not_found)
otherwise.
Test: registry_tests::status_returns_not_found_for_unknown_id.
Sourcepub fn send(&self, id: &str, input: &str) -> Result<(), RpcError>
pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError>
session.send: deliver input to a session and publish an observable
event proving the daemon received it.
Why: #2054/#2055 do not wire a real agent loop (that is task.*,
#2056); publishing Event::SessionInput is what makes session.send
observably reach a session.attached client NOW, and gives #2056 a
concrete event to build real echo/ack behaviour on top of.
What: errors with session_not_found if id is unknown; otherwise
records+publishes Event::SessionInput { session_id, input }.
Test: registry_tests::send_publishes_input_event,
registry_tests::send_unknown_session_errors.
Sourcepub fn cancel(&self, id: &str) -> Result<Session, RpcError>
pub fn cancel(&self, id: &str) -> Result<Session, RpcError>
session.cancel: send a cancellation signal and mark the session
terminal.
Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
a status transition + event, not a deletion. #2054/#2055 have no
in-flight agent loop to interrupt yet (that lands with #2056), so
this is the full implementation available today: it marks the
session Cancelled and publishes the terminal events; #2056 hooks
the actual agent-loop interrupt onto the same status transition.
What: idempotent — cancelling an already-terminal session is a no-op
that returns the current snapshot rather than erroring (repeated
session.cancel calls are safe). Errors with session_not_found if
id is unknown. On a live session: publishes
Event::SessionStatusChanged (status: "cancelled"), then the
dedicated Event::SessionCancelled signal, then the generic terminal
Event::SessionDone (status: "cancelled") — matching the vision
spec’s started/status-changed/input/cancelled/done taxonomy — and
returns the updated snapshot.
Test: registry_tests::cancel_transitions_to_cancelled_and_publishes,
registry_tests::cancel_is_idempotent_on_terminal_session,
registry_tests::cancel_unknown_session_errors.
Sourcepub fn finish(
&self,
id: &str,
status: SessionStatus,
) -> Result<Session, RpcError>
pub fn finish( &self, id: &str, status: SessionStatus, ) -> Result<Session, RpcError>
Mark a session terminal (finished, failed, or cancelled while
executing) and publish the terminal Event::SessionDone (#2056).
Why: the background executor (crate::task::executor) needs to set
the FINAL status once an agent loop returns, distinctly from the
user-initiated session.cancel JSON-RPC path (Self::cancel),
which ALSO emits a dedicated Event::SessionCancelled signal that
only makes sense for an explicit user cancel request — not a natural
finish or failure, and not a cancellation the EXECUTOR itself
observed (that path already went through request_cancel, which
does not transition status; the executor calls this afterward to
actually land the transition once it has unwound).
What: idempotent — a no-op (returns the current snapshot) if the
session is already terminal, since a race between request_cancel’s
caller and the executor noticing cancellation is possible but
harmless. Errors with session_not_found if id is unknown.
Otherwise transitions to status and publishes
Event::SessionDone { status }.
Test: registry_tests::finish_transitions_and_publishes_session_done,
registry_tests::finish_is_idempotent_on_terminal_session,
registry_tests::finish_unknown_session_errors.
Sourcepub fn attach(
&self,
id: &str,
connection_id: Uuid,
notify: NotifySender,
) -> Result<Vec<SessionEventEnvelope>, RpcError>
pub fn attach( &self, id: &str, connection_id: Uuid, notify: NotifySender, ) -> Result<Vec<SessionEventEnvelope>, RpcError>
session.attach: replay recent history and start forwarding this
session’s live events to notify.
Why: the streaming half of the session-attach protocol (vision spec
§4.4/Axiom 4). Works identically regardless of transport — the
difference between STDIO (long-lived notify, events interleaved on
stdout) and HTTP (throwaway notify; the real live path is the GET /sessions/{id}/events SSE route) lives entirely in
crate::jsonrpc::ConnectionContext’s docs and crate::serve’s
transports, not here.
What: errors with session_not_found if id is unknown. Otherwise
takes a snapshot of the ring buffer (oldest-first, each entry a full
SessionEventEnvelope with its seq intact) to return as the
replay, registers connection_id’s cancel sender (replacing — and
thus cancelling — any prior forwarder for the same
(session, connection) pair), and spawns a task that subscribes to
crate::events::subscribe(), filters by session_id, and forwards
each match into notify as a JSON-RPC notification whose params IS
the envelope ({"jsonrpc":"2.0","method":"session.event","params": {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}})
until detach fires the cancel sender or notify.send fails (the
connection is gone). Because every envelope — replayed or live —
comes from the SAME per-session seq counter (record), a client
that concatenates the replay array with the live notifications it
receives afterward sees one gap-free, strictly increasing sequence.
Test: registry_tests::attach_returns_ring_buffer_replay,
registry_tests::attach_forwards_live_events_until_detach,
registry_tests::attach_replay_then_live_seq_is_contiguous,
registry_tests::attach_unknown_session_errors.
Sourcepub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError>
pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError>
session.detach: stop forwarding this session’s live events to the
calling connection.
Why: the other half of the attach protocol — releases the forwarder
task started by attach for this (session, connection) pair.
What: errors with session_not_found if id is unknown. If the
connection has no live attachment (already detached, or never
attached), this is a no-op success rather than an error — detach is
idempotent. Otherwise fires the stored cancel sender, which stops the
forwarder task on its next select! poll.
Test: registry_tests::detach_stops_the_forwarder,
registry_tests::detach_without_prior_attach_is_a_noop,
registry_tests::detach_unknown_session_errors.
Sourcepub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError>
pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError>
Snapshot the ring buffer for a session without attaching to it.
Why: the HTTP SSE route (crate::serve::http) needs the same replay
burst attach returns, but subscribes to the live bus itself (one
Stream per SSE connection) rather than going through a
NotifySender forwarder — so it calls this directly instead of
attach.
What: same replay semantics as attach (full envelopes, seq
intact), no side effects (no forwarder spawned, no attachment
recorded).
Test: registry_tests::replay_returns_ring_buffer_without_attaching.
Sourcepub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError>
pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError>
Begin tracking a new background task execution for id (#2056).
Why: task.run (and session.send on an idle session) must not start
a second overlapping run for the same session, and the returned flag
is how the executor’s AgentLoop(s) later observe cancellation.
What: errors with session_not_found if id is unknown,
invalid_argument if the session is already terminal or already has
an execution in flight. On success, stores a fresh Arc<AtomicBool>
cancel flag (initially false) with handle: None — the caller
attaches the real JoinHandle via
Self::attach_execution_handle immediately after spawning, since
the handle cannot exist before that — and returns the flag.
Test: registry_tests::begin_execution_rejects_second_overlapping_run,
registry_tests::begin_execution_rejects_terminal_session,
registry_tests::begin_execution_unknown_session_errors.
Sourcepub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>)
pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>)
Attach the real JoinHandle to id’s tracked execution (#2056).
Why: the handle only exists once the caller has actually called
tokio::spawn, which must happen after begin_execution returns (the
spawned future needs the cancel flag begin_execution produces).
What: best-effort — a no-op if id or its execution is already gone
(e.g. the run finished astonishingly fast, or the session vanished).
Test: registry_tests::shutdown_executions_awaits_cancelled_tasks
(exercises this indirectly via a real spawn).
Sourcepub fn finish_execution(&self, id: &str)
pub fn finish_execution(&self, id: &str)
Clear the execution-in-flight marker for id (#2056).
Why: called by the executor once the background task has stopped
(finished, failed, or cancelled) so a later task.run/session.send
can start a new run against the same session.
What: best-effort — a no-op if id is already gone.
Test: registry_tests::begin_execution_rejects_second_overlapping_run
(calls this between the two begin_execution attempts).
Sourcepub fn is_executing(&self, id: &str) -> bool
pub fn is_executing(&self, id: &str) -> bool
Whether id currently has a background execution in flight (#2056).
Why: session::protocol::cancel uses this to choose between
cooperative cancellation (Self::request_cancel) and the original
#2054 immediate-transition Self::cancel.
What: false for both “unknown session” and “known but idle” — callers
that need to distinguish those already call another method first.
Test: registry_tests::request_cancel_*.
Sourcepub fn request_cancel(&self, id: &str) -> Result<bool, RpcError>
pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError>
Request cooperative cancellation of id’s in-flight execution, if any
(#2056).
Why: session.cancel on a RUNNING session must signal the background
task rather than force an immediate status transition — the task
itself transitions to Cancelled once it actually observes the flag
and unwinds (see crate::task::executor).
What: Err(session_not_found) if id is unknown. Ok(true) if an
execution was in flight and its flag was set; Ok(false) if the
session exists but nothing is executing (the caller should fall back
to Self::cancel for the immediate-transition path).
Test: registry_tests::request_cancel_sets_flag_when_executing,
registry_tests::request_cancel_returns_false_when_idle.
Sourcepub fn set_run_outcome(
&self,
id: &str,
transcript: Vec<TurnRecord>,
usage: TokenUsage,
cost_usd: Option<f64>,
)
pub fn set_run_outcome( &self, id: &str, transcript: Vec<TurnRecord>, usage: TokenUsage, cost_usd: Option<f64>, )
Persist a finished execution’s transcript/usage/cost into the session (#2056).
Why: populates the storage Self::get_transcript (#2058) reads back
over the wire.
What: best-effort — a no-op if id is already gone (e.g. the daemon
is shutting down mid-run).
Test: registry_tests::set_run_outcome_stores_transcript_and_usage.
Sourcepub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError>
pub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError>
session.get_transcript: fetch the stored run record for a session
(#2058).
Why: Self::set_run_outcome populates the storage; this is its read
counterpart — the M1 cut-line’s “inspect transcript” verb. A never-run
session is a valid, empty transcript, not an error: SessionEntry’s
transcript/usage/cost_usd fields already default to
empty/zero/None at create time, so returning them unconditionally
(once the session itself is confirmed to exist) is correct with no
extra branching.
What: Err(session_not_found) if id is unknown; otherwise a clone of
whatever is currently stored, wrapped in a self-describing
TranscriptRecord. Never recomputes cost or usage — exposes exactly
what Self::set_run_outcome last stored.
Test: registry_tests::get_transcript_returns_stored_record,
registry_tests::get_transcript_on_never_run_session_is_empty,
registry_tests::get_transcript_unknown_session_errors.
Sourcepub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError>
pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError>
task.run: persist the resolved HarnessMode onto the session
(#2059).
Why: task::protocol::task_run resolves the mode (env var >
task.run param > .claude/settings.json > default) BEFORE spawning
the execution; storing it here — rather than waiting for
set_run_outcome at the end of the run — makes it queryable via
session.status/session.list (Session.mode) and
session.get_transcript (TranscriptRecord.mode, which reads the
SAME field) as soon as task.run returns, not only after the run
completes.
What: Err(session_not_found) if id is unknown; otherwise sets
entry.session.mode = Some(mode). No event is published — mode is
bookkeeping metadata, not a session-lifecycle transition in the
#2055 event taxonomy.
Test: registry_tests::set_mode_stores_on_session,
registry_tests::set_mode_unknown_session_errors.
Sourcepub async fn shutdown_executions(&self, grace: Duration)
pub async fn shutdown_executions(&self, grace: Duration)
Cooperatively cancel every in-flight execution and wait, bounded by
grace, for them to actually stop (#2056 — graceful daemon shutdown).
Why: without this, a tokio::spawn’d background execution would be
abruptly dropped — never given a chance to unwind — the instant the
process’s tokio runtime shuts down, violating the connection-safe
daemon-restart convention (issue #534) this extends from connections
to long-running tasks.
What: flips every tracked execution’s cancel flag, takes ownership of
each JoinHandle, then awaits all of them concurrently with an
overall grace timeout. A handle that doesn’t finish in time is left
to be dropped when the process exits (best-effort, not a hard
guarantee — matching the same best-effort framing as every other
shutdown step in this codebase).
Test: registry_tests::shutdown_executions_awaits_cancelled_tasks.
Sourcepub fn record_tool_started(
&self,
id: &str,
tool: &str,
call_id: &str,
args: &str,
) -> Result<(), RpcError>
pub fn record_tool_started( &self, id: &str, tool: &str, call_id: &str, args: &str, ) -> Result<(), RpcError>
Record a tool invocation starting (#2055 emission plumbing for #2056’s agent loop).
Why: gives the future agent loop a stable, already-wired call for
ToolStarted without it needing to touch the ring buffer, sequencing,
or bus directly.
What: errors with session_not_found if id is unknown; args_preview
is truncated via crate::events::preview before emission so a large
argument payload can’t blow the ring buffer / wire size.
Test: registry_tests::record_tool_started_publishes_event.
Sourcepub fn record_tool_finished(
&self,
id: &str,
tool: &str,
call_id: &str,
success: bool,
result: &str,
) -> Result<(), RpcError>
pub fn record_tool_finished( &self, id: &str, tool: &str, call_id: &str, success: bool, result: &str, ) -> Result<(), RpcError>
Record a tool invocation finishing (#2055 emission plumbing for
#2056’s agent loop). See Self::record_tool_started.
Test: registry_tests::record_tool_finished_publishes_event.
Sourcepub fn record_tool_error(
&self,
id: &str,
tool: &str,
call_id: &str,
error: &str,
) -> Result<(), RpcError>
pub fn record_tool_error( &self, id: &str, tool: &str, call_id: &str, error: &str, ) -> Result<(), RpcError>
Record a tool invocation raising an exceptional error (#2055 emission
plumbing for #2056’s agent loop). See Self::record_tool_started.
Test: registry_tests::record_tool_error_publishes_event.
Sourcepub fn record_log(
&self,
id: &str,
level: &str,
message: &str,
) -> Result<(), RpcError>
pub fn record_log( &self, id: &str, level: &str, message: &str, ) -> Result<(), RpcError>
Record a session-scoped diagnostic log line (#2055 emission plumbing).
Test: registry_tests::record_log_publishes_event.
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for SessionRegistry
impl RefUnwindSafe for SessionRegistry
impl Send for SessionRegistry
impl Sync for SessionRegistry
impl Unpin for SessionRegistry
impl UnsafeUnpin for SessionRegistry
impl UnwindSafe for SessionRegistry
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more