-
Notifications
You must be signed in to change notification settings - Fork 0
packages coding agent session runtime
Active contributors: Mario Zechner, kt, Armin Ronacher
The session runtime turns a bare Agent into a durable, resumable Prime Agent session. It owns turn admission and queues, JSONL transcript persistence, model and thinking settings, compaction and branching, the event stream that clients render, and the IPython kernel. There are two creation paths: the simple createAgentSession factory in packages/coding-agent/src/core/sdk.ts, and the services-based trio (createAgentSessionServices, createAgentSessionFromServices, createAgentSessionRuntime) that the CLI and the web adapter use when they need cwd-bound services and session replacement.
- Keep one long-lived
AgentSessionper session file, so prompts, steering messages, background jobs, and RLM subagents all flow through the same admission queue. - Persist every message, model change, compaction, and branch as append-only JSONL entries that survive process restarts and rehydrate into LLM context.
- Emit typed events (
AgentSessionEvent) so clients (TUI, web, RPC) render turns without touching session internals.
packages/coding-agent/src/core/
├── sdk.ts # createAgentSession factory
├── agent-session.ts # AgentSession class, AgentSessionEvent, turn and tool hooks
├── agent-session-runtime.ts # AgentSessionRuntime + createAgentSessionRuntime
├── agent-session-services.ts # createAgentSessionServices / createAgentSessionFromServices
├── agent-session-config.ts # AgentSessionRuntimeConfig + mergeAgentSessionRuntimeConfig
├── session-manager.ts # SessionManager, entry types, JSONL I/O, context building
├── session-id.ts # display ids, suffix matching, normalization
├── session-cwd.ts # stored-cwd validation, MissingSessionCwdError
├── session-lease.ts # per-session-file write leases
├── session-file-actions.ts # deleteSessionFile (trash then unlink) + artifacts
├── session-resolver.ts # resolve --resume selectors to session files
├── session-import-errors.ts # SessionImportFileNotFoundError
├── session-action-store.ts # ActionStore, session action lifecycle
├── session-stats.ts # SessionStats shape
├── event-bus.ts # channel-based EventBus for UI wiring
├── context-tree.ts # context usage trees for /context and snapshots
├── compaction/
│ ├── index.ts # re-exports compaction + branch summarization
│ ├── compaction.ts # cut-point detection, token accounting, summarize + compact
│ ├── branch-summarization.ts # branch summary generation for tree navigation
│ └── utils.ts # file-op tracking, conversation serialization
├── agent-messages.ts # agent-to-agent messaging bridge
├── agent-traces.ts # trace upload to the traces endpoint
├── timings.ts # PI_TIMING=1 startup instrumentation
├── defaults.ts # DEFAULT_THINKING_LEVEL
├── system-prompt.ts # buildSystemPrompt
├── settings-manager.ts # settings.json (global + project)
├── auth-storage.ts # auth.json API keys and OAuth credentials
├── side-question.ts # startSideQuestion
├── footer-data-provider.ts # git branch + extension statuses for the footer
├── source-info.ts # SourceInfo for loaded resources
├── resource-loader.ts # DefaultResourceLoader, project context files
└── resolve-config-value.ts # env / shell command / literal config resolution
| Type / function | Full path | One-line description |
|---|---|---|
createAgentSession |
packages/coding-agent/src/core/sdk.ts |
Resolves defaults and builds an AgentSession around an Agent
|
AgentSession |
packages/coding-agent/src/core/agent-session.ts |
The session: prompt/steer/followUp, event emission, persistence, compaction, tools, RLM children |
AgentSessionRuntime |
packages/coding-agent/src/core/agent-session-runtime.ts |
Owns a session plus cwd-bound services; newSession, switchSession, fork, importFromJsonl, dispose
|
AgentSessionServices |
packages/coding-agent/src/core/agent-session-services.ts |
cwd-bound bundle: auth, settings, models, resources, MCP, diagnostics |
createAgentSessionServices |
packages/coding-agent/src/core/agent-session-services.ts |
Builds services without a session; used by packages/coding-agent/src/main.ts and web/server
|
SessionManager |
packages/coding-agent/src/core/session-manager.ts |
JSONL persistence, entry tree, buildSessionContext, branching |
ActionStore |
packages/coding-agent/src/core/session-action-store.ts |
Two delivery queues and the session-action lifecycle state machine |
createEventBus |
packages/coding-agent/src/core/event-bus.ts |
Channel-based emitter wrapping node:events
|
shouldCompact / compact
|
packages/coding-agent/src/core/compaction/compaction.ts |
Threshold check and summarization that shrinks model context |
generateBranchSummary |
packages/coding-agent/src/core/compaction/branch-summarization.ts |
Summarizes an abandoned branch on tree navigation |
buildSystemPrompt |
packages/coding-agent/src/core/system-prompt.ts |
Composes the model-facing system prompt with tools, context files, and skills |
SettingsManager |
packages/coding-agent/src/core/settings-manager.ts |
Loads and saves ~/.prime/agent/settings.json with file locking |
AuthStorage |
packages/coding-agent/src/core/auth-storage.ts |
Credential storage for API keys and OAuth tokens |
createAgentSession in packages/coding-agent/src/core/sdk.ts is the minimal factory. It derives cwd and the config dir, creates AuthStorage, ModelRegistry, SettingsManager, and SessionManager, wires the MCP manager, reloads a DefaultResourceLoader, restores model/thinking/service tier from the existing transcript when continuing, clamps the thinking level to the model's capabilities, builds an Agent (with streamFn resolving auth via the model registry and extension hooks for onPayload, onResponse, and transformContext), and returns { session, extensionsResult, modelFallbackMessage }.
The services-based path separates concerns. createAgentSessionServices in packages/coding-agent/src/core/agent-session-services.ts creates the cwd-bound services bundle and collects non-fatal AgentSessionRuntimeDiagnostic entries (telemetry notice, extension provider registration errors, unknown extension flags). createAgentSessionFromServices then calls createAgentSession with those services and installs trace upload and telemetry. createAgentSessionRuntime in packages/coding-agent/src/core/agent-session-runtime.ts adds the AgentSessionRuntime wrapper, which acquires a session lease and drives session replacement.
The constructor of AgentSession in packages/coding-agent/src/core/agent-session.ts subscribes to the wrapped Agent's event stream, installs extension tool hooks (beforeToolCall / afterToolCall map to the tool_call / tool_result extension events), turn hooks (shouldStopBeforeTurn / shouldStopAfterTurn), and the continuation hook (getContinuationMessages). It then builds the runtime tools and the system prompt.
Inputs enter through the action store. prompt and steer/followUp in packages/coding-agent/src/core/session-action-store.ts normalize the text (slash commands, skills, prompt templates), create a SessionAction, and admit it through the ActionStore under a delivery policy (next_turn_boundary or when_run_idle). An action moves through queued -> selected -> preparing -> committing -> running -> completed | failed | cancelled. canSelectSessionAction gates selection while the agent is streaming, compacting, retrying, running bash, or applying refinement.
The turn itself runs in the Agent: it streams the assistant response from the provider, executes tool calls, and emits AgentEvents (message_start, message_update, message_end, tool_execution_*, agent_end). AgentSession consumes those events to persist entries, emit AgentSessionEvent to subscribers, schedule auto-compaction, and run retry and refinement logic.
sequenceDiagram
participant C as Client (TUI, web, RPC)
participant AS as AgentSession
participant A as Agent (pi-agent-core)
participant P as Provider stream (pi-ai)
participant T as Tools (kernel, bash, edit)
participant SM as SessionManager
participant J as session JSONL
C->>AS: prompt(text)
AS->>AS: normalize (slash cmd, skills, templates)
AS->>AS: admit session action (ActionStore)
AS->>A: agent.prompt()
A->>P: stream assistant response
P-->>A: text deltas or tool calls
A->>T: execute tool call
T-->>A: partial output, then final result
A-->>AS: agent events (message_start/end, agent_end)
AS->>SM: appendMessage and friends
SM->>J: append JSONL line
AS-->>C: AgentSessionEvent via subscribe()
Note over AS,SM: after agent_end: auto-compact check, retry, refinement
SessionManager in packages/coding-agent/src/core/session-manager.ts is the persistence layer. Sessions are JSONL files at ~/.prime/agent/sessions/<id>.jsonl; the exact layout is documented in packages/coding-agent/docs/session-format.md. The first line is the session header (version, id, timestamp, cwd, optional parentSession, rlmDepth, git). Every following line is a typed entry with id and parentId, which forms a tree so branching happens in place without new files. Current format is version 3; v1 and v2 files are migrated on load via migrateSessionEntries.
Entry types include message (any AgentMessage), model_change, thinking_level_change, service_tier_change, compaction, branch_summary, custom (extension state, not in context), custom_message (extension content, in context), child_usage_attributed, label, session_info, session_state, agent_status, and git_state. buildSessionContext walks from the current leaf to the root and produces the message list for the LLM, emitting a compaction summary first when one is on the path. Bookkeeping entries never enter model context.
Compaction keeps context bounded. shouldCompact in packages/coding-agent/src/core/compaction/compaction.ts triggers when estimated context tokens exceed contextWindow - reserveTokens; defaults are reserveTokens: 16384 and keepRecentTokens: 20000 in DEFAULT_COMPACTION_SETTINGS. findCutPoint walks backward from the newest entry accumulating estimated tokens until the keep-recent budget is met, never cutting at a tool result. prepareCompaction produces a CompactionPreparation; compact calls generateSummary (via completeSimple in packages/ai) and appends file-operation lists. The session manager records a compaction entry, and the next buildSessionContext reads summary-first context. Compaction runs manually (/compact, AgentSession.compact) or automatically at the threshold after a turn.
Branching interacts with the same tree. Navigating the tree (navigateTree in packages/coding-agent/src/core/agent-session.ts) moves the session leaf; when leaving a branch with content, collectEntriesForBranchSummary and generateBranchSummary in packages/coding-agent/src/core/compaction/branch-summarization.ts summarize the abandoned path up to the common ancestor, and branchWithSummary in packages/coding-agent/src/core/session-manager.ts appends a branch_summary entry. createBranchedSession extracts a single root-to-leaf path into a new session file. Forks record the source path in the new header's parentSession field.
-
packages/coding-agent/src/core/session-id.tsformats display ids (last 12 hex chars), matches suffix selectors, and normalizes ids for comparison. -
packages/coding-agent/src/core/session-cwd.tsvalidates that a session's stored cwd still exists;assertSessionCwdExiststhrowsMissingSessionCwdErrorotherwise so resume can prompt for a fallback. -
packages/coding-agent/src/core/session-lease.tsgives each session file a single writer.acquireSessionLeasewrites anowner.jsonunder<agentDir>/session-leases/guarded byproper-lockfileand throwsSessionAlreadyActiveErrorwhen another live process owns the file. Leases are enabled viaPRIME_AGENT_INTERNAL_SESSION_LEASES. -
packages/coding-agent/src/core/session-file-actions.tsdeletes a session file by trying thetrashCLI first and falling back tounlink, then removes the session artifact directory. -
packages/coding-agent/src/core/session-resolver.tsturns a--resumeselector into a session path: explicit paths win, then exact and suffix matches against local and global session lists, with edit-distance suggestions on miss. -
packages/coding-agent/src/core/session-import-errors.tsdefinesSessionImportFileNotFoundError, thrown byimportFromJsonl.
-
packages/coding-agent/src/core/event-bus.tsprovides a small channel emitter (wrappingnode:events) used to wire UI services; the session's own event stream isAgentSession.subscribe. -
packages/coding-agent/src/core/context-tree.tsbuildsContextTreeNodetrees with own-versus-attributed usage for/contextand connection snapshots, including disk-only RLM child nodes. -
packages/coding-agent/src/core/agent-messages.tsimplements agent-to-agent messaging: theagent_messagecustom type, the family roster, rate limiting, and kernel host handlers (agent_message.send,agent_message.list_agents). -
packages/coding-agent/src/core/agent-traces.tsuploads session transcripts to the traces endpoint with debounce, retry, and rate limiting. -
packages/coding-agent/src/core/timings.tsrecords startup timings whenPI_TIMING=1. -
packages/coding-agent/src/core/agent-session-config.tsdefinesAgentSessionRuntimeConfigandmergeAgentSessionRuntimeConfig, the shape that carries CLI options into runtime creation. -
packages/coding-agent/src/core/defaults.tsholdsDEFAULT_THINKING_LEVEL("medium"). -
packages/coding-agent/src/core/system-prompt.tscomposes the system prompt viabuildSystemPrompt(RLM prompt, tools, context files, skills, harness state). -
packages/coding-agent/src/core/settings-manager.tsandpackages/coding-agent/src/core/auth-storage.tsmanage~/.prime/agent/settings.jsonand~/.prime/agent/auth.jsonwith file locking;packages/coding-agent/src/core/resolve-config-value.tsresolves config values that are shell commands, env vars, or literals. -
packages/coding-agent/src/core/side-question.tsruns a side question on a cloned no-toolsAgentagainst a snapshot of the live conversation, without persisting it. -
packages/coding-agent/src/core/footer-data-provider.tsexposes the git branch and extension statuses for the TUI footer. -
packages/coding-agent/src/core/source-info.tsandpackages/coding-agent/src/core/resource-loader.tstrack where skills, prompts, themes, and extensions came from and load project context files.
-
web/serverconsumescreateAgentSession/createAgentSessionFromServices,AgentSession,AgentSessionEvent,SessionManager, andIpythonKernelProvisioner; see Web server. - The CLI (
packages/coding-agent/src/main.ts) usescreateAgentSessionServicespluscreateAgentSessionRuntimefor daemon-backed and in-process runs; see CLI and Daemon. - The daemon wires
AgentSessionRuntimeinto worker processes;AgentSessionRuntimeis the unit the daemon attaches clients to, and theAgentConnectionseam defines the client-visible session surface. - RLM subagents are sessions too:
createRlmSubagentRuntimeinpackages/coding-agent/src/core/agent-session-runtime.tscreates child runtimes whose transcripts live insub-*session dirs; see RLM runtime and Interactive mode. - User-facing session workflow is documented in Sessions and branching; terms like SessionView and compaction are in Glossary.
- Change turn admission or queueing:
packages/coding-agent/src/core/session-action-store.tsand the prompt methods inpackages/coding-agent/src/core/agent-session.ts. - Change persistence or the transcript format:
packages/coding-agent/src/core/session-manager.ts, then updatepackages/coding-agent/docs/session-format.mdandCURRENT_SESSION_VERSIONmigrations. - Change compaction policy:
packages/coding-agent/src/core/compaction/compaction.tsand the auto-compaction scheduling inpackages/coding-agent/src/core/agent-session.ts. - Change session replacement flows:
packages/coding-agent/src/core/agent-session-runtime.ts. - Change the session event surface:
AgentSessionEventinpackages/coding-agent/src/core/agent-session.ts; keepweb/server/src/event-mapper.tsin sync.
| File | Purpose |
|---|---|
packages/coding-agent/src/core/sdk.ts |
createAgentSession factory |
packages/coding-agent/src/core/agent-session.ts |
AgentSession, AgentSessionEvent, turn and tool hooks |
packages/coding-agent/src/core/agent-session-runtime.ts |
AgentSessionRuntime, session replacement, subagent runtimes |
packages/coding-agent/src/core/agent-session-services.ts |
Services creation and diagnostics |
packages/coding-agent/src/core/session-manager.ts |
SessionManager, entry types, JSONL I/O, buildSessionContext
|
packages/coding-agent/src/core/session-action-store.ts |
ActionStore and session action lifecycle |
packages/coding-agent/src/core/compaction/compaction.ts |
Compaction trigger, cut points, summarization |
packages/coding-agent/src/core/compaction/branch-summarization.ts |
Branch summary generation |
packages/coding-agent/src/core/event-bus.ts |
Channel-based event emitter |
packages/coding-agent/src/core/context-tree.ts |
Context usage trees |
packages/coding-agent/docs/session-format.md |
JSONL transcript format documentation |
- Coding agent - package overview and SDK entry points
- Agent tools - the tools the session runs
- Daemon - how sessions run in daemon workers
- Extensions - extension events and session hooks
- Skills - skills loaded into the session
- Refinement - the refine harness running between turns
- RLM runtime - recursive subagent sessions
-
Interactive mode - the client that renders
AgentSessionEvent