@prismshadow/penguin-server · packages/server/src/runtime/session-manager.ts:3780

Sessions

interface

The session runtime: one entry per live Session, task mutex, approvals, streaming.

API

@Interface()
export abstract class Sessions {
  abstract statusOf(sessionId: string): SessionStatus;
  abstract pendingApprovalCount(sessionId: string): number;
  abstract pendingApprovals(sessionId: string): PendingApproval[];
  abstract pendingFollowUpCount(sessionId: string): number;
  abstract pendingSteeringOf(sessionId: string): PendingSteeringInfo[];
  abstract subagentsOf(sessionId: string): BackgroundSubagentInfo[];
  abstract sendToSubagent(
      sessionId: string,
      childSessionId: string,
      messages: AmspRecord[],
    ): Promise<SubagentMessageOutcome>;
  abstract abortSubagentRun(sessionId: string, childSessionId: string): Promise<boolean>;
  abstract pendingFollowUpsOf(sessionId: string): PendingFollowUpInfo[];
  abstract liveFragments(sessionId: string): AmspRecord[];
  abstract liveRun(sessionId: string): LiveRun | null;
  abstract pendingInputs(sessionId: string): AmspRecord[];
  abstract pendingBootstrap(sessionId: string): AmspRecord[];
  abstract activeCountForAgent(projectId: string, agentId: string): number;
  abstract invalidateAgentRuntimes(projectId: string, agentId: string): void;
  abstract invalidateProjectRuntimes(projectId: string): void;
  abstract assertCanAcceptTask(
      sessionId: string,
      opts?: {
        queueIfBusy?: boolean;
        interrupt?: boolean;
        steerIfBusy?: boolean;
      },
    ): void;
  abstract startTask(
      sessionId: string,
      input: AmspRecord[],
      opts?: {
        queueIfBusy?: boolean;
        interrupt?: boolean;
        steerIfBusy?: boolean;
        recall?: RecallStore;
        promptHooks?: readonly string[];
        /**
         * The signed-in person sending it: the driver of the run it starts — now, or when it leaves
         * the queue (RuntimeEntry.runDriver). Absent for everything nobody signed in sent: the local
         * API token, schedules without a creator, the Agent API, company mode, the bridge.
         */
        driver?: string;
      },
    ): Promise<{ sessionId: string; queued: boolean; steered?: boolean }>;
  abstract retryTask(sessionId: string, driver?: string): Promise<{ sessionId: string }>;
  abstract startGoal(
      sessionId: string,
      args: {
        /** The user's own message(s) exactly as submitted — text and images, no wrapping. */
        messages: AmspRecord[];
        /** The user's own objective text (leading marker blocks stripped): what the plugin records, the goal_started event and the title material. */
        objective: string;
        budget: number;
      },
    ): Promise<{ sessionId: string }>;
  abstract startCompact(sessionId: string): Promise<{ sessionId: string }>;
  abstract startSwitch(
      sessionId: string,
      ref: ModelRefDto,
      whenIdle?: boolean,
    ): Promise<{ sessionId: string; switched: boolean }>;
  abstract onModelChanged(listener: (sessionId: string, model: ModelRefDto) => void): () => void;
  abstract decideApproval(
      sessionId: string,
      toolCallId: string,
      decision: "allow" | "deny",
    ): boolean;
  abstract steer(
      sessionId: string,
      input: AmspRecord[],
      recall: RecallStore,
      driver?: string,
    ): void;
  abstract recallSteering(sessionId: string, steerId: string): RecallStore;
  abstract recallFollowUp(sessionId: string, followUpId: string): { recall: RecallStore };
  abstract interruptQueued(
      sessionId: string,
      target:
        | {
            followUpId: string;
          }
        | {
            steerId: string;
          },
    ): void;
  abstract retryNow(sessionId: string): boolean;
  abstract abortTask(sessionId: string): boolean;
  abstract listProcesses(sessionId: string): BackgroundCommandInfo[];
  abstract listToolCalls(sessionId: string): ToolCallListing[];
  abstract probeProcessServices(sessionId: string): Promise<void>;
  abstract killProcess(sessionId: string, processId: string): boolean;
  abstract removeProcess(sessionId: string, processId: string): "removed" | "running" | "not_found";
  abstract abortProject(projectId: string): Promise<void>[];
  abstract beginAgentDeletion(projectId: string, agentId: string): Promise<void>[];
  abstract endAgentDeletion(projectId: string, agentId: string): void;
  abstract beginSessionDeletion(sessionId: string): Promise<void>[];
  abstract endSessionDeletion(sessionId: string): void;
  abstract atIdleBoundary<T>(sessionId: string, operation: () => Promise<T>): Promise<T>;
  abstract shutdown(timeoutMs?: number): Promise<void>;
  abstract detach(): void;
  abstract runningSessionIds(): string[];
  abstract sweepIdle(now?: number, idleMs?: number): void;
  abstract keepLoaded(sessionId: string, on: boolean): void;
  abstract preload(sessionId: string): Promise<void>;
}

