跳转到内容

Pi SDK v2 — abilities boundary and data model

Pi SDK v2 — abilities boundary and data model

Section titled “Pi SDK v2 — abilities boundary and data model”

Related: Cloud agent orchestrator · 2026-09-28 Pi SDK sessions worktrees and TS coordinator · 2026-09-28 Pi Agent SDK bash PATH and Nix flake · 2026-09-28 Worktree and PR by design orchestrators · 2026-09-28 Minimal orchestrator core Web UI plugin

Deepens (does not replace) the sessions/worktrees digest for the 0.84–0.87 surface. Skip Herdr.


LabelLayerMeaning for us
Coding-agent session file version: 3@earendil-works/pi-coding-agent SessionManagerCurrent on-disk JSONL contract (CURRENT_SESSION_VERSION = 3). v1 = linear; v2 = tree id/parentId; v3 = hookMessage → custom role. Auto-migrates on load.
AgentHarness v2 + SessionRepo v4@earendil-works/pi-agent-core (≥ 0.84.0)Low-level harness: lane-based Session / SessionStorage / SessionRepo (JsonlSessionRepo, InMemorySessionRepo). Promoted from experimental; legacy harness JSONL APIs removed. Not what createAgentSession persists today.
npm scopepackages@mariozechner/* → @earendil-works/* from 0.74.0 (2026-05). Pin Earendil scope.
ModelRuntimecoding-agent (≥ 0.80.8)Replaces SDK authStorage / old modelRegistry option — async model+credential facade.
pi-multiagents-v2 (community package)ExtensionCodex Multi-Agent V2 behavior via in-process AgentSessions — optional; not core.
@earendil-works/chordSibling packageFacets/services/replicated-state composition runtime — useful later for multi-process/UI; not required for worktree workers.

Pinned packages (npm, 2026-09-22): pi-coding-agent, pi-agent-core, chord all 0.87.1. Docs: SDK · Session format · Sessions · Changelog.

Orchestrator default: stay on coding-agent createAgentSession / SessionManager / AgentSessionRuntime. Only dive into agent-core AgentHarness if building a custom non-coding loop.


Abilities boundary — Pi vs orchestrator-core

Section titled “Abilities boundary — Pi vs orchestrator-core”

“Abilities” here = who owns which capability, not a Chord type.

AbilityPi ownsOrchestrator-core owns
LLM loop + toolsAgent via session.agent; built-ins read / bash / powershell / edit / write / grep / find / ls (ToolName); createCodingTools / createBashTool / …; tools / excludeTools / noTools / customTools / defaultToolsTool policy (allowlists), flake PATH via bash spawnHook, e2e in Nix — not a parallel tool runner
One conversationAgentSession: prompt / steer / followUp / abort / waitForIdle / subscribe / disposeRun lifecycle: create → settle → dispose; never leave orphaned sessions
cwd / workspaceTools + resource discovery bound to session cwdgit worktree add, unique branch, pin baseSha, pass cwd: worktreePath
Session persistenceAppend-only JSONL tree (SessionManager); optional inMemoryRun record in core event store: {runId, baseSha, branch, worktreePath, prUrl, sessionId, sessionFile, leafId?} — Pi JSONL is conversation artifact, not project DB
Context truthSessionManager.buildSessionContext / buildSessionProjection; system messages with sections + toolsAdded/toolsRemoved; context_edit; compactionDo not assign session.agent.state.messages to “fix” history (0.87: Manager is canonical). Mirror selected events into core SSE
Extensions / skillsResourceLoader / DefaultResourceLoader; extension events (turn_end, agent_before_settle, context_with_system, …)Choose which extensions load per worker; re-bindExtensions after every AgentSessionRuntime session replacement; never put product orchestration only in opaque extensions
Auth / modelsModelRuntime (+ settings / credentials store)Project-level model policy; worker env secrets; don’t share mutable auth files across hostile concurrent writers without care
Multi-agentCore: none (by design). Packages: pi-multiagents-v2, other subagent extensionsFleet: N workers = N sessions; coordinator is BYO MCP / core API — not Pi subagents
RPC / process isolationRpcClient (--mode rpc), print/JSON modes; CLI/RPC set AI_AGENT=pi + PI_CODING_AGENT=truePrefer in-process for same-machine workers; RpcClient for OS/crash isolation. Wire: LF-only JSONL (avoid Node readline); drain stdout; RPC message_update is delta-only (assemble until message_end)
Git / PRIndirectly via bash if instructedAlways worktree + push + PR gate (2026-09-28 Worktree and PR by design orchestrators)
Project memory / UISession name / labels / custom entries inside one JSONLDurable project files + core event log + panels (SSE)

Security note (Pi SECURITY.md): Pi’s trust boundary is the local user account — worktrees ≠ sandbox. OS isolation (container/VM) remains orchestrator/platform if required.


createAgentSession(opts) → { session: AgentSession, … }
AgentSession.sessionManager → SessionManager // persistence + tree
AgentSession.agent → Agent // agent-core loop
AgentSessionRuntime → newSession / switchSession / fork / importFromJsonl
(replaces active session; rebind subscriptions + extensions)
~/.pi/agent/sessions/<encoded-cwd>/<timestamp>_<session-id>.jsonl

Overrides: sessionDir / PI_CODING_AGENT_SESSION_DIR / CLI --session-dir. Header cwd groups sessions. Custom id via SDK / --session-id.

FieldRole
type: "session"Marker
versionPrefer 3
idSession UUID (also SessionManager.getSessionId())
timestampISO created
cwdWorkspace / worktree path
parentSession?Path to parent JSONL (fork / newSession({ parentSession }))

All (except header) have id, parentId, timestamp. Leaf = current append point (getLeafId()).

typeIn LLM context?Notes
messageYesAgentMessage (system / user / assistant / toolResult / …). System messages carry sections + toolsAdded/toolsRemoved
model_changeSettingsprovider + modelId
thinking_level_changeSettings
compactionSummary + checkpointfirstKeptEntryId, optional systemMessage, usage
branch_summarySummaryleft-branch capture on /tree navigate
context_editProjection onlytargetId + replacement (null = omit); raw history unchanged (0.87)
usageNo (totals yes)e.g. kind: "cache_warm"
customNoExtension state (customType)
custom_messageYesExtension-injected context
label / session_infoMetaBookmarks / display name

Core should key: sessionId, sessionFile path, optional leafId at settle, plus our runId / prUrl.

Subscribe before prompt. Completion = agent_settled (not merely agent_end — retries / queued work can follow).

Notable AgentSessionEvent types (0.87.1):

  • From agent-core stream: message/tool lifecycle (via AgentEvent, with agent_end reshaped to include willRetry)
  • agent_settled
  • queue_update (steering / followUp queues)
  • entry_appended (persist-aware)
  • compaction_start / compaction_end
  • auto_retry_*, summarization_retry_*
  • bash_execution_update (RPC/direct bash streaming)
  • session_info_changed, thinking_level_changed

RPC message_update (0.84+): deltas only — assemble until message_end.

When exposeSessionEnvironment is true: PI_SESSION_ID, PI_SESSION_FILE, PI_PROVIDER, PI_MODEL, PI_REASONING_LEVEL. CLI/RPC also set AI_AGENT=pi / PI_CODING_AGENT=true; SDK embed does not auto-set those markers.


Deltas vs our earlier Digests (0.84–0.87)

Section titled “Deltas vs our earlier Digests (0.84–0.87)”

Still true from 2026-09-28 Pi SDK sessions worktrees and TS coordinator: one session per worktree cwd; wait agent_settled; no built-in worktree/PR; mid-run second prompt needs steer/followUp.

New / sharpened for core:

  1. SessionManager is the only context authority — restore via manager entries / navigateTree / append + refreshContext; mutating agent.state.messages does not replace future provider history.
  2. context_edit — omit/replace model-visible content without rewriting JSONL history (good for redaction / orchestrator injects that must not fork files).
  3. Transcript-backed system + tool updates — survive resume/branch; cache-friendly dynamic tools (toolsAdded from tool results).
  4. Built-in ToolName set includes grep / find / ls (not only read/bash/edit/write).
  5. ModelRuntime required mindset — no authStorage on createAgentSession.
  6. Extension boundaries — actionable turn_end / agent_before_settle; deferred runs from agent_settled handlers until handlers finish.
  7. agent-core harness v2/v4 — ignore for default workers unless we deliberately embed AgentHarness instead of coding-agent.
  8. Chord — optional composition later; not on the worktree hot path.

Bash PATH / flake spawnHook unchanged: 2026-09-28 Pi Agent SDK bash PATH and Nix flake.


  1. One active run per AgentSession. Parallelism = multiple sessions (or processes). Shared agentDir → careful concurrent writers on settings/auth; prefer shared ModelRuntime + per-run sessionManager/cwd.
  2. After AgentSessionRuntime replace — old subscribe handles are dead; rebind to runtime.session and re-bindExtensions.
  3. In-process vs RPC streams — in-process message_update can carry cumulative message / partial; JSON/RPC (≈0.84+) emits deltas only until message_end. RpcClient.prompt success ≠ settled (disposition: "handled" may skip wait); use promptAndWait / waitForIdle / agent_settled.
  4. In-memory restore — SessionManager.inMemory(cwd?, options?, entries?) can rehydrate externally stored entries (0.85+); still keep our own run index.
  5. Exhaustive switches on SessionEntry / ExtensionEvent must handle context_edit and new boundary events (0.87).
  6. Multi-agent packages share one filesystem — disjoint write scopes or worktrees; tree not restored across process restart in pi-multiagents-v2.
  7. Security — Pi is not a sandbox; PR + CI remain the merge gate; optional container for untrusted code.
  8. Don’t treat community multiagent-v2 as product lock — coordinator stays outside Pi.

Keep the locked contract:

Task → worktree+branch → createAgentSession({ cwd, sessionManager, modelRuntime, bash spawnHook }) → prompt → agent_settled → core opens PR → dispose + GC

Store in core: run metadata + pointers into Pi’s JSONL (sessionId / path / leaf). Stream agent_settled, tool/compaction failures, and PR lifecycle on SSE. Leave AgentHarness/Chord for a later “custom harness” spike, not v0 workers.