Contract Topology

Static AST wiring across @Module / @Provide / @Use

Members (47)

statusOf

statusOf(sessionId: string): SessionStatus
@paramsessionIdstring
@returnsSessionStatus

pendingApprovalCount

pendingApprovalCount(sessionId: string): number
@paramsessionIdstring
@returnsnumber

pendingApprovals

pendingApprovals(sessionId: string): PendingApproval[]
@paramsessionIdstring
@returnsPendingApproval[]

pendingFollowUpCount

pendingFollowUpCount(sessionId: string): number

Number of queued follow-up tasks (queueIfBusy) awaiting auto-start.

@paramsessionIdstring
@returnsnumber

pendingSteeringOf

pendingSteeringOf(sessionId: string): PendingSteeringInfo[]

Steering messages queued but not yet delivered to the model (display mirror; see RuntimeEntry.pendingSteering).

@paramsessionIdstring
@returnsPendingSteeringInfo[]

subagentsOf

subagentsOf(sessionId: string): BackgroundSubagentInfo[]

Live subagent children of an ACTIVE runtime entry (empty when the session is not loaded — after a restart there is no in-process child left to report, so empty is the truth). Rides task_state events and the SSE subscribe snapshot; the panel renders child running marks from this instead of parsing tool-output text.

@paramsessionIdstring
@returnsBackgroundSubagentInfo[]

sendToSubagent

sendToSubagent(sessionId: string, childSessionId: string, messages: AmspRecord[]): Promise<SubagentMessageOutcome>

Host message to one child session — a user input on the child, whatever its state: steering while it runs, a follow-up run while it is idle, a revival (resume-session semantics) when it is no longer live (core Session.sendToBackgroundSubagent). The parent runtime itself is loaded on demand (ensureEntry — the same get-or-resume path a task uses), so messaging a child of a long-idle conversation works after a restart too; the resume fallback names the child's owning Agent from its own session row, which must belong to the parent's project.

@paramsessionIdstring
@paramchildSessionIdstring
@parammessagesAmspRecord[]
@returnsPromise<SubagentMessageOutcome>

abortSubagentRun

abortSubagentRun(sessionId: string, childSessionId: string): Promise<boolean>

Host abort of one child session's current run (core Session.abortBackgroundSubagentRun); false when the parent runtime is not loaded, the child is unknown, or it is idle.

@paramsessionIdstring
@paramchildSessionIdstring
@returnsPromise<boolean>

pendingFollowUpsOf

pendingFollowUpsOf(sessionId: string): PendingFollowUpInfo[]

Queued follow-up tasks awaiting auto-start, as their display/recall info (id + content summary).

@paramsessionIdstring
@returnsPendingFollowUpInfo[]

liveFragments

liveFragments(sessionId: string): AmspRecord[]

Live tail of a running session: one synthetic partial_* start AmspRecord per open streaming fragment, carrying the full accumulated content so far (see live-tail.ts). Empty when idle or when nothing is streaming. GET /messages attaches this (with a channel cursor) so a client joining mid-stream can render the in-progress message.

@paramsessionIdstring
@returnsAmspRecord[]

liveRun

liveRun(sessionId: string): LiveRun | null

The current run's records (one drive: a Task, a goal loop, a compaction or a model switch) in publish order, each streamed fragment's deltas folded into its start, with the records the run starts at; null when no run is under way (see live-tail.ts). The run form of GET /messages attaches the records and cuts its history read before the run.

@paramsessionIdstring
@returnsLiveRun | null

pendingInputs

pendingInputs(sessionId: string): AmspRecord[]

The running Task's input messages as published at launch; empty when idle. The engine writes these exact envelopes to the Trace only after the first run's bootstrap (MCP connect + discovery), so GET /messages appends whichever of them the Trace read has not caught up to yet — without this, a client rebuilding history during the connect (the draft flow subscribes only after the input publish) loses the user's own message.

@paramsessionIdstring
@returnsAmspRecord[]

pendingBootstrap

pendingBootstrap(sessionId: string): AmspRecord[]

The running Task's streamed bootstrap records (see RuntimeEntry.pendingBootstrap); empty when idle.

@paramsessionIdstring
@returnsAmspRecord[]

activeCountForAgent

activeCountForAgent(projectId: string, agentId: string): number

Number of Sessions for this Agent that are currently running / compacting.

@paramprojectIdstring
@paramagentIdstring
@returnsnumber

invalidateAgentRuntimes

invalidateAgentRuntimes(projectId: string, agentId: string): void

Bumps one Agent's config generation so every runtime built before it is discarded on its next idle access and re-resumed via the loader (history is preserved through the Trace). What warrants it is a Session-fixed fact changing under the runtime — the Project's credentials (see invalidateProjectRuntimes). Agent State changes never do: core reads them into the next model context itself. A Task already in flight is neither aborted nor hot-swapped: it keeps the values it started with, and its entry is rebuilt on the first access after it returns to idle (see ensureEntry).

@paramprojectIdstring
@paramagentIdstring
@returnsvoid

invalidateProjectRuntimes

invalidateProjectRuntimes(projectId: string): void

After a Project's models/credentials change: invalidate every cached runtime in this Project, so the next Task re-resumes with the new api_key / base_url. Same effective-value semantics as invalidateAgentRuntimes — no hot swap into a Task already in flight. Iterating the active table is complete here, not a shortcut: the generation map only matters for runtimes that are already cached, and an Agent with no cached entry builds fresh through the loader anyway.

@paramprojectIdstring
@returnsvoid

assertCanAcceptTask

assertCanAcceptTask(sessionId: string, opts?: { queueIfBusy?: boolean; interrupt?: boolean; steerIfBusy?: boolean; }): void

Cheap, lock-free rehearsal of the 409/503 conditions startTask checks, throwing exactly the same HttpErrors. Advisory only: it neither takes the Session lock nor loads an entry, so a session that isn't in the active table reads as acceptable and a status change racing this call is not caught — the authoritative check is still the one inside startTask.

It exists so a caller that has irreversible work to do first (POST /tasks writes the message's file attachments to disk) can find out about the ordinary "a Task is already running" rejection before doing it, instead of undoing it afterwards.

@paramsessionIdstring
@paramopts?{ queueIfBusy?: boolean; interrupt?: boolean; steerIfBusy?: boolean; }
@returnsvoid

startTask

startTask(sessionId: string, input: AmspRecord[], opts?: { queueIfBusy?: boolean; interrupt?: boolean; steerIfBusy?: boolean; recall?: RecallStore; promptHooks?: readonly string[]; driver?: string; }): Promise<{ sessionId: string; queued: boolean; steered?: boolean }>

Start a Task: get-or-load → 409 mutual-exclusion check → publish the input messages first → drive run in the background. Returns the current actual session_id (the new id after self-heal). With queueIfBusy, a busy session (running/compacting) enqueues the input as a follow-up instead of 409: it auto-starts as an ordinary next task once the session returns to idle (queued: true in the result; see startQueuedFollowUp). opts.recall is that queued message's original content — optional, because only the HTTP route knows the parts of it the input does not carry (the pre-attachment text and where each file landed on disk); every other caller's store is read off the input, so a queued follow-up is recallable and shows its content whichever path queued it.

With interrupt, a busy session aborts its run and the input waits at the head of the queue instead (see enqueueInterrupt). So does an idle one whose queue has not drained yet, so that the interrupt cannot overtake an earlier one still waiting to start.

With steerIfBusy, a running Task takes the input as steering, exactly as steer gives it (steered: true; recall is then the steering message's content). A compaction has no Task to steer, and a run already settling no longer takes steering (core refuses it): both queue the input as queueIfBusy does. Decided here, under the lock, so one request does whatever the Session's state calls for.

promptHooks names the composer's switches (prompt-hooks.ts): their contexts join the input behind the user's message once it is known to start, queue or interrupt — a steered input takes none, as steering consults no user_prompt hook. recall stays the user's own.

@paramsessionIdstring
@paraminputAmspRecord[]
@paramopts?{ queueIfBusy?: boolean; interrupt?: boolean; steerIfBusy?: boolean; recall?: RecallStore; promptHooks?: readonly string[]; driver?: string; }
@returnsPromise<{ sessionId: string; queued: boolean; steered?: boolean }>

retryTask

retryTask(sessionId: string, driver?: string): Promise<{ sessionId: string }>

Retry a failed or stopped run (POST /retry): a Task started with EMPTY input, so core sends the input of the turn that did not finish — held as carry-over since the run ended fatal, gave up reconnecting or was stopped by the user, with whatever the model had already written — and nothing else. No user message is published or recorded, and with no Prompt there is no user_prompt consult. Gated like startTask (busy is the same 409) but never queued, and refused with 409 nothing_to_retry when nothing is held — the user's next message already resent that input, or no run was cut short — since the run would end at once and the client would watch a Task start and stop with nothing sent. Not a person's input for company mode's hop accounting: the turn it resends was counted, or not, when it was first sent.

@paramsessionIdstring
@paramdriver?string
@returnsPromise<{ sessionId: string }>

startGoal

startGoal(sessionId: string, args: { messages: AmspRecord[]; objective: string; budget: number; }): Promise<{ sessionId: string }>

Start a goal run: like startTask, but the goal plugin composes the input and its stop hook drives every later round inside this one session.run call — so the Session stays running for the whole goal (every round), the existing abort endpoint interrupts the entire loop and schedules queue behind it as usual. The plugin's user_prompt hook (hooks run in core and nowhere else — Session.runUserPromptHook) writes the Session's goal file and answers the round-1 protocol message; it runs under the session lock AFTER the idle check, since it overwrites the goal file a running goal is reading. An Agent without the goal plugin's hook package is refused with the route's 409 before the Session is even loaded (goal-plugin.ts); a loaded Session whose hook answers null is the same 409, and an empty answer a 500. Round inputs are yielded by core and published like any streamed message; progress additionally goes out as goal_* server events (the run state itself is the goal file the plugin maintains).

@paramsessionIdstring
@paramargs{ messages: AmspRecord[]; objective: string; budget: number; }
@returnsPromise<{ sessionId: string }>

startCompact

startCompact(sessionId: string): Promise<{ sessionId: string }>

Manually compact the context: 409 if already running; compaction output also flows into the SSE channel.

@paramsessionIdstring
@returnsPromise<{ sessionId: string }>

startSwitch

startSwitch(sessionId: string, ref: ModelRefDto, whenIdle?: boolean): Promise<{ sessionId: string; switched: boolean }>

Switches the Session's model in place (POST /switch-model) — core Session.switchModel, gated like a compaction (open, not deleting, idle). Core decides everything before its first event, so the head of its stream is pulled here, under the lock, and tells the three outcomes apart:

  • it throws — a refusal, answered 409 with the code of its reason (see switchRefusal);
  • it is already done — a Session that never ran has no context to close: core re-assembled its first context on the target, nothing streams, and the row carries the new pair by the time this returns (switched: true; the route answers with the fresh DTO);
  • it yields — a driven run like a compaction (switched: false): status compacting, idle when it ends. The head is a compaction's begin, the first record of a bootstrap (a Session loaded from its Trace opens its context first), or — for a context with no completed turn, which streams no pair — the opener's first record.

The switch is the entry's run from that pull on — it can be stopped, and a deletion or a shutdown waits for it — while the entry only reads compacting once there is something to stream, so a refusal never flickers a state.

The entry and the row follow the runtime as the new context's session_meta passes through the drive (see drive); a switch that does not complete streams no meta and leaves them where they were. Usage: a drive bills to the model it started on, so the switch's compaction request goes to the model that served it and the next run to the new one.

A Session not in memory is loaded the ordinary way first, so a refusal of the target is core's, as for any loaded Session. Only one the ordinary load refuses — its model can no longer be reached — is loaded for this switch alone (SessionLoader.load's switchTo): with a Trace it is resumed anyway, since core then hands its history over by Trace path rather than ask that model for a summary; without one it is rebuilt on the target, and the load is the whole switch (200, or the target's 409). Such a runtime runs nothing on the model it cannot reach (RuntimeEntry.stranded), and one the switch did not move is not kept: the next access loads it the ordinary way and meets the ordinary refusal.

@paramsessionIdstring
@paramrefModelRefDto
@paramwhenIdle?boolean
@returnsPromise<{ sessionId: string; switched: boolean }>

onModelChanged

onModelChanged(listener: (sessionId: string, model: ModelRefDto) => void): () => void

Subscribes to a Session's model moving: an in-session switch completing, or a row brought back in step with its Trace when the Session loads. The listener runs once the entry and the row carry the new pair. Returns the unsubscribe. Company mode listens: an employee's model is its desk Session's.

@paramlistener(sessionId: string, model: ModelRefDto) => void
@returns() => void

decideApproval

decideApproval(sessionId: string, toolCallId: string, decision: "allow" | "deny"): boolean

Submit an approval decision; returns false if the pending approval doesn't exist (already decided/unknown).

@paramsessionIdstring
@paramtoolCallIdstring
@paramdecision"allow" | "deny"
@returnsboolean

steer

steer(sessionId: string, input: AmspRecord[], recall: RecallStore, driver?: string): void

Mid-run steering: forward the message to the running Session (core delivers it between turns as a standalone [user_steering] user message followed by its images — no SSE event of its own; the messages arrive through the stream the drive loop already publishes). 409 when the Session isn't running a Task (idle / compacting / not loaded) or the run finished in the race window — the caller falls back to submitting a normal task, which carries the same text and images.

recall is the queued message's original content: its summary (with a fresh id) is mirrored on the entry and broadcast via task_state (and the SSE subscribe snapshot) until the delivered [user_steering] message is observed on the stream — that is what keeps the composer's "steering queued" hint, content included, alive across reloads — and the content itself is what a recall (recallSteering) hands back to the composer.

@paramsessionIdstring
@paraminputAmspRecord[]
@paramrecallRecallStore
@paramdriver?string
@returnsvoid

recallSteering

recallSteering(sessionId: string, steerId: string): RecallStore

Recall an undelivered steering message (#287): withdraw it from core's queue and the display mirror, re-broadcast state, and hand back its original content for the composer to restore. 409 not_pending when the entry is no longer queued — already delivered to the model (core's unsteer says so authoritatively; the mirror can lag behind delivery until the [user_steering] message is observed on the stream), the run exited, or the id is unknown — all the same outcome for the caller: nothing left to take back.

@paramsessionIdstring
@paramsteerIdstring
@returnsRecallStore

recallFollowUp

recallFollowUp(sessionId: string, followUpId: string): { recall: RecallStore }

Recall a queued follow-up task (#287): remove it from the queue before it auto-starts, re-broadcast state, and hand back its original content (plus the thinking level it was queued with). Being in the queue is the whole condition — every queued entry carries a recall store (see QueuedFollowUp.recall), so no queued message is ever refused. 409 follow_up_started when the id is not in the queue: it already auto-started, or the runtime was released and took the queue with it. Its own code, distinct from steering's not_pending, because the two mean different things to the user — a follow-up became a task of its own, a steering message reached the model mid-run.

@paramsessionIdstring
@paramfollowUpIdstring
@returns{ recall: RecallStore }

interruptQueued

interruptQueued(sessionId: string, target: | { followUpId: string; } | { steerId: string; }): void

Send one waiting message now (POST /interrupt): the queued follow-up followUpId names, or the undelivered steering message steerId names, becomes an interrupt (see enqueueInterrupt). A follow-up keeps its id, so it stays recallable by it; one that is an interrupt already is left where it is. 409 follow_up_started when the follow-up is no longer queued, 409 not_pending when the steering message already reached the model.

@paramsessionIdstring
@paramtarget| { followUpId: string; } | { steerId: string; }
@returnsvoid

retryNow

retryNow(sessionId: string): boolean

"Retry now" on the reconnect countdown: skip the in-progress backoff wait and fire the next retry immediately (the attempt counter is unchanged — the skipped wait does not consume an extra attempt). Returns false as a benign no-op when the session has no active runtime or no reconnect wait is in progress — timing races (the wait elapsed right before the click) must not surface as errors. Mirrors the steer seam: manager → RuntimeSession → core Session → engine.

@paramsessionIdstring
@returnsboolean

abortTask

abortTask(sessionId: string): boolean

Interrupt the current Task/compaction: pending approvals converge to deny first, then the AbortSignal fires. Returns false if nothing is in progress (the route treats this as a 204 no-op).

@paramsessionIdstring
@returnsboolean

listProcesses

listProcesses(sessionId: string): BackgroundCommandInfo[]

Background command processes of a LOADED session (empty when the entry is not in the active table — a resumed entry starts with a fresh environment and can only ever report an empty list, so nothing is resurrected just to answer a poll).

@paramsessionIdstring
@returnsBackgroundCommandInfo[]

listToolCalls

listToolCalls(sessionId: string): ToolCallListing[]

Executing tool calls of a loaded session (or hosted subagent child).

@paramsessionIdstring
@returnsToolCallListing[]

probeProcessServices

probeProcessServices(sessionId: string): Promise<void>

Refreshes the listen-port probes behind the process list's serviceUrl (core Session.probeBackgroundCommandServices): called by the processes route before listing, so the first fetch already carries probed URLs. Bounded by core's own probe timeout and TTL; a session that isn't loaded has no processes to probe.

@paramsessionIdstring
@returnsPromise<void>

killProcess

killProcess(sessionId: string, processId: string): boolean

Kills one background command process of a loaded session; false when the session isn't loaded or the id is unknown.

@paramsessionIdstring
@paramprocessIdstring
@returnsboolean

removeProcess

removeProcess(sessionId: string, processId: string): "removed" | "running" | "not_found"

Removes one EXITED background command entry from a loaded session's process list. A running process is refused ("running") — stopping is killProcess's job, and a bare removal must never surprise-signal a live process group. "not_found" covers an unloaded session and an unknown id alike: the entry is gone either way. The removal itself reuses the kill path — core's registry removal signals the (dead) group defensively and drops the row, exactly like input_command's post-exit reap. The only race, an entry observed running that exits before a retry, is benign: the caller gets "running", refreshes, and sees the row exited on the next look.

Note what leaves with the row: the registry entry owns the ManagedSession holding that process's captured output, so after a removal input_command on the same process_id answers "unknown process_id". Removal is a deliberate discard, not just a list tidy-up — the Web App says so at the button and in the docs.

@paramsessionIdstring
@paramprocessIdstring
@returns"removed" | "running" | "not_found"

abortProject

abortProject(projectId: string): Promise<void>[]

Before deleting a Project, converge all its active runs and clear them out of the active table. Returns the drive and background-cleanup Promises of the affected entries: the caller (deleteProject) should await them before removing the directory, so that interrupt-cleanup Trace writes don't recreate the directory after deletion.

@paramprojectIdstring
@returnsPromise<void>[]

beginAgentDeletion

beginAgentDeletion(projectId: string, agentId: string): Promise<void>[]

Before deleting an Agent, converge all its active runs and clear them out of the active table (same semantics as abortProject). Also marks this Agent as "being deleted": new Tasks/compactions entering during the deletion process are always rejected with 409 (assertAgentNotDeleting), closing the race window where a new task recreates the directory and revives an already-deleted Agent between the abortAgent snapshot and the directory removal. The caller must call endAgentDeletion once deletion finishes (success or failure).

@paramprojectIdstring
@paramagentIdstring
@returnsPromise<void>[]

endAgentDeletion

endAgentDeletion(projectId: string, agentId: string): void
@paramprojectIdstring
@paramagentIdstring
@returnsvoid

beginSessionDeletion

beginSessionDeletion(sessionId: string): Promise<void>[]

Before deleting a single Session, converge its active run and clear it out of the active table (same semantics as beginAgentDeletion). Also marks this Session as "being deleted": new Tasks/compactions entering during the deletion process are always rejected with 409 (assertSessionNotDeleting), closing the race window where a new task recreates the entry and Trace file, reviving an already-deleted Session between the abort snapshot and the file removal. The caller must call endSessionDeletion once deletion finishes (success or failure). Returns the drive and background-cleanup Promise: the caller should await it before deleting the Trace file, so cleanup writes don't recreate the file.

@paramsessionIdstring
@returnsPromise<void>[]

endSessionDeletion

endSessionDeletion(sessionId: string): void
@paramsessionIdstring
@returnsvoid

atIdleBoundary

atIdleBoundary<T>(sessionId: string, operation: () => Promise<T>): Promise<T>

Run a metadata operation at an idle Session boundary under the same mutex as Task and compaction starts. Session fork uses this to snapshot an append-only Trace without a Task beginning between its status check and final read. An uncached Session is idle by definition; unlike startTask this path deliberately does not load a heavyweight runtime.

@paramsessionIdstring
@paramoperation() => Promise<T>
@returnsPromise<T>

shutdown

shutdown(timeoutMs?: number): Promise<void>

Graceful shutdown: reject new tasks (503), interrupt all active runs, and wait for them to finish (default ≤5s).

@paramtimeoutMs?number
@returnsPromise<void>

detach

detach(): void

The hand-over's half of a swap: this generation stops working on the state and leaves everything in it as it is — running Tasks keep running, pending approvals keep waiting — for the next generation to take over (PRFC-0015). Only what is this instance's own stops: the idle sweep. shutdown is the other ending, for a state nobody takes over.

@returnsvoid

runningSessionIds

runningSessionIds(): string[]

The Sessions with a Task in flight right now — what a swap parks, so that a successor that cannot take the state over knows which ones to start again.

@returnsstring[]

sweepIdle

sweepIdle(now?: number, idleMs?: number): void

Active-table idle eviction: removes entries that are idle (idle status, no pending approvals, no in-flight drive) and have been inactive past the timeout, releasing the core Session's full in-memory history. This is purely memory reclamation: the next access re-resumes via the loader, so correctness is unaffected. Lock-table entries are auto-cleaned by withLock once their chain drains (including leftover entries under the old id after self-heal). now / idleMs are injectable for tests and timers.

@paramnow?number
@paramidleMs?number
@returnsvoid

keepLoaded

keepLoaded(sessionId: string, on: boolean): void

Pins (on) or releases a Session's runtime entry against idle eviction (see sweepIdle). The messaging bridge holds the pin for as long as a binding's connection is enabled: that Session is where the bot lives on this server, and evicting it after half an hour of quiet makes the next chat message wait for a resume from the Trace before anything else happens.

It pins only what is loaded and loads nothing itself (preload does). A stale id pins nothing: an entry a delete removed is gone from the table whatever this set says, and the bridge releases the id when its connection goes.

@paramsessionIdstring
@paramonboolean
@returnsvoid

preload

preload(sessionId: string): Promise<void>

Loads a Session's runtime into the active table ahead of its first Task, through the same get-or-resume path that Task would take, so the first message after a messaging connection comes up — an enable, a server restart — does not pay for a resume from the Trace on top of everything else. Only the load: no run starts, and the core bootstrap (session metadata, MCP connections) still happens on the first run. Under the Session lock, like startTask, so a Task arriving mid-load waits for this load instead of starting a second one.

A Session that is gone or being deleted, alone or with its Agent, resolves quietly: there is nothing to warm and the caller has nothing to do about it. One that never ran is rebuilt under its own id (see createCoreSessionLoader), so the binding that asked keeps its Session. Any other load failure rejects; the first Task meets the same failure and reports it where a person will see it.

@paramsessionIdstring
@returnsPromise<void>