@bastani/atomic 0.9.73 → 0.9.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +32 -0
- package/dist/builtin/workflows/README.md +2 -2
- package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
- package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +9 -9
- package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/tournament.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring.d.ts +2 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
- package/dist/builtin/workflows/src/index.js +393 -62
- package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
- package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
- package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-background-compaction.js +2 -1
- package/dist/core/agent-session-background-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +98 -4
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-detached-tools.d.ts +20 -5
- package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
- package/dist/core/agent-session-detached-tools.js +97 -21
- package/dist/core/agent-session-detached-tools.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +2 -1
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.js +12 -4
- package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +33 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/compaction/background-compaction.d.ts +11 -5
- package/dist/core/compaction/background-compaction.d.ts.map +1 -1
- package/dist/core/compaction/background-compaction.js +19 -10
- package/dist/core/compaction/background-compaction.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +10 -0
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.js +30 -2
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +7 -0
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +13 -5
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +1 -1
- package/dist/core/compaction/compaction-types.js +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/deleted-ranges.d.ts +17 -2
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
- package/dist/core/compaction/deleted-ranges.js +44 -5
- package/dist/core/compaction/deleted-ranges.js.map +1 -1
- package/dist/core/compaction/history-recall.d.ts +32 -0
- package/dist/core/compaction/history-recall.d.ts.map +1 -0
- package/dist/core/compaction/history-recall.js +275 -0
- package/dist/core/compaction/history-recall.js.map +1 -0
- package/dist/core/compaction/index.d.ts +2 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +2 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
- package/dist/core/compaction/pi-summary-fallback.js +1 -0
- package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
- package/dist/core/compaction/planner-outcome.d.ts +14 -0
- package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
- package/dist/core/compaction/planner-outcome.js +8 -0
- package/dist/core/compaction/planner-outcome.js.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
- package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.js +67 -24
- package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +7 -4
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +43 -19
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/refusal-recovery.d.ts +27 -0
- package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
- package/dist/core/compaction/refusal-recovery.js +65 -0
- package/dist/core/compaction/refusal-recovery.js.map +1 -0
- package/dist/core/compaction/region-trimming.d.ts +23 -0
- package/dist/core/compaction/region-trimming.d.ts.map +1 -1
- package/dist/core/compaction/region-trimming.js +59 -15
- package/dist/core/compaction/region-trimming.js.map +1 -1
- package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
- package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
- package/dist/core/compaction/structured-compaction-input.js +30 -17
- package/dist/core/compaction/structured-compaction-input.js.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts +9 -3
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js +18 -10
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/messages.d.ts +5 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +21 -3
- package/dist/core/messages.js.map +1 -1
- package/dist/core/session-manager-core.js +1 -1
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +1 -1
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +2 -5
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +3 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +4 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/storage/session/conformance.d.ts.map +1 -1
- package/dist/core/storage/session/conformance.js +12 -0
- package/dist/core/storage/session/conformance.js.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.js +3 -0
- package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
- package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/legacy-session-store.js +3 -0
- package/dist/core/storage/session/legacy-session-store.js.map +1 -1
- package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/memory-session-store.js +3 -0
- package/dist/core/storage/session/memory-session-store.js.map +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/sql-session-store.js +12 -3
- package/dist/core/storage/session/sql-session-store.js.map +1 -1
- package/dist/core/storage/session/types.d.ts +3 -0
- package/dist/core/storage/session/types.d.ts.map +1 -1
- package/dist/core/storage/session/types.js +3 -0
- package/dist/core/storage/session/types.js.map +1 -1
- package/dist/core/tools/history-protocol.d.ts +3 -0
- package/dist/core/tools/history-protocol.d.ts.map +1 -1
- package/dist/core/tools/history-protocol.js +7 -87
- package/dist/core/tools/history-protocol.js.map +1 -1
- package/dist/core/tools/history-transcript.d.ts +24 -0
- package/dist/core/tools/history-transcript.d.ts.map +1 -0
- package/dist/core/tools/history-transcript.js +110 -0
- package/dist/core/tools/history-transcript.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +21 -5
- package/dist/main-session.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +2 -2
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/session-id-target.d.ts +1 -0
- package/dist/session-id-target.d.ts.map +1 -1
- package/dist/session-id-target.js +3 -0
- package/dist/session-id-target.js.map +1 -1
- package/docs/compaction/reference.md +3 -2
- package/docs/compaction.md +35 -7
- package/docs/development.md +1 -1
- package/docs/sdk/reference.md +6 -5
- package/docs/sessions.md +3 -3
- package/docs/settings.md +3 -0
- package/docs/storage.md +2 -0
- package/docs/workflows/api-reference.md +15 -3
- package/docs/workflows/authoring.md +2 -2
- package/docs/workflows/operations.md +1 -0
- package/docs/workflows/reliable-design.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/schemas/settings.schema.json +5 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;CAGpC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAsDlD,4FAA4F;AAC5F,MAAM,UAAU,uBAAuB,CAAyB,OAAU;IACzE,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,MAAM,CAAC;QACZ,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY,CAAC;QAClB,KAAK,QAAQ;YACZ,OAAO,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,EAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;QAC/E;YACC,OAAO,OAAO,CAAC;IACjB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,gCAAgC,CAAC,KAAc;IAC9D,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,SAAS,GAAG,KAA2C,CAAC;IAC9D,IAAI,SAAS,CAAC,IAAI,KAAK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,CAAC;YACH,KAAK,MAAM,EAAE,CAAC;gBACb,IAAI,CAAC,wBAAwB,CAAC,CAAC,CAAC;oBAAE,OAAO,SAAS,CAAC;gBACnD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;oBAAE,OAAO,CAAC,CAAC;gBACxC,OAAO,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,2BAA2B,CAAC,CAAC,CAAC,OAAO,CAAC,EAAa,CAAC;YAC7E,CAAC;YACD,KAAK,QAAQ;gBACZ,OAAO,CAAC,CAAC;YACV,KAAK,WAAW,CAAC;YACjB,KAAK,YAAY;gBAChB,OAAO,CAAC,CAAC;YACV,SAAS,CAAC;gBACT,2FAA2F;gBAC3F,MAAM,gBAAgB,GAAU,CAAC,CAAC;gBAClC,KAAK,gBAAgB,CAAC;gBACtB,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { uniquifyToolCallIds } from \"./context-tool-pairing.js\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nexport const SUMMARY_COMPACTION_PREFIX = \"The following is a summary of the earlier conversation:\\n\\n\";\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n): CustomMessage {\n\tconst prefix =\n\t\ttypeof details === \"object\" && details !== null && \"backend\" in details && details.backend === \"summary\"\n\t\t\t? SUMMARY_COMPACTION_PREFIX\n\t\t\t: VERBATIM_COMPACTION_PREFIX;\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: prefix + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n\t/**\n\t * Calls that are running again (an interrupted question asked anew on resume): they are\n\t * pending, not interrupted, so no interrupted result is inserted for them.\n\t */\n\tinFlightToolCallIds?: ReadonlySet<string>;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id) || options.inFlightToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\nconst LEGACY_COMPACTION_SUMMARY_ROLE = \"compactionSummary\";\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tconst role: string = m.role;\n\t\t\tif (role === LEGACY_COMPACTION_SUMMARY_ROLE) return undefined;\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(uniquifyToolCallIds(converted));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;CAGpC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAsDlD,4FAA4F;AAC5F,MAAM,UAAU,uBAAuB,CAAyB,OAAU;IACzE,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,MAAM,CAAC;QACZ,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY,CAAC;QAClB,KAAK,QAAQ;YACZ,OAAO,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,EAAQ,CAAC,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,2BAA2B,CAAC,CAAC,CAAC,OAAO,CAAC,EAAa,CAAC;YAC7E,CAAC;YACD,KAAK,QAAQ;gBACZ,OAAO,CAAC,CAAC;YACV,KAAK,WAAW,CAAC;YACjB,KAAK,YAAY;gBAChB,OAAO,CAAC,CAAC;YACV,SAAS,CAAC;gBACT,2FAA2F;gBAC3F,MAAM,gBAAgB,GAAU,CAAC,CAAC;gBAClC,KAAK,gBAAgB,CAAC;gBACtB,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { uniquifyToolCallIds } from \"./context-tool-pairing.js\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nconst VERBATIM_RECALL_HINT_PATTERN =\n\t/^Removed lines remain in this session's history at history:\\/\\/sessions\\/\\S+\\. Use `search`[\\s\\S]*?\\n\\n/;\nexport const SUMMARY_COMPACTION_PREFIX = \"The following is a summary of the earlier conversation:\\n\\n\";\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function verbatimRecallHint(sessionId: string): string {\n\tconst url = `history://sessions/${sessionId}`;\n\tconst lines = [\n\t\t`Removed lines remain in this session's history at ${url}. Use \\`search\\` on that URL to find removed text, including text removed in this session's earlier compaction cycles, then \\`read\\` with \\`:N-M\\` to open it.`,\n\t\t\"You can also recall relevant findings from the project's other sessions (`search history://sessions`) and from workflow runs (`search history://workflows`, or `search history://` for both). Do this before redoing an investigation, or when a removed decision, error message, file path or result matters.\",\n\t\t\"A search over several records covers the newest ones by default; page on with `?offset=`.\",\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/** Drop the verbatim boundary prefix and, when present, the history recall hint that follows it. */\nexport function stripVerbatimCompactionPrefix(text: string): string {\n\tif (!text.startsWith(VERBATIM_COMPACTION_PREFIX)) return text;\n\treturn text.slice(VERBATIM_COMPACTION_PREFIX.length).replace(VERBATIM_RECALL_HINT_PATTERN, \"\");\n}\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n * When `sessionId` is given, a verbatim boundary also tells the agent where removed lines can be recalled.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n\tsessionId?: string,\n): CustomMessage {\n\tconst isSummary =\n\t\ttypeof details === \"object\" && details !== null && \"backend\" in details && details.backend === \"summary\";\n\tconst prefix = isSummary\n\t\t? SUMMARY_COMPACTION_PREFIX\n\t\t: VERBATIM_COMPACTION_PREFIX + (sessionId === undefined ? \"\" : verbatimRecallHint(sessionId));\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: prefix + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n\t/**\n\t * Calls that are running again (an interrupted question asked anew on resume): they are\n\t * pending, not interrupted, so no interrupted result is inserted for them.\n\t */\n\tinFlightToolCallIds?: ReadonlySet<string>;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id) || options.inFlightToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\nconst LEGACY_COMPACTION_SUMMARY_ROLE = \"compactionSummary\";\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tconst role: string = m.role;\n\t\t\tif (role === LEGACY_COMPACTION_SUMMARY_ROLE) return undefined;\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(uniquifyToolCallIds(converted));\n}\n"]}
|
|
@@ -550,7 +550,7 @@ export class SessionManager {
|
|
|
550
550
|
}
|
|
551
551
|
/** Build provenance-preserving, compaction-aware model context from the current leaf. */
|
|
552
552
|
buildSessionProjection() {
|
|
553
|
-
return buildSessionProjection(this.getEntries(), this.leafId, this.byId);
|
|
553
|
+
return buildSessionProjection(this.getEntries(), this.leafId, this.byId, this.sessionId);
|
|
554
554
|
}
|
|
555
555
|
/** Build the session context (what gets sent to the LLM). */
|
|
556
556
|
buildSessionContext() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager-core.js","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,0BAA0B,EAAE,4BAA4B,EAAE,MAAM,qCAAqC,CAAC;AAC/G,OAAO,EACN,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,EACtB,yBAAyB,EACzB,8BAA8B,EAC9B,2BAA2B,EAC3B,uBAAuB,EACvB,oBAAoB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACN,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,gBAAgB,EAChB,aAAa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D,OAAO,mBAAmB,KAAK,UAAU;oBACxC,CAAC,CAAC,mBAAmB;oBACrB,CAAC,CAAC,OAAO,gBAAgB,KAAK,UAAU;wBACvC,CAAC,CAAC,gBAAgB;wBAClB,CAAC,CAAC,SAAS,CACb,CAAC;YACH,CAAC;oBAAS,CAAC;gBACV,IAAI,CAAC,QAAQ;oBAAE,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;YACpC,CAAC;QACF,CAAC;QACD,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC,2BAA2B,CAAC,CAAC;QACtE,OAAO,eAAe,CACrB,mBAAmB,EACnB,OAAO,gBAAgB,KAAK,UAAU,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,EACrE,OAAO,KAAK,SAAS,IAAI,iBAAiB,IAAI,OAAO,IAAI,OAAO,CAAC,eAAe,KAAK,IAAI,EACzF,OAAO,IAAI,SAAS,IAAI,OAAO;YAC9B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAC7F,CAAC;IACH,CAAC;CACD","sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { getCurrentSystemMessage } from \"@bastani/pi-ai\";\nimport type { ImageContent, Message, TextContent, Usage } from \"@bastani/pi-ai/compat\";\nimport { getAgentDir } from \"../config.js\";\nimport { createSessionCwdMatcher, normalizePath, pathsEqual, resolvePath } from \"../utils/paths.ts\";\nimport type { VerbatimCompactionDetails } from \"./compaction/compaction-types.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport { createBranchedSessionState } from \"./session-manager-archive.ts\";\nimport { classifiedWorkflowMetadata, validSessionWorkflowMetadata } from \"./session-manager-classification.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateCompactionEntry,\n\tcreateContextEditEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateSessionSummaryEntry,\n\tcreateThinkingLevelChangeEntry,\n\tcreateWorktreeSnapshotEntry,\n\tgetEntriesWithoutHeader,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { SessionEntryError } from \"./session-manager-errors.js\";\nimport {\n\tbuildContextEntries,\n\tbuildSessionIndex,\n\tbuildSessionProjection,\n\tbuildSessionTree,\n\tgetBranchPath,\n} from \"./session-manager-history.ts\";\nimport { listProjectSessions } from \"./session-manager-list.ts\";\nimport { getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextEditEntry,\n\tFileEntry,\n\tModelFallbackRecord,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionNameState,\n\tSessionProjection,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n\tUsageEntry,\n\tWorktreeRestoreHostWarning,\n} from \"./session-manager-types.ts\";\nimport {\n\tassertValidSessionId,\n\tcreateSessionId,\n\tgenerateId,\n\tvalidateSessionFileEntries,\n} from \"./session-manager-validation.ts\";\nimport { listSessionStore } from \"./session-store-list.js\";\nimport {\n\tassertSessionBlobStore,\n\tcopySessionBlobs,\n\tsessionBlobHashes,\n\tstoreSessionBlobs,\n\tTOOL_OUTPUT_ENTRY_TYPE,\n\ttype ToolOutputReference,\n\ttakeInlineToolOutput,\n} from \"./session-tool-output.ts\";\nimport { adoptInlineSnapshotBlobs } from \"./session-worktree-snapshots.ts\";\nimport { SessionBlobError, type StorageFailureCause, StorageRollbackError } from \"./storage/errors.js\";\nimport {\n\tSessionFormatVersionError,\n\tSessionIdMismatchError,\n\ttype SessionJsonValue,\n\tSessionNotFoundError,\n\tStorageUnavailableError,\n} from \"./storage/session/errors.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport { MemorySessionStore, markPrivateMemorySessionStore } from \"./storage/session/memory-session-store.js\";\nimport type { SessionBlob, SessionRecordHeader, SessionSnapshot, SessionStore } from \"./storage/session/types.js\";\nimport { WorkspaceConfigError } from \"./worktree-snapshot/errors.ts\";\nimport type { WorktreeRootMapping, WorktreeSnapshot } from \"./worktree-snapshot/types.ts\";\n\nasync function resolveSessionStore(cwd: string): Promise<SessionStore> {\n\t// Selection loads settings and tools, which depend on the completed session module.\n\treturn (await import(\"./session-storage.js\")).resolveSessionStore(cwd);\n}\n\n/** An in-memory session tree whose mutations await the backing store. */\nexport class SessionManager {\n\tprivate sessionId = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate store: SessionStore;\n\tprivate lastSeq = 0;\n\tprivate mutation: Promise<void> = Promise.resolve();\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(store: SessionStore, cwd: string, sessionDir: string, options?: NewSessionOptions) {\n\t\tthis.store = store;\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.start(options);\n\t}\n\n\tprivate runMutation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.mutation.then(operation);\n\t\tthis.mutation = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate recordHeader(header = this.getHeader()!): SessionRecordHeader {\n\t\tconst { type: _type, ...record } = header;\n\t\treturn record;\n\t}\n\n\tprivate restore(snapshot: SessionSnapshot, location?: string): void {\n\t\tconst header = snapshot.header;\n\t\tthis.fileEntries = [{ type: \"session\", ...header }, ...snapshot.entries];\n\t\tthis.sessionId = header.id;\n\t\tthis.lastSeq = snapshot.lastSeq;\n\t\tthis.sessionFile =\n\t\t\tlocation ?? (this.store instanceof JsonlSessionStore ? this.store.locationFor(header) : undefined);\n\t\tthis._buildIndex();\n\t}\n\n\tprivate start(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) assertValidSessionId(options.id);\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tthis.fileEntries = [\n\t\t\tcreateSessionHeader(\n\t\t\t\tthis.sessionId,\n\t\t\t\tthis.cwd,\n\t\t\t\tnew Date().toISOString(),\n\t\t\t\toptions?.parentSession,\n\t\t\t\toptions?.internal,\n\t\t\t\toptions?.workflow,\n\t\t\t),\n\t\t];\n\t\tthis.lastSeq = 0;\n\t\tthis._buildIndex();\n\t\tthis.sessionFile =\n\t\t\tthis.store instanceof JsonlSessionStore\n\t\t\t\t? this.sessionDir\n\t\t\t\t\t? createSessionFilePath(this.sessionDir, this.getHeader()!.createdAt, this.sessionId)\n\t\t\t\t\t: this.store.locationFor(this.recordHeader())\n\t\t\t\t: undefined;\n\t\treturn this.sessionFile;\n\t}\n\n\tsetSessionFile(sessionFile: string): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst opened = await SessionManager.open(sessionFile, this.sessionDir, this.cwd);\n\t\t\tthis.store = opened.store;\n\t\t\tthis.restore(\n\t\t\t\t{ header: opened.recordHeader(), entries: opened.getEntries(), lastSeq: opened.lastSeq },\n\t\t\t\topened.sessionFile,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async initialize(): Promise<void> {\n\t\tthis.lastSeq = (\n\t\t\tawait (this.store instanceof JsonlSessionStore\n\t\t\t\t? this.store.create(this.recordHeader(), this.getEntries(), this.sessionFile)\n\t\t\t\t: this.store.create(this.recordHeader(), this.getEntries()))\n\t\t).lastSeq;\n\t}\n\n\tprivate async storeForNewSession(): Promise<SessionStore> {\n\t\tif (\n\t\t\tthis.store instanceof JsonlSessionStore &&\n\t\t\tthis.sessionDir &&\n\t\t\tthis.store.descriptor.location !== resolvePath(this.sessionDir)\n\t\t) {\n\t\t\treturn JsonlSessionStore.open(this.sessionDir, { exactDirectory: true, scanExisting: false });\n\t\t}\n\t\treturn this.store;\n\t}\n\n\tnewSession(options?: NewSessionOptions): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (options?.id !== undefined) assertValidSessionId(options.id);\n\t\t\tconst header = createSessionHeader(\n\t\t\t\toptions?.id ?? createSessionId(),\n\t\t\t\tthis.cwd,\n\t\t\t\tnew Date().toISOString(),\n\t\t\t\toptions?.parentSession,\n\t\t\t\toptions?.internal,\n\t\t\t\toptions?.workflow,\n\t\t\t);\n\t\t\tconst record = this.recordHeader(header);\n\t\t\tconst store = await this.storeForNewSession();\n\t\t\tconst location =\n\t\t\t\tstore instanceof JsonlSessionStore\n\t\t\t\t\t? this.sessionDir\n\t\t\t\t\t\t? createSessionFilePath(this.sessionDir, record.createdAt, record.id)\n\t\t\t\t\t\t: store.locationFor(record)\n\t\t\t\t\t: undefined;\n\t\t\tconst result = await (store instanceof JsonlSessionStore\n\t\t\t\t? store.create(record, [], location)\n\t\t\t\t: store.create(record, []));\n\t\t\tthis.store = store;\n\t\t\tthis.byId.clear();\n\t\t\tthis.labelsById.clear();\n\t\t\tthis.labelTimestampsById.clear();\n\t\t\tthis.restore({ header: record, entries: [], lastSeq: result.lastSeq }, location);\n\t\t\treturn this.sessionFile;\n\t\t});\n\t}\n\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst previous = this.getHeader()!;\n\t\t\tif (classifiedWorkflowMetadata(previous)) return;\n\t\t\tconst validWorkflow = validSessionWorkflowMetadata(workflow);\n\t\t\tif (!validWorkflow) return;\n\t\t\tconst header: SessionHeader = { ...previous, internal: true, workflow: validWorkflow };\n\t\t\tconst result = await this.store.replace(this.sessionId, this.recordHeader(header), this.getEntries(), {\n\t\t\t\texpectSeq: this.lastSeq,\n\t\t\t});\n\t\t\tthis.lastSeq = result.lastSeq;\n\t\t\tthis.fileEntries[0] = header;\n\t\t});\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tvalidateSessionFileEntries(this.fileEntries, this.sessionFile ?? \"in-memory session\");\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn !(this.store instanceof MemorySessionStore);\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn pathsEqual(this.sessionDir, getDefaultSessionDirPath(this.cwd));\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\tgetSessionStore(): SessionStore {\n\t\treturn this.store;\n\t}\n\n\tasync deleteSession(sessionId: string): Promise<void> {\n\t\tassertValidSessionId(sessionId);\n\t\tif (sessionId === this.sessionId) {\n\t\t\tthrow new Error(`Cannot delete the session that is currently open: ${sessionId}`);\n\t\t}\n\t\ttry {\n\t\t\tawait this.store.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError)) throw error;\n\t\t}\n\t}\n\n\t/** @internal Finalize provisional startup storage after project trust resolves. */\n\trebindStore(store: SessionStore, removeProvisionalRecord: boolean): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (store === this.store) return;\n\t\t\tconst header = this.recordHeader();\n\t\t\tconst entries = this.getEntries();\n\t\t\tconst hashes = sessionBlobHashes(this.store, entries);\n\t\t\tassertSessionBlobStore(store, this.sessionId, hashes.length);\n\t\t\tconst result = await store.create(header, entries);\n\t\t\tawait copySessionBlobs(this.store, this.sessionId, store, this.sessionId, hashes);\n\t\t\tif (removeProvisionalRecord) await this.store.delete(this.sessionId);\n\t\t\tthis.store = store;\n\t\t\tthis.sessionDir = store instanceof JsonlSessionStore ? store.descriptor.location : \"\";\n\t\t\tthis.restore({ header, entries, lastSeq: result.lastSeq });\n\t\t});\n\t}\n\n\tasync openSessionById(sessionId: string, cwdOverride?: string, sessionDirectory?: string): Promise<SessionManager> {\n\t\tlet store =\n\t\t\tsessionDirectory === undefined\n\t\t\t\t? this.store\n\t\t\t\t: await JsonlSessionStore.open(sessionDirectory, { exactDirectory: true, scanExisting: false });\n\t\tlet snapshot: SessionSnapshot;\n\t\ttry {\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\t!(error instanceof SessionNotFoundError) ||\n\t\t\t\tsessionDirectory !== undefined ||\n\t\t\t\t!this.usesDefaultSessionDir()\n\t\t\t)\n\t\t\t\tthrow error;\n\t\t\tstore = await JsonlSessionStore.open(join(getAgentDir(), \"sessions\"), { scanExisting: false });\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t}\n\t\tconst location = store instanceof JsonlSessionStore ? await store.findFile(sessionId) : undefined;\n\t\tif (location !== undefined) {\n\t\t\tstore = await JsonlSessionStore.open(dirname(location), { exactDirectory: true, scanExisting: false });\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t}\n\t\tif (snapshot.header.id !== sessionId) throw new SessionIdMismatchError(sessionId, snapshot.header.id);\n\t\tconst manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);\n\t\tmanager.restore(snapshot, location);\n\t\tif (location !== undefined) manager.sessionDir = dirname(location);\n\t\treturn manager;\n\t}\n\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<SessionManager> {\n\t\tconst source = await JsonlSessionStore.open(dirname(resolvePath(inputPath)), {\n\t\t\texactDirectory: true,\n\t\t\tscanExisting: false,\n\t\t});\n\t\ttry {\n\t\t\tconst loaded = await source.loadFile(inputPath);\n\t\t\tconst { entries, blobs } = takeInlineToolOutput(loaded.entries, loaded.header.id);\n\t\t\tassertSessionBlobStore(this.store, loaded.header.id, blobs.length);\n\t\t\tconst snapshot = {\n\t\t\t\t...loaded,\n\t\t\t\tentries: await adoptInlineSnapshotBlobs(entries, this.store.snapshotBlobs),\n\t\t\t};\n\t\t\tconst manager = new SessionManager(this.store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);\n\t\t\tmanager.restore(snapshot);\n\t\t\tawait manager.initialize();\n\t\t\tawait storeSessionBlobs(this.store, snapshot.header.id, blobs);\n\t\t\treturn manager;\n\t\t} finally {\n\t\t\tawait source.close();\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): Promise<void> {\n\t\treturn this._appendEntries([entry]);\n\t}\n\n\tprivate async _appendEntries(entries: readonly SessionEntry[]): Promise<void> {\n\t\tconst result = await this.store.append(this.sessionId, entries, { expectSeq: this.lastSeq });\n\t\tthis.lastSeq = result.lastSeq;\n\t\tfor (const entry of entries) {\n\t\t\tthis.fileEntries.push(entry);\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t}\n\t}\n\n\t/**\n\t * @internal Record the model and thinking level a new session starts on with one store write, as a model change\n\t * followed by a thinking level change.\n\t */\n\tappendStartState(\n\t\tmodel: { readonly provider: string; readonly modelId: string } | undefined,\n\t\tthinkingLevel: string,\n\t): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst modelEntry =\n\t\t\t\tmodel === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: createModelChangeEntry(model.provider, model.modelId, this.byId, this.leafId);\n\t\t\tconst thinkingEntry = createThinkingLevelChangeEntry(\n\t\t\t\tthinkingLevel,\n\t\t\t\t{ has: (id) => id === modelEntry?.id || this.byId.has(id) },\n\t\t\t\tmodelEntry?.id ?? this.leafId,\n\t\t\t);\n\t\t\tawait this._appendEntries(modelEntry === undefined ? [thinkingEntry] : [modelEntry, thinkingEntry]);\n\t\t});\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Record auxiliary model usage without adding it to the LLM context. */\n\tappendUsage(kind: string, provider: string, model: string, usage: Usage, note?: string): Promise<UsageEntry> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry: UsageEntry = {\n\t\t\t\ttype: \"usage\",\n\t\t\t\tid: generateId(this.byId),\n\t\t\t\tparentId: this.leafId,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tkind,\n\t\t\t\tprovider,\n\t\t\t\tmodel,\n\t\t\t\tusage,\n\t\t\t\t...(note === undefined ? {} : { note }),\n\t\t\t};\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry;\n\t\t});\n\t}\n\n\t/**\n\t * Append a model change as child of current leaf, then advance leaf. Returns entry id. `fallback` records why a model\n\t * fallback made the change.\n\t */\n\tappendModelChange(provider: string, modelId: string, fallback?: ModelFallbackRecord): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId, fallback);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\tappendCompaction(\n\t\tcompactedText: string,\n\t\tfirstKeptEntryId: string | null,\n\t\ttokensBefore: number,\n\t\tdetails: VerbatimCompactionDetails,\n\t\tusage?: Usage,\n\t\tcoveredThroughEntryId?: string,\n\t\tprecondition?: () => void,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tprecondition?.();\n\t\t\tif (firstKeptEntryId !== null && !this.byId.has(firstKeptEntryId))\n\t\t\t\tthrow new SessionEntryError(firstKeptEntryId, \"missing\");\n\t\t\tif (coveredThroughEntryId !== undefined && !this.byId.has(coveredThroughEntryId))\n\t\t\t\tthrow new SessionEntryError(coveredThroughEntryId, \"missing\");\n\t\t\tconst entry = createCompactionEntry(\n\t\t\t\tcompactedText,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t\tusage,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t\tcoveredThroughEntryId,\n\t\t\t);\n\t\t\tconst systemMessage = getCurrentSystemMessage(this.buildSessionProjection().messages);\n\t\t\tif (systemMessage) entry.systemMessage = { ...systemMessage, timestamp: new Date(entry.timestamp).getTime() };\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Save a JSONL backup; database-backed sessions have no file snapshot. */\n\twriteBackupSnapshot(label = \"compact\"): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!(this.store instanceof JsonlSessionStore) || !this.sessionFile) return undefined;\n\t\t\tconst path = `${this.sessionFile}.${new Date().toISOString().replace(/[:.]/g, \"-\")}.${label.replace(/[^a-z0-9_-]/gi, \"-\") || \"backup\"}.bak`;\n\t\t\ttry {\n\t\t\t\tawait writeFile(\n\t\t\t\t\tpath,\n\t\t\t\t\t`${[JSON.stringify({ type: \"session\", ...this.recordHeader() }), ...this.getEntries().map((entry) => JSON.stringify(entry))].join(\"\\n\")}\\n`,\n\t\t\t\t);\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new StorageUnavailableError(this.store.descriptor, cause as Error);\n\t\t\t}\n\t\t\treturn path;\n\t\t});\n\t}\n\n\t/** Append a branch-local edit to an earlier model-visible entry. */\n\tappendContextEdit(targetId: string, replacement: ContextEditEntry[\"replacement\"]): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (\n\t\t\t\treplacement !== null &&\n\t\t\t\t(typeof replacement !== \"object\" ||\n\t\t\t\t\t!(\"content\" in replacement) ||\n\t\t\t\t\t(typeof replacement.content !== \"string\" && !Array.isArray(replacement.content)))\n\t\t\t) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"invalid-replacement\");\n\t\t\t}\n\t\t\tconst target = this.byId.get(targetId);\n\t\t\tif (!target) throw new SessionEntryError(targetId, \"missing\");\n\t\t\tif (!this.getBranch().some((entry) => entry.id === targetId)) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"inactive\");\n\t\t\t}\n\t\t\tconst editable =\n\t\t\t\ttarget.type === \"custom_message\" ||\n\t\t\t\t(target.type === \"message\" &&\n\t\t\t\t\t(target.message.role === \"user\" ||\n\t\t\t\t\t\ttarget.message.role === \"assistant\" ||\n\t\t\t\t\t\ttarget.message.role === \"toolResult\"));\n\t\t\tif (!editable) throw new SessionEntryError(targetId, \"not-editable\");\n\t\t\tconst targetRole = target.type === \"message\" ? target.message.role : \"custom\";\n\t\t\tconst normalizedReplacement =\n\t\t\t\treplacement !== null &&\n\t\t\t\t(targetRole === \"assistant\" || targetRole === \"toolResult\") &&\n\t\t\t\ttypeof replacement.content === \"string\"\n\t\t\t\t\t? { content: [{ type: \"text\" as const, text: replacement.content }] }\n\t\t\t\t\t: replacement;\n\t\t\tconst entry = createContextEditEntry(targetId, normalizedReplacement, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry<T = SessionJsonValue>(customType: string, data?: T): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/**\n\t * @internal Stores `data` as a blob of the current session and appends the entry that references it, as one\n\t * mutation, so a session change cannot come between the two. The blob goes first: a process that stops in between\n\t * leaves only a blob of this session. Rejects with `blobs-unsupported` when the store holds no blobs.\n\t */\n\tappendToolOutputBlob(toolCallId: string, data: Uint8Array): Promise<SessionBlob> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst { putBlob } = this.store;\n\t\t\tif (putBlob === undefined) {\n\t\t\t\tthrow new SessionBlobError(\"blobs-unsupported\", {\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tadapter: this.store.descriptor.adapter,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst blob = await putBlob.call(this.store, this.sessionId, data);\n\t\t\tconst reference: ToolOutputReference = { toolCallId, hash: blob.hash, bytes: blob.bytes };\n\t\t\tawait this._appendEntry(createCustomEntry(TOOL_OUTPUT_ENTRY_TYPE, reference, this.byId, this.leafId));\n\t\t\treturn blob;\n\t\t});\n\t}\n\n\t/**\n\t * Record a checkout's snapshot at the current leaf. Pass the snapshot when it is new; omit it to refer to an earlier\n\t * entry's snapshot with the same id (an unchanged capture). `restore` records that the snapshot was restored on\n\t * this host into `root`, and `restoreWarnings` what that restore reported beyond its snapshot record.\n\t */\n\tappendWorktreeSnapshot(\n\t\troot: string,\n\t\tsnapshotId: string,\n\t\tsnapshot?: WorktreeSnapshot,\n\t\trestore?: WorktreeRootMapping,\n\t\trestoreWarnings: readonly WorktreeRestoreHostWarning[] = [],\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (snapshot !== undefined && snapshot.id !== snapshotId) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"snapshot\", \"a snapshot whose id is snapshotId\");\n\t\t\t}\n\t\t\tif (snapshot === undefined && !this.getWorktreeSnapshotRecords().has(snapshotId)) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"snapshotId\", \"the id of a snapshot recorded in this session\");\n\t\t\t}\n\t\t\tif (restore !== undefined && (restore.to !== root || restore.snapshotId !== snapshotId)) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"restore\", \"a mapping to root for snapshotId\");\n\t\t\t}\n\t\t\tif (restore === undefined && restoreWarnings.length > 0) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"restoreWarnings\", \"warnings recorded together with their restore\");\n\t\t\t}\n\t\t\tconst entry = createWorktreeSnapshotEntry(\n\t\t\t\troot,\n\t\t\t\tsnapshotId,\n\t\t\t\tsnapshot,\n\t\t\t\trestore,\n\t\t\t\trestoreWarnings,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Restores recorded on the active branch, oldest first: work recorded under `from` continues under `to`. */\n\tgetWorktreeRootMappings(): WorktreeRootMapping[] {\n\t\treturn this.getBranch().flatMap((entry) =>\n\t\t\tentry.type === \"worktree_snapshot\" && entry.restore ? [entry.restore] : [],\n\t\t);\n\t}\n\n\t/** Every snapshot record in the session, by id. */\n\tgetWorktreeSnapshotRecords(): Map<string, WorktreeSnapshot> {\n\t\tconst records = new Map<string, WorktreeSnapshot>();\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"worktree_snapshot\" && entry.snapshot) records.set(entry.snapshotId, entry.snapshot);\n\t\t}\n\t\treturn records;\n\t}\n\n\t/** The latest snapshot of each checkout root on the active branch, keyed by the root it was last recorded under. */\n\tgetLatestWorktreeSnapshots(): Map<string, WorktreeSnapshot> {\n\t\tconst records = this.getWorktreeSnapshotRecords();\n\t\tconst latest = new Map<string, WorktreeSnapshot>();\n\t\tfor (const entry of this.getBranch()) {\n\t\t\tif (entry.type !== \"worktree_snapshot\") continue;\n\t\t\tconst snapshot = records.get(entry.snapshotId);\n\t\t\tif (snapshot) latest.set(entry.root, snapshot);\n\t\t}\n\t\treturn latest;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a generated resume summary anchored to the message it describes. Returns entry id. */\n\tappendSessionSummary(summary: string, summarizedThroughId: string, usage?: Usage): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(summarizedThroughId)) throw new SessionEntryError(summarizedThroughId, \"missing\");\n\t\t\tconst entry = createSessionSummaryEntry(summary, summarizedThroughId, usage, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn this.getSessionNameState().name;\n\t}\n\n\t/**\n\t * Get the session name state. `hasName` is true for a session that was named and\n\t * then cleared even though `name` is undefined; a never-named session reports\n\t * `hasName: false`. Read-side only: the JSONL already records the distinction.\n\t */\n\tgetSessionNameState(): SessionNameState {\n\t\treturn getLatestSessionName(this.fileEntries);\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = SessionJsonValue>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t\tprotectedReconciliation?: { delivery: \"steer\" | \"followUp\" },\n\t\tstageAdmissionKey?: string,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createCustomMessageEntry(\n\t\t\t\tcustomType,\n\t\t\t\tcontent,\n\t\t\t\tdisplay,\n\t\t\t\tdetails,\n\t\t\t\texcludeFromContext,\n\t\t\t\tprotectedReconciliation,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t\tstageAdmissionKey,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(targetId)) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"missing\");\n\t\t\t}\n\t\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\tif (label) {\n\t\t\t\tthis.labelsById.set(targetId, label);\n\t\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tthis.labelsById.delete(targetId);\n\t\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t\t}\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Return the active branch entries after applying the latest compaction boundary. */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Build provenance-preserving, compaction-aware model context from the current leaf. */\n\tbuildSessionProjection(): SessionProjection {\n\t\treturn buildSessionProjection(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\tconst { messages, thinkingLevel, model } = this.buildSessionProjection();\n\t\treturn { messages, thinkingLevel, model };\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Number of entries without copying the session history. */\n\tgetEntryCount(): number {\n\t\treturn this.byId.size;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(branchFromId)) {\n\t\t\t\tthrow new SessionEntryError(branchFromId, \"missing\");\n\t\t\t}\n\t\t\tthis.leafId = branchFromId;\n\t\t});\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tthis.leafId = null;\n\t\t});\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary<T = SessionJsonValue>(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: import(\"@bastani/pi-ai/compat\").Usage,\n\t\tfromId?: string,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\t\tthrow new SessionEntryError(branchFromId, \"missing\");\n\t\t\t}\n\t\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(\n\t\t\t\tbranchFromId,\n\t\t\t\tfromId ?? this.leafId ?? \"root\",\n\t\t\t\tsummary,\n\t\t\t\tdetails,\n\t\t\t\tusage,\n\t\t\t\tfromHook,\n\t\t\t\tthis.byId,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\tcreateBranchedSession(leafId: string): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst result = createBranchedSessionState({\n\t\t\t\tleafId,\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tparentSessionId: this.sessionId,\n\t\t\t\tworkflow: classifiedWorkflowMetadata(this.getHeader()),\n\t\t\t\tpath: this.getBranch(leafId),\n\t\t\t\tlabelsById: this.labelsById,\n\t\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t\t});\n\t\t\tconst header = result.fileEntries[0] as SessionHeader;\n\t\t\tconst entries = getEntriesWithoutHeader(result.fileEntries);\n\t\t\tconst record = this.recordHeader(header);\n\t\t\tconst hashes = sessionBlobHashes(this.store, entries);\n\t\t\tconst store = await this.storeForNewSession();\n\t\t\tconst location =\n\t\t\t\tstore instanceof JsonlSessionStore\n\t\t\t\t\t? this.sessionDir\n\t\t\t\t\t\t? createSessionFilePath(this.sessionDir, record.createdAt, record.id)\n\t\t\t\t\t\t: store.locationFor(record)\n\t\t\t\t\t: undefined;\n\t\t\tconst lastSeq = (\n\t\t\t\tawait (store instanceof JsonlSessionStore\n\t\t\t\t\t? store.create(record, entries, location)\n\t\t\t\t\t: store.create(record, entries))\n\t\t\t).lastSeq;\n\t\t\tawait copySessionBlobs(this.store, this.sessionId, store, record.id, hashes);\n\t\t\tthis.store = store;\n\t\t\tthis.fileEntries = result.fileEntries;\n\t\t\tthis.sessionId = header.id;\n\t\t\tthis.lastSeq = lastSeq;\n\t\t\tthis.sessionFile = location;\n\t\t\tthis._buildIndex();\n\t\t\treturn this.sessionFile;\n\t\t});\n\t}\n\n\tasync forkTo(cwd: string, sessionDir?: string | SessionStore, options?: NewSessionOptions): Promise<SessionManager> {\n\t\tconst store =\n\t\t\ttypeof sessionDir === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: (sessionDir ?? (await resolveSessionStore(cwd)));\n\t\tconst directory = store instanceof JsonlSessionStore ? store.descriptor.location : \"\";\n\t\treturn SessionManager.constructWithStore(store, store !== sessionDir, async () => {\n\t\t\tconst source = { store: this.store, sessionId: this.sessionId, entries: this.getEntries() };\n\t\t\tconst manager = new SessionManager(store, cwd, directory, { ...options, parentSession: source.sessionId });\n\t\t\tconst hashes = sessionBlobHashes(source.store, source.entries);\n\t\t\tassertSessionBlobStore(store, manager.sessionId, hashes.length);\n\t\t\tmanager.fileEntries.push(...source.entries);\n\t\t\tawait manager.initialize();\n\t\t\tawait copySessionBlobs(source.store, source.sessionId, store, manager.sessionId, hashes);\n\t\t\tmanager._buildIndex();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async importFromJsonl(\n\t\tinputPath: string,\n\t\tcwd: string,\n\t\tsessionDir?: string | SessionStore,\n\t): Promise<SessionManager> {\n\t\tconst store =\n\t\t\ttypeof sessionDir === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: (sessionDir ?? (await resolveSessionStore(cwd)));\n\t\treturn SessionManager.constructWithStore(store, store !== sessionDir, () =>\n\t\t\tnew SessionManager(\n\t\t\t\tstore,\n\t\t\t\tcwd,\n\t\t\t\tstore instanceof JsonlSessionStore ? store.descriptor.location : \"\",\n\t\t\t).importFromJsonl(inputPath),\n\t\t);\n\t}\n\tprivate static async constructWithStore(\n\t\tstore: SessionStore,\n\t\towned: boolean,\n\t\tconstruct: () => Promise<SessionManager>,\n\t): Promise<SessionManager> {\n\t\ttry {\n\t\t\treturn await construct();\n\t\t} catch (error) {\n\t\t\tif (owned) {\n\t\t\t\ttry {\n\t\t\t\t\tawait store.close();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new StorageRollbackError(error as StorageFailureCause, cause as StorageFailureCause);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tstatic async create(cwd: string, sessionDir?: string, options?: NewSessionOptions): Promise<SessionManager>;\n\tstatic async create(store: SessionStore, cwd: string, options?: NewSessionOptions): Promise<SessionManager>;\n\tstatic async create(\n\t\tcwdOrStore: string | SessionStore,\n\t\tdirectoryOrCwd?: string,\n\t\toptions?: NewSessionOptions,\n\t): Promise<SessionManager> {\n\t\tconst cwd = typeof cwdOrStore === \"string\" ? cwdOrStore : (directoryOrCwd ?? process.cwd());\n\t\tif (typeof cwdOrStore === \"string\" && directoryOrCwd === undefined) {\n\t\t\tconst store = await resolveSessionStore(cwd);\n\t\t\treturn SessionManager.constructWithStore(store, true, () => SessionManager.create(store, cwd, options));\n\t\t}\n\t\tconst directory =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? directoryOrCwd\n\t\t\t\t\t? normalizePath(directoryOrCwd)\n\t\t\t\t\t: getDefaultSessionDirPath(cwd)\n\t\t\t\t: cwdOrStore instanceof JsonlSessionStore\n\t\t\t\t\t? cwdOrStore.descriptor.location\n\t\t\t\t\t: \"\";\n\t\tconst store =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: cwdOrStore;\n\t\treturn SessionManager.constructWithStore(store, store !== cwdOrStore, async () => {\n\t\t\tconst manager = new SessionManager(store, cwd, directory, options);\n\t\t\tif (typeof cwdOrStore !== \"string\" && store instanceof JsonlSessionStore) {\n\t\t\t\tmanager.sessionFile = store.locationFor(manager.recordHeader());\n\t\t\t\tmanager.sessionDir = dirname(manager.sessionFile);\n\t\t\t}\n\t\t\tawait manager.initialize();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async open(path: string, sessionDir?: string, cwdOverride?: string): Promise<SessionManager>;\n\tstatic async open(store: SessionStore, sessionId: string, cwdOverride?: string): Promise<SessionManager>;\n\tstatic async open(\n\t\tpathOrStore: string | SessionStore,\n\t\tdirectoryOrId?: string,\n\t\tcwdOverride?: string,\n\t): Promise<SessionManager> {\n\t\tif (typeof pathOrStore !== \"string\") {\n\t\t\tconst snapshot = await pathOrStore.load(directoryOrId!);\n\t\t\tif (snapshot.header.id !== directoryOrId) throw new SessionIdMismatchError(directoryOrId!, snapshot.header.id);\n\t\t\tconst manager = new SessionManager(\n\t\t\t\tpathOrStore,\n\t\t\t\tcwdOverride ?? snapshot.header.cwd,\n\t\t\t\tpathOrStore instanceof JsonlSessionStore ? pathOrStore.descriptor.location : \"\",\n\t\t\t);\n\t\t\tmanager.restore(\n\t\t\t\tsnapshot,\n\t\t\t\tpathOrStore instanceof JsonlSessionStore ? await pathOrStore.findFile(directoryOrId!) : undefined,\n\t\t\t);\n\t\t\tif (manager.sessionFile) manager.sessionDir = dirname(manager.sessionFile);\n\t\t\treturn manager;\n\t\t}\n\t\tconst path = resolvePath(pathOrStore);\n\t\tconst directory = directoryOrId ?? dirname(path);\n\t\tconst store = await JsonlSessionStore.open(dirname(path), { exactDirectory: true, scanExisting: false });\n\t\tlet snapshot: SessionSnapshot;\n\t\ttry {\n\t\t\tsnapshot = await store.loadFile(path);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof StorageUnavailableError) || (error.cause as NodeJS.ErrnoException).code !== \"ENOENT\")\n\t\t\t\tthrow error;\n\t\t\tconst manager = new SessionManager(store, cwdOverride ?? process.cwd(), directory);\n\t\t\tmanager.lastSeq = (await store.create(manager.recordHeader(), [], path)).lastSeq;\n\t\t\tmanager.sessionFile = path;\n\t\t\treturn manager;\n\t\t}\n\t\tconst manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, directory);\n\t\tmanager.restore(snapshot, path);\n\t\treturn manager;\n\t}\n\n\tstatic async continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager>;\n\tstatic async continueRecent(\n\t\tstore: SessionStore,\n\t\tcwd: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager>;\n\tstatic async continueRecent(\n\t\tcwdOrStore: string | SessionStore,\n\t\tdirectoryOrCwd?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager> {\n\t\tconst cwd = typeof cwdOrStore === \"string\" ? cwdOrStore : directoryOrCwd!;\n\t\tif (typeof cwdOrStore === \"string\" && directoryOrCwd === undefined) {\n\t\t\tconst store = await resolveSessionStore(cwd);\n\t\t\treturn SessionManager.constructWithStore(store, true, () =>\n\t\t\t\tSessionManager.continueRecent(store, cwd, options),\n\t\t\t);\n\t\t}\n\t\tconst directory = typeof cwdOrStore === \"string\" ? (directoryOrCwd ?? getDefaultSessionDirPath(cwd)) : \"\";\n\t\tconst store =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: cwdOrStore;\n\t\treturn SessionManager.constructWithStore(store, store !== cwdOrStore, async () => {\n\t\t\tconst recent = await store.findMostRecent({\n\t\t\t\tcwd: resolvePath(cwd),\n\t\t\t\tincludeInternal: options?.includeInternal,\n\t\t\t});\n\t\t\tconst manager = new SessionManager(store, cwd, directory);\n\t\t\tif (recent) manager.restore(await store.load(recent.id), recent.location);\n\t\t\telse await manager.initialize();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions, entries?: FileEntry[]): SessionManager {\n\t\tconst manager = new SessionManager(\n\t\t\tmarkPrivateMemorySessionStore(new MemorySessionStore(createSessionCwdMatcher)),\n\t\t\tcwd,\n\t\t\t\"\",\n\t\t\toptions,\n\t\t);\n\t\tif (entries?.length) {\n\t\t\tmanager.fileEntries = entries[0].type === \"session\" ? entries : [...manager.fileEntries, ...entries];\n\t\t\tmanager.sessionId = manager.getHeader()!.id;\n\t\t\tmanager._buildIndex();\n\t\t}\n\t\tmanager.mutation = manager.initialize();\n\t\treturn manager;\n\t}\n\n\tstatic async forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): Promise<SessionManager> {\n\t\tconst sourceStore = await JsonlSessionStore.open(dirname(resolvePath(sourcePath)), {\n\t\t\texactDirectory: true,\n\t\t\tscanExisting: false,\n\t\t});\n\t\tlet source: SessionSnapshot;\n\t\ttry {\n\t\t\tsource = await sourceStore.loadFile(resolvePath(sourcePath));\n\t\t} finally {\n\t\t\tawait sourceStore.close();\n\t\t}\n\t\tconst { entries, blobs } = takeInlineToolOutput(source.entries, source.header.id);\n\t\tconst store =\n\t\t\tsessionDir === undefined\n\t\t\t\t? await resolveSessionStore(targetCwd)\n\t\t\t\t: await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false });\n\t\treturn SessionManager.constructWithStore(store, true, async () => {\n\t\t\tconst manager = new SessionManager(store, targetCwd, sessionDir ?? \"\", {\n\t\t\t\t...options,\n\t\t\t\tparentSession: source.header.id,\n\t\t\t});\n\t\t\tassertSessionBlobStore(store, manager.sessionId, blobs.length);\n\t\t\tmanager.fileEntries.push(...entries);\n\t\t\tawait manager.initialize();\n\t\t\tawait storeSessionBlobs(store, manager.sessionId, blobs);\n\t\t\tmanager._buildIndex();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async findById(cwd: string, id: string, sessionDir?: string): Promise<string | undefined> {\n\t\tconst store =\n\t\t\tsessionDir === undefined\n\t\t\t\t? await resolveSessionStore(cwd)\n\t\t\t\t: await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false });\n\t\ttry {\n\t\t\tconst header = await store.readHeader(id);\n\t\t\tif (\n\t\t\t\t!header ||\n\t\t\t\tclassifiedWorkflowMetadata(header) ||\n\t\t\t\t!createSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\treturn store instanceof JsonlSessionStore ? await store.findFile(id) : id;\n\t\t} catch (error) {\n\t\t\tif (error instanceof SessionFormatVersionError) return undefined;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t}\n\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string | SessionStore,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tconst signal = options && \"aborted\" in options ? options : options?.signal;\n\t\tif (typeof sessionDir !== \"string\") {\n\t\t\tconst store = sessionDir ?? (await resolveSessionStore(cwd));\n\t\t\ttry {\n\t\t\t\treturn await listSessionStore(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd: resolvePath(cwd),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tincludeInternal:\n\t\t\t\t\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\t\t\t},\n\t\t\t\t\tonProgress,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tif (sessionDir === undefined) await store.close();\n\t\t\t}\n\t\t}\n\t\treturn listProjectSessions(\n\t\t\tcwd,\n\t\t\tsessionDir,\n\t\t\tonProgress,\n\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tstatic async listAll(onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string | SessionStore,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tdirectoryOrProgress?: string | SessionStore | SessionListProgress,\n\t\tprogressOrSignal?: SessionListProgress | AbortSignal,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tif (typeof directoryOrProgress !== \"string\") {\n\t\t\tconst supplied = typeof directoryOrProgress === \"object\" ? directoryOrProgress : undefined;\n\t\t\tconst store = supplied ?? (await resolveSessionStore(process.cwd()));\n\t\t\ttry {\n\t\t\t\treturn await listSessionStore(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tincludeInternal:\n\t\t\t\t\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\t\t\t\tsignal:\n\t\t\t\t\t\t\toptions && \"aborted\" in options\n\t\t\t\t\t\t\t\t? options\n\t\t\t\t\t\t\t\t: (options?.signal ?? (typeof progressOrSignal === \"object\" ? progressOrSignal : undefined)),\n\t\t\t\t\t},\n\t\t\t\t\ttypeof directoryOrProgress === \"function\"\n\t\t\t\t\t\t? directoryOrProgress\n\t\t\t\t\t\t: typeof progressOrSignal === \"function\"\n\t\t\t\t\t\t\t? progressOrSignal\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tif (!supplied) await store.close();\n\t\t\t}\n\t\t}\n\t\tconst { listAllSessions } = await import(\"./session-manager-list.ts\");\n\t\treturn listAllSessions(\n\t\t\tdirectoryOrProgress,\n\t\t\ttypeof progressOrSignal === \"function\" ? progressOrSignal : undefined,\n\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\toptions && \"aborted\" in options\n\t\t\t\t? options\n\t\t\t\t: (options?.signal ?? (typeof progressOrSignal === \"object\" ? progressOrSignal : undefined)),\n\t\t);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-manager-core.js","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,0BAA0B,EAAE,4BAA4B,EAAE,MAAM,qCAAqC,CAAC;AAC/G,OAAO,EACN,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,EACtB,yBAAyB,EACzB,8BAA8B,EAC9B,2BAA2B,EAC3B,uBAAuB,EACvB,oBAAoB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACN,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,gBAAgB,EAChB,aAAa,GACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAmBtE,OAAO,EACN,oBAAoB,EACpB,eAAe,EACf,UAAU,EACV,0BAA0B,GAC1B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EACN,sBAAsB,EACtB,gBAAgB,EAChB,i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Ae,EAAE,GAAG,MAAM,MAAM,CAAC,2BAA2B,CAAC,CAAC;QACtE,OAAO,eAAe,CACrB,mBAAmB,EACnB,OAAO,gBAAgB,KAAK,UAAU,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,EACrE,OAAO,KAAK,SAAS,IAAI,iBAAiB,IAAI,OAAO,IAAI,OAAO,CAAC,eAAe,KAAK,IAAI,EACzF,OAAO,IAAI,SAAS,IAAI,OAAO;YAC9B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAC7F,CAAC;IACH,CAAC;CACD","sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { getCurrentSystemMessage } from \"@bastani/pi-ai\";\nimport type { ImageContent, Message, TextContent, Usage } from \"@bastani/pi-ai/compat\";\nimport { getAgentDir } from \"../config.js\";\nimport { createSessionCwdMatcher, normalizePath, pathsEqual, resolvePath } from \"../utils/paths.ts\";\nimport type { VerbatimCompactionDetails } from \"./compaction/compaction-types.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport { createBranchedSessionState } from \"./session-manager-archive.ts\";\nimport { classifiedWorkflowMetadata, validSessionWorkflowMetadata } from \"./session-manager-classification.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateCompactionEntry,\n\tcreateContextEditEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateSessionSummaryEntry,\n\tcreateThinkingLevelChangeEntry,\n\tcreateWorktreeSnapshotEntry,\n\tgetEntriesWithoutHeader,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { SessionEntryError } from \"./session-manager-errors.js\";\nimport {\n\tbuildContextEntries,\n\tbuildSessionIndex,\n\tbuildSessionProjection,\n\tbuildSessionTree,\n\tgetBranchPath,\n} from \"./session-manager-history.ts\";\nimport { listProjectSessions } from \"./session-manager-list.ts\";\nimport { getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextEditEntry,\n\tFileEntry,\n\tModelFallbackRecord,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionNameState,\n\tSessionProjection,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n\tUsageEntry,\n\tWorktreeRestoreHostWarning,\n} from \"./session-manager-types.ts\";\nimport {\n\tassertValidSessionId,\n\tcreateSessionId,\n\tgenerateId,\n\tvalidateSessionFileEntries,\n} from \"./session-manager-validation.ts\";\nimport { listSessionStore } from \"./session-store-list.js\";\nimport {\n\tassertSessionBlobStore,\n\tcopySessionBlobs,\n\tsessionBlobHashes,\n\tstoreSessionBlobs,\n\tTOOL_OUTPUT_ENTRY_TYPE,\n\ttype ToolOutputReference,\n\ttakeInlineToolOutput,\n} from \"./session-tool-output.ts\";\nimport { adoptInlineSnapshotBlobs } from \"./session-worktree-snapshots.ts\";\nimport { SessionBlobError, type StorageFailureCause, StorageRollbackError } from \"./storage/errors.js\";\nimport {\n\tSessionFormatVersionError,\n\tSessionIdMismatchError,\n\ttype SessionJsonValue,\n\tSessionNotFoundError,\n\tStorageUnavailableError,\n} from \"./storage/session/errors.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport { MemorySessionStore, markPrivateMemorySessionStore } from \"./storage/session/memory-session-store.js\";\nimport type { SessionBlob, SessionRecordHeader, SessionSnapshot, SessionStore } from \"./storage/session/types.js\";\nimport { WorkspaceConfigError } from \"./worktree-snapshot/errors.ts\";\nimport type { WorktreeRootMapping, WorktreeSnapshot } from \"./worktree-snapshot/types.ts\";\n\nasync function resolveSessionStore(cwd: string): Promise<SessionStore> {\n\t// Selection loads settings and tools, which depend on the completed session module.\n\treturn (await import(\"./session-storage.js\")).resolveSessionStore(cwd);\n}\n\n/** An in-memory session tree whose mutations await the backing store. */\nexport class SessionManager {\n\tprivate sessionId = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate store: SessionStore;\n\tprivate lastSeq = 0;\n\tprivate mutation: Promise<void> = Promise.resolve();\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(store: SessionStore, cwd: string, sessionDir: string, options?: NewSessionOptions) {\n\t\tthis.store = store;\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.start(options);\n\t}\n\n\tprivate runMutation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.mutation.then(operation);\n\t\tthis.mutation = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\tprivate recordHeader(header = this.getHeader()!): SessionRecordHeader {\n\t\tconst { type: _type, ...record } = header;\n\t\treturn record;\n\t}\n\n\tprivate restore(snapshot: SessionSnapshot, location?: string): void {\n\t\tconst header = snapshot.header;\n\t\tthis.fileEntries = [{ type: \"session\", ...header }, ...snapshot.entries];\n\t\tthis.sessionId = header.id;\n\t\tthis.lastSeq = snapshot.lastSeq;\n\t\tthis.sessionFile =\n\t\t\tlocation ?? (this.store instanceof JsonlSessionStore ? this.store.locationFor(header) : undefined);\n\t\tthis._buildIndex();\n\t}\n\n\tprivate start(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) assertValidSessionId(options.id);\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tthis.fileEntries = [\n\t\t\tcreateSessionHeader(\n\t\t\t\tthis.sessionId,\n\t\t\t\tthis.cwd,\n\t\t\t\tnew Date().toISOString(),\n\t\t\t\toptions?.parentSession,\n\t\t\t\toptions?.internal,\n\t\t\t\toptions?.workflow,\n\t\t\t),\n\t\t];\n\t\tthis.lastSeq = 0;\n\t\tthis._buildIndex();\n\t\tthis.sessionFile =\n\t\t\tthis.store instanceof JsonlSessionStore\n\t\t\t\t? this.sessionDir\n\t\t\t\t\t? createSessionFilePath(this.sessionDir, this.getHeader()!.createdAt, this.sessionId)\n\t\t\t\t\t: this.store.locationFor(this.recordHeader())\n\t\t\t\t: undefined;\n\t\treturn this.sessionFile;\n\t}\n\n\tsetSessionFile(sessionFile: string): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst opened = await SessionManager.open(sessionFile, this.sessionDir, this.cwd);\n\t\t\tthis.store = opened.store;\n\t\t\tthis.restore(\n\t\t\t\t{ header: opened.recordHeader(), entries: opened.getEntries(), lastSeq: opened.lastSeq },\n\t\t\t\topened.sessionFile,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async initialize(): Promise<void> {\n\t\tthis.lastSeq = (\n\t\t\tawait (this.store instanceof JsonlSessionStore\n\t\t\t\t? this.store.create(this.recordHeader(), this.getEntries(), this.sessionFile)\n\t\t\t\t: this.store.create(this.recordHeader(), this.getEntries()))\n\t\t).lastSeq;\n\t}\n\n\tprivate async storeForNewSession(): Promise<SessionStore> {\n\t\tif (\n\t\t\tthis.store instanceof JsonlSessionStore &&\n\t\t\tthis.sessionDir &&\n\t\t\tthis.store.descriptor.location !== resolvePath(this.sessionDir)\n\t\t) {\n\t\t\treturn JsonlSessionStore.open(this.sessionDir, { exactDirectory: true, scanExisting: false });\n\t\t}\n\t\treturn this.store;\n\t}\n\n\tnewSession(options?: NewSessionOptions): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (options?.id !== undefined) assertValidSessionId(options.id);\n\t\t\tconst header = createSessionHeader(\n\t\t\t\toptions?.id ?? createSessionId(),\n\t\t\t\tthis.cwd,\n\t\t\t\tnew Date().toISOString(),\n\t\t\t\toptions?.parentSession,\n\t\t\t\toptions?.internal,\n\t\t\t\toptions?.workflow,\n\t\t\t);\n\t\t\tconst record = this.recordHeader(header);\n\t\t\tconst store = await this.storeForNewSession();\n\t\t\tconst location =\n\t\t\t\tstore instanceof JsonlSessionStore\n\t\t\t\t\t? this.sessionDir\n\t\t\t\t\t\t? createSessionFilePath(this.sessionDir, record.createdAt, record.id)\n\t\t\t\t\t\t: store.locationFor(record)\n\t\t\t\t\t: undefined;\n\t\t\tconst result = await (store instanceof JsonlSessionStore\n\t\t\t\t? store.create(record, [], location)\n\t\t\t\t: store.create(record, []));\n\t\t\tthis.store = store;\n\t\t\tthis.byId.clear();\n\t\t\tthis.labelsById.clear();\n\t\t\tthis.labelTimestampsById.clear();\n\t\t\tthis.restore({ header: record, entries: [], lastSeq: result.lastSeq }, location);\n\t\t\treturn this.sessionFile;\n\t\t});\n\t}\n\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst previous = this.getHeader()!;\n\t\t\tif (classifiedWorkflowMetadata(previous)) return;\n\t\t\tconst validWorkflow = validSessionWorkflowMetadata(workflow);\n\t\t\tif (!validWorkflow) return;\n\t\t\tconst header: SessionHeader = { ...previous, internal: true, workflow: validWorkflow };\n\t\t\tconst result = await this.store.replace(this.sessionId, this.recordHeader(header), this.getEntries(), {\n\t\t\t\texpectSeq: this.lastSeq,\n\t\t\t});\n\t\t\tthis.lastSeq = result.lastSeq;\n\t\t\tthis.fileEntries[0] = header;\n\t\t});\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tvalidateSessionFileEntries(this.fileEntries, this.sessionFile ?? \"in-memory session\");\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn !(this.store instanceof MemorySessionStore);\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn pathsEqual(this.sessionDir, getDefaultSessionDirPath(this.cwd));\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\tgetSessionStore(): SessionStore {\n\t\treturn this.store;\n\t}\n\n\tasync deleteSession(sessionId: string): Promise<void> {\n\t\tassertValidSessionId(sessionId);\n\t\tif (sessionId === this.sessionId) {\n\t\t\tthrow new Error(`Cannot delete the session that is currently open: ${sessionId}`);\n\t\t}\n\t\ttry {\n\t\t\tawait this.store.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError)) throw error;\n\t\t}\n\t}\n\n\t/** @internal Finalize provisional startup storage after project trust resolves. */\n\trebindStore(store: SessionStore, removeProvisionalRecord: boolean): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (store === this.store) return;\n\t\t\tconst header = this.recordHeader();\n\t\t\tconst entries = this.getEntries();\n\t\t\tconst hashes = sessionBlobHashes(this.store, entries);\n\t\t\tassertSessionBlobStore(store, this.sessionId, hashes.length);\n\t\t\tconst result = await store.create(header, entries);\n\t\t\tawait copySessionBlobs(this.store, this.sessionId, store, this.sessionId, hashes);\n\t\t\tif (removeProvisionalRecord) await this.store.delete(this.sessionId);\n\t\t\tthis.store = store;\n\t\t\tthis.sessionDir = store instanceof JsonlSessionStore ? store.descriptor.location : \"\";\n\t\t\tthis.restore({ header, entries, lastSeq: result.lastSeq });\n\t\t});\n\t}\n\n\tasync openSessionById(sessionId: string, cwdOverride?: string, sessionDirectory?: string): Promise<SessionManager> {\n\t\tlet store =\n\t\t\tsessionDirectory === undefined\n\t\t\t\t? this.store\n\t\t\t\t: await JsonlSessionStore.open(sessionDirectory, { exactDirectory: true, scanExisting: false });\n\t\tlet snapshot: SessionSnapshot;\n\t\ttry {\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\t!(error instanceof SessionNotFoundError) ||\n\t\t\t\tsessionDirectory !== undefined ||\n\t\t\t\t!this.usesDefaultSessionDir()\n\t\t\t)\n\t\t\t\tthrow error;\n\t\t\tstore = await JsonlSessionStore.open(join(getAgentDir(), \"sessions\"), { scanExisting: false });\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t}\n\t\tconst location = store instanceof JsonlSessionStore ? await store.findFile(sessionId) : undefined;\n\t\tif (location !== undefined) {\n\t\t\tstore = await JsonlSessionStore.open(dirname(location), { exactDirectory: true, scanExisting: false });\n\t\t\tsnapshot = await store.load(sessionId);\n\t\t}\n\t\tif (snapshot.header.id !== sessionId) throw new SessionIdMismatchError(sessionId, snapshot.header.id);\n\t\tconst manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);\n\t\tmanager.restore(snapshot, location);\n\t\tif (location !== undefined) manager.sessionDir = dirname(location);\n\t\treturn manager;\n\t}\n\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<SessionManager> {\n\t\tconst source = await JsonlSessionStore.open(dirname(resolvePath(inputPath)), {\n\t\t\texactDirectory: true,\n\t\t\tscanExisting: false,\n\t\t});\n\t\ttry {\n\t\t\tconst loaded = await source.loadFile(inputPath);\n\t\t\tconst { entries, blobs } = takeInlineToolOutput(loaded.entries, loaded.header.id);\n\t\t\tassertSessionBlobStore(this.store, loaded.header.id, blobs.length);\n\t\t\tconst snapshot = {\n\t\t\t\t...loaded,\n\t\t\t\tentries: await adoptInlineSnapshotBlobs(entries, this.store.snapshotBlobs),\n\t\t\t};\n\t\t\tconst manager = new SessionManager(this.store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);\n\t\t\tmanager.restore(snapshot);\n\t\t\tawait manager.initialize();\n\t\t\tawait storeSessionBlobs(this.store, snapshot.header.id, blobs);\n\t\t\treturn manager;\n\t\t} finally {\n\t\t\tawait source.close();\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): Promise<void> {\n\t\treturn this._appendEntries([entry]);\n\t}\n\n\tprivate async _appendEntries(entries: readonly SessionEntry[]): Promise<void> {\n\t\tconst result = await this.store.append(this.sessionId, entries, { expectSeq: this.lastSeq });\n\t\tthis.lastSeq = result.lastSeq;\n\t\tfor (const entry of entries) {\n\t\t\tthis.fileEntries.push(entry);\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t}\n\t}\n\n\t/**\n\t * @internal Record the model and thinking level a new session starts on with one store write, as a model change\n\t * followed by a thinking level change.\n\t */\n\tappendStartState(\n\t\tmodel: { readonly provider: string; readonly modelId: string } | undefined,\n\t\tthinkingLevel: string,\n\t): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst modelEntry =\n\t\t\t\tmodel === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: createModelChangeEntry(model.provider, model.modelId, this.byId, this.leafId);\n\t\t\tconst thinkingEntry = createThinkingLevelChangeEntry(\n\t\t\t\tthinkingLevel,\n\t\t\t\t{ has: (id) => id === modelEntry?.id || this.byId.has(id) },\n\t\t\t\tmodelEntry?.id ?? this.leafId,\n\t\t\t);\n\t\t\tawait this._appendEntries(modelEntry === undefined ? [thinkingEntry] : [modelEntry, thinkingEntry]);\n\t\t});\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Record auxiliary model usage without adding it to the LLM context. */\n\tappendUsage(kind: string, provider: string, model: string, usage: Usage, note?: string): Promise<UsageEntry> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry: UsageEntry = {\n\t\t\t\ttype: \"usage\",\n\t\t\t\tid: generateId(this.byId),\n\t\t\t\tparentId: this.leafId,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tkind,\n\t\t\t\tprovider,\n\t\t\t\tmodel,\n\t\t\t\tusage,\n\t\t\t\t...(note === undefined ? {} : { note }),\n\t\t\t};\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry;\n\t\t});\n\t}\n\n\t/**\n\t * Append a model change as child of current leaf, then advance leaf. Returns entry id. `fallback` records why a model\n\t * fallback made the change.\n\t */\n\tappendModelChange(provider: string, modelId: string, fallback?: ModelFallbackRecord): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId, fallback);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\tappendCompaction(\n\t\tcompactedText: string,\n\t\tfirstKeptEntryId: string | null,\n\t\ttokensBefore: number,\n\t\tdetails: VerbatimCompactionDetails,\n\t\tusage?: Usage,\n\t\tcoveredThroughEntryId?: string,\n\t\tprecondition?: () => void,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tprecondition?.();\n\t\t\tif (firstKeptEntryId !== null && !this.byId.has(firstKeptEntryId))\n\t\t\t\tthrow new SessionEntryError(firstKeptEntryId, \"missing\");\n\t\t\tif (coveredThroughEntryId !== undefined && !this.byId.has(coveredThroughEntryId))\n\t\t\t\tthrow new SessionEntryError(coveredThroughEntryId, \"missing\");\n\t\t\tconst entry = createCompactionEntry(\n\t\t\t\tcompactedText,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t\tusage,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t\tcoveredThroughEntryId,\n\t\t\t);\n\t\t\tconst systemMessage = getCurrentSystemMessage(this.buildSessionProjection().messages);\n\t\t\tif (systemMessage) entry.systemMessage = { ...systemMessage, timestamp: new Date(entry.timestamp).getTime() };\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Save a JSONL backup; database-backed sessions have no file snapshot. */\n\twriteBackupSnapshot(label = \"compact\"): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!(this.store instanceof JsonlSessionStore) || !this.sessionFile) return undefined;\n\t\t\tconst path = `${this.sessionFile}.${new Date().toISOString().replace(/[:.]/g, \"-\")}.${label.replace(/[^a-z0-9_-]/gi, \"-\") || \"backup\"}.bak`;\n\t\t\ttry {\n\t\t\t\tawait writeFile(\n\t\t\t\t\tpath,\n\t\t\t\t\t`${[JSON.stringify({ type: \"session\", ...this.recordHeader() }), ...this.getEntries().map((entry) => JSON.stringify(entry))].join(\"\\n\")}\\n`,\n\t\t\t\t);\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new StorageUnavailableError(this.store.descriptor, cause as Error);\n\t\t\t}\n\t\t\treturn path;\n\t\t});\n\t}\n\n\t/** Append a branch-local edit to an earlier model-visible entry. */\n\tappendContextEdit(targetId: string, replacement: ContextEditEntry[\"replacement\"]): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (\n\t\t\t\treplacement !== null &&\n\t\t\t\t(typeof replacement !== \"object\" ||\n\t\t\t\t\t!(\"content\" in replacement) ||\n\t\t\t\t\t(typeof replacement.content !== \"string\" && !Array.isArray(replacement.content)))\n\t\t\t) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"invalid-replacement\");\n\t\t\t}\n\t\t\tconst target = this.byId.get(targetId);\n\t\t\tif (!target) throw new SessionEntryError(targetId, \"missing\");\n\t\t\tif (!this.getBranch().some((entry) => entry.id === targetId)) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"inactive\");\n\t\t\t}\n\t\t\tconst editable =\n\t\t\t\ttarget.type === \"custom_message\" ||\n\t\t\t\t(target.type === \"message\" &&\n\t\t\t\t\t(target.message.role === \"user\" ||\n\t\t\t\t\t\ttarget.message.role === \"assistant\" ||\n\t\t\t\t\t\ttarget.message.role === \"toolResult\"));\n\t\t\tif (!editable) throw new SessionEntryError(targetId, \"not-editable\");\n\t\t\tconst targetRole = target.type === \"message\" ? target.message.role : \"custom\";\n\t\t\tconst normalizedReplacement =\n\t\t\t\treplacement !== null &&\n\t\t\t\t(targetRole === \"assistant\" || targetRole === \"toolResult\") &&\n\t\t\t\ttypeof replacement.content === \"string\"\n\t\t\t\t\t? { content: [{ type: \"text\" as const, text: replacement.content }] }\n\t\t\t\t\t: replacement;\n\t\t\tconst entry = createContextEditEntry(targetId, normalizedReplacement, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry<T = SessionJsonValue>(customType: string, data?: T): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/**\n\t * @internal Stores `data` as a blob of the current session and appends the entry that references it, as one\n\t * mutation, so a session change cannot come between the two. The blob goes first: a process that stops in between\n\t * leaves only a blob of this session. Rejects with `blobs-unsupported` when the store holds no blobs.\n\t */\n\tappendToolOutputBlob(toolCallId: string, data: Uint8Array): Promise<SessionBlob> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst { putBlob } = this.store;\n\t\t\tif (putBlob === undefined) {\n\t\t\t\tthrow new SessionBlobError(\"blobs-unsupported\", {\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\tadapter: this.store.descriptor.adapter,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst blob = await putBlob.call(this.store, this.sessionId, data);\n\t\t\tconst reference: ToolOutputReference = { toolCallId, hash: blob.hash, bytes: blob.bytes };\n\t\t\tawait this._appendEntry(createCustomEntry(TOOL_OUTPUT_ENTRY_TYPE, reference, this.byId, this.leafId));\n\t\t\treturn blob;\n\t\t});\n\t}\n\n\t/**\n\t * Record a checkout's snapshot at the current leaf. Pass the snapshot when it is new; omit it to refer to an earlier\n\t * entry's snapshot with the same id (an unchanged capture). `restore` records that the snapshot was restored on\n\t * this host into `root`, and `restoreWarnings` what that restore reported beyond its snapshot record.\n\t */\n\tappendWorktreeSnapshot(\n\t\troot: string,\n\t\tsnapshotId: string,\n\t\tsnapshot?: WorktreeSnapshot,\n\t\trestore?: WorktreeRootMapping,\n\t\trestoreWarnings: readonly WorktreeRestoreHostWarning[] = [],\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (snapshot !== undefined && snapshot.id !== snapshotId) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"snapshot\", \"a snapshot whose id is snapshotId\");\n\t\t\t}\n\t\t\tif (snapshot === undefined && !this.getWorktreeSnapshotRecords().has(snapshotId)) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"snapshotId\", \"the id of a snapshot recorded in this session\");\n\t\t\t}\n\t\t\tif (restore !== undefined && (restore.to !== root || restore.snapshotId !== snapshotId)) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"restore\", \"a mapping to root for snapshotId\");\n\t\t\t}\n\t\t\tif (restore === undefined && restoreWarnings.length > 0) {\n\t\t\t\tthrow new WorkspaceConfigError(\"sdk\", \"restoreWarnings\", \"warnings recorded together with their restore\");\n\t\t\t}\n\t\t\tconst entry = createWorktreeSnapshotEntry(\n\t\t\t\troot,\n\t\t\t\tsnapshotId,\n\t\t\t\tsnapshot,\n\t\t\t\trestore,\n\t\t\t\trestoreWarnings,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Restores recorded on the active branch, oldest first: work recorded under `from` continues under `to`. */\n\tgetWorktreeRootMappings(): WorktreeRootMapping[] {\n\t\treturn this.getBranch().flatMap((entry) =>\n\t\t\tentry.type === \"worktree_snapshot\" && entry.restore ? [entry.restore] : [],\n\t\t);\n\t}\n\n\t/** Every snapshot record in the session, by id. */\n\tgetWorktreeSnapshotRecords(): Map<string, WorktreeSnapshot> {\n\t\tconst records = new Map<string, WorktreeSnapshot>();\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"worktree_snapshot\" && entry.snapshot) records.set(entry.snapshotId, entry.snapshot);\n\t\t}\n\t\treturn records;\n\t}\n\n\t/** The latest snapshot of each checkout root on the active branch, keyed by the root it was last recorded under. */\n\tgetLatestWorktreeSnapshots(): Map<string, WorktreeSnapshot> {\n\t\tconst records = this.getWorktreeSnapshotRecords();\n\t\tconst latest = new Map<string, WorktreeSnapshot>();\n\t\tfor (const entry of this.getBranch()) {\n\t\t\tif (entry.type !== \"worktree_snapshot\") continue;\n\t\t\tconst snapshot = records.get(entry.snapshotId);\n\t\t\tif (snapshot) latest.set(entry.root, snapshot);\n\t\t}\n\t\treturn latest;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Append a generated resume summary anchored to the message it describes. Returns entry id. */\n\tappendSessionSummary(summary: string, summarizedThroughId: string, usage?: Usage): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(summarizedThroughId)) throw new SessionEntryError(summarizedThroughId, \"missing\");\n\t\t\tconst entry = createSessionSummaryEntry(summary, summarizedThroughId, usage, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn this.getSessionNameState().name;\n\t}\n\n\t/**\n\t * Get the session name state. `hasName` is true for a session that was named and\n\t * then cleared even though `name` is undefined; a never-named session reports\n\t * `hasName: false`. Read-side only: the JSONL already records the distinction.\n\t */\n\tgetSessionNameState(): SessionNameState {\n\t\treturn getLatestSessionName(this.fileEntries);\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = SessionJsonValue>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t\tprotectedReconciliation?: { delivery: \"steer\" | \"followUp\" },\n\t\tstageAdmissionKey?: string,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst entry = createCustomMessageEntry(\n\t\t\t\tcustomType,\n\t\t\t\tcontent,\n\t\t\t\tdisplay,\n\t\t\t\tdetails,\n\t\t\t\texcludeFromContext,\n\t\t\t\tprotectedReconciliation,\n\t\t\t\tthis.byId,\n\t\t\t\tthis.leafId,\n\t\t\t\tstageAdmissionKey,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(targetId)) {\n\t\t\t\tthrow new SessionEntryError(targetId, \"missing\");\n\t\t\t}\n\t\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\t\tawait this._appendEntry(entry);\n\t\t\tif (label) {\n\t\t\t\tthis.labelsById.set(targetId, label);\n\t\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tthis.labelsById.delete(targetId);\n\t\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t\t}\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Return the active branch entries after applying the latest compaction boundary. */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Build provenance-preserving, compaction-aware model context from the current leaf. */\n\tbuildSessionProjection(): SessionProjection {\n\t\treturn buildSessionProjection(this.getEntries(), this.leafId, this.byId, this.sessionId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\tconst { messages, thinkingLevel, model } = this.buildSessionProjection();\n\t\treturn { messages, thinkingLevel, model };\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Number of entries without copying the session history. */\n\tgetEntryCount(): number {\n\t\treturn this.byId.size;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (!this.byId.has(branchFromId)) {\n\t\t\t\tthrow new SessionEntryError(branchFromId, \"missing\");\n\t\t\t}\n\t\t\tthis.leafId = branchFromId;\n\t\t});\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): Promise<void> {\n\t\treturn this.runMutation(async () => {\n\t\t\tthis.leafId = null;\n\t\t});\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary<T = SessionJsonValue>(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: import(\"@bastani/pi-ai/compat\").Usage,\n\t\tfromId?: string,\n\t): Promise<string> {\n\t\treturn this.runMutation(async () => {\n\t\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\t\tthrow new SessionEntryError(branchFromId, \"missing\");\n\t\t\t}\n\t\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(\n\t\t\t\tbranchFromId,\n\t\t\t\tfromId ?? this.leafId ?? \"root\",\n\t\t\t\tsummary,\n\t\t\t\tdetails,\n\t\t\t\tusage,\n\t\t\t\tfromHook,\n\t\t\t\tthis.byId,\n\t\t\t);\n\t\t\tawait this._appendEntry(entry);\n\t\t\treturn entry.id;\n\t\t});\n\t}\n\n\tcreateBranchedSession(leafId: string): Promise<string | undefined> {\n\t\treturn this.runMutation(async () => {\n\t\t\tconst result = createBranchedSessionState({\n\t\t\t\tleafId,\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tparentSessionId: this.sessionId,\n\t\t\t\tworkflow: classifiedWorkflowMetadata(this.getHeader()),\n\t\t\t\tpath: this.getBranch(leafId),\n\t\t\t\tlabelsById: this.labelsById,\n\t\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t\t});\n\t\t\tconst header = result.fileEntries[0] as SessionHeader;\n\t\t\tconst entries = getEntriesWithoutHeader(result.fileEntries);\n\t\t\tconst record = this.recordHeader(header);\n\t\t\tconst hashes = sessionBlobHashes(this.store, entries);\n\t\t\tconst store = await this.storeForNewSession();\n\t\t\tconst location =\n\t\t\t\tstore instanceof JsonlSessionStore\n\t\t\t\t\t? this.sessionDir\n\t\t\t\t\t\t? createSessionFilePath(this.sessionDir, record.createdAt, record.id)\n\t\t\t\t\t\t: store.locationFor(record)\n\t\t\t\t\t: undefined;\n\t\t\tconst lastSeq = (\n\t\t\t\tawait (store instanceof JsonlSessionStore\n\t\t\t\t\t? store.create(record, entries, location)\n\t\t\t\t\t: store.create(record, entries))\n\t\t\t).lastSeq;\n\t\t\tawait copySessionBlobs(this.store, this.sessionId, store, record.id, hashes);\n\t\t\tthis.store = store;\n\t\t\tthis.fileEntries = result.fileEntries;\n\t\t\tthis.sessionId = header.id;\n\t\t\tthis.lastSeq = lastSeq;\n\t\t\tthis.sessionFile = location;\n\t\t\tthis._buildIndex();\n\t\t\treturn this.sessionFile;\n\t\t});\n\t}\n\n\tasync forkTo(cwd: string, sessionDir?: string | SessionStore, options?: NewSessionOptions): Promise<SessionManager> {\n\t\tconst store =\n\t\t\ttypeof sessionDir === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: (sessionDir ?? (await resolveSessionStore(cwd)));\n\t\tconst directory = store instanceof JsonlSessionStore ? store.descriptor.location : \"\";\n\t\treturn SessionManager.constructWithStore(store, store !== sessionDir, async () => {\n\t\t\tconst source = { store: this.store, sessionId: this.sessionId, entries: this.getEntries() };\n\t\t\tconst manager = new SessionManager(store, cwd, directory, { ...options, parentSession: source.sessionId });\n\t\t\tconst hashes = sessionBlobHashes(source.store, source.entries);\n\t\t\tassertSessionBlobStore(store, manager.sessionId, hashes.length);\n\t\t\tmanager.fileEntries.push(...source.entries);\n\t\t\tawait manager.initialize();\n\t\t\tawait copySessionBlobs(source.store, source.sessionId, store, manager.sessionId, hashes);\n\t\t\tmanager._buildIndex();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async importFromJsonl(\n\t\tinputPath: string,\n\t\tcwd: string,\n\t\tsessionDir?: string | SessionStore,\n\t): Promise<SessionManager> {\n\t\tconst store =\n\t\t\ttypeof sessionDir === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: (sessionDir ?? (await resolveSessionStore(cwd)));\n\t\treturn SessionManager.constructWithStore(store, store !== sessionDir, () =>\n\t\t\tnew SessionManager(\n\t\t\t\tstore,\n\t\t\t\tcwd,\n\t\t\t\tstore instanceof JsonlSessionStore ? store.descriptor.location : \"\",\n\t\t\t).importFromJsonl(inputPath),\n\t\t);\n\t}\n\tprivate static async constructWithStore(\n\t\tstore: SessionStore,\n\t\towned: boolean,\n\t\tconstruct: () => Promise<SessionManager>,\n\t): Promise<SessionManager> {\n\t\ttry {\n\t\t\treturn await construct();\n\t\t} catch (error) {\n\t\t\tif (owned) {\n\t\t\t\ttry {\n\t\t\t\t\tawait store.close();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new StorageRollbackError(error as StorageFailureCause, cause as StorageFailureCause);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tstatic async create(cwd: string, sessionDir?: string, options?: NewSessionOptions): Promise<SessionManager>;\n\tstatic async create(store: SessionStore, cwd: string, options?: NewSessionOptions): Promise<SessionManager>;\n\tstatic async create(\n\t\tcwdOrStore: string | SessionStore,\n\t\tdirectoryOrCwd?: string,\n\t\toptions?: NewSessionOptions,\n\t): Promise<SessionManager> {\n\t\tconst cwd = typeof cwdOrStore === \"string\" ? cwdOrStore : (directoryOrCwd ?? process.cwd());\n\t\tif (typeof cwdOrStore === \"string\" && directoryOrCwd === undefined) {\n\t\t\tconst store = await resolveSessionStore(cwd);\n\t\t\treturn SessionManager.constructWithStore(store, true, () => SessionManager.create(store, cwd, options));\n\t\t}\n\t\tconst directory =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? directoryOrCwd\n\t\t\t\t\t? normalizePath(directoryOrCwd)\n\t\t\t\t\t: getDefaultSessionDirPath(cwd)\n\t\t\t\t: cwdOrStore instanceof JsonlSessionStore\n\t\t\t\t\t? cwdOrStore.descriptor.location\n\t\t\t\t\t: \"\";\n\t\tconst store =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: cwdOrStore;\n\t\treturn SessionManager.constructWithStore(store, store !== cwdOrStore, async () => {\n\t\t\tconst manager = new SessionManager(store, cwd, directory, options);\n\t\t\tif (typeof cwdOrStore !== \"string\" && store instanceof JsonlSessionStore) {\n\t\t\t\tmanager.sessionFile = store.locationFor(manager.recordHeader());\n\t\t\t\tmanager.sessionDir = dirname(manager.sessionFile);\n\t\t\t}\n\t\t\tawait manager.initialize();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async open(path: string, sessionDir?: string, cwdOverride?: string): Promise<SessionManager>;\n\tstatic async open(store: SessionStore, sessionId: string, cwdOverride?: string): Promise<SessionManager>;\n\tstatic async open(\n\t\tpathOrStore: string | SessionStore,\n\t\tdirectoryOrId?: string,\n\t\tcwdOverride?: string,\n\t): Promise<SessionManager> {\n\t\tif (typeof pathOrStore !== \"string\") {\n\t\t\tconst snapshot = await pathOrStore.load(directoryOrId!);\n\t\t\tif (snapshot.header.id !== directoryOrId) throw new SessionIdMismatchError(directoryOrId!, snapshot.header.id);\n\t\t\tconst manager = new SessionManager(\n\t\t\t\tpathOrStore,\n\t\t\t\tcwdOverride ?? snapshot.header.cwd,\n\t\t\t\tpathOrStore instanceof JsonlSessionStore ? pathOrStore.descriptor.location : \"\",\n\t\t\t);\n\t\t\tmanager.restore(\n\t\t\t\tsnapshot,\n\t\t\t\tpathOrStore instanceof JsonlSessionStore ? await pathOrStore.findFile(directoryOrId!) : undefined,\n\t\t\t);\n\t\t\tif (manager.sessionFile) manager.sessionDir = dirname(manager.sessionFile);\n\t\t\treturn manager;\n\t\t}\n\t\tconst path = resolvePath(pathOrStore);\n\t\tconst directory = directoryOrId ?? dirname(path);\n\t\tconst store = await JsonlSessionStore.open(dirname(path), { exactDirectory: true, scanExisting: false });\n\t\tlet snapshot: SessionSnapshot;\n\t\ttry {\n\t\t\tsnapshot = await store.loadFile(path);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof StorageUnavailableError) || (error.cause as NodeJS.ErrnoException).code !== \"ENOENT\")\n\t\t\t\tthrow error;\n\t\t\tconst manager = new SessionManager(store, cwdOverride ?? process.cwd(), directory);\n\t\t\tmanager.lastSeq = (await store.create(manager.recordHeader(), [], path)).lastSeq;\n\t\t\tmanager.sessionFile = path;\n\t\t\treturn manager;\n\t\t}\n\t\tconst manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, directory);\n\t\tmanager.restore(snapshot, path);\n\t\treturn manager;\n\t}\n\n\tstatic async continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager>;\n\tstatic async continueRecent(\n\t\tstore: SessionStore,\n\t\tcwd: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager>;\n\tstatic async continueRecent(\n\t\tcwdOrStore: string | SessionStore,\n\t\tdirectoryOrCwd?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionManager> {\n\t\tconst cwd = typeof cwdOrStore === \"string\" ? cwdOrStore : directoryOrCwd!;\n\t\tif (typeof cwdOrStore === \"string\" && directoryOrCwd === undefined) {\n\t\t\tconst store = await resolveSessionStore(cwd);\n\t\t\treturn SessionManager.constructWithStore(store, true, () =>\n\t\t\t\tSessionManager.continueRecent(store, cwd, options),\n\t\t\t);\n\t\t}\n\t\tconst directory = typeof cwdOrStore === \"string\" ? (directoryOrCwd ?? getDefaultSessionDirPath(cwd)) : \"\";\n\t\tconst store =\n\t\t\ttypeof cwdOrStore === \"string\"\n\t\t\t\t? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })\n\t\t\t\t: cwdOrStore;\n\t\treturn SessionManager.constructWithStore(store, store !== cwdOrStore, async () => {\n\t\t\tconst recent = await store.findMostRecent({\n\t\t\t\tcwd: resolvePath(cwd),\n\t\t\t\tincludeInternal: options?.includeInternal,\n\t\t\t});\n\t\t\tconst manager = new SessionManager(store, cwd, directory);\n\t\t\tif (recent) manager.restore(await store.load(recent.id), recent.location);\n\t\t\telse await manager.initialize();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions, entries?: FileEntry[]): SessionManager {\n\t\tconst manager = new SessionManager(\n\t\t\tmarkPrivateMemorySessionStore(new MemorySessionStore(createSessionCwdMatcher)),\n\t\t\tcwd,\n\t\t\t\"\",\n\t\t\toptions,\n\t\t);\n\t\tif (entries?.length) {\n\t\t\tmanager.fileEntries = entries[0].type === \"session\" ? entries : [...manager.fileEntries, ...entries];\n\t\t\tmanager.sessionId = manager.getHeader()!.id;\n\t\t\tmanager._buildIndex();\n\t\t}\n\t\tmanager.mutation = manager.initialize();\n\t\treturn manager;\n\t}\n\n\tstatic async forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): Promise<SessionManager> {\n\t\tconst sourceStore = await JsonlSessionStore.open(dirname(resolvePath(sourcePath)), {\n\t\t\texactDirectory: true,\n\t\t\tscanExisting: false,\n\t\t});\n\t\tlet source: SessionSnapshot;\n\t\ttry {\n\t\t\tsource = await sourceStore.loadFile(resolvePath(sourcePath));\n\t\t} finally {\n\t\t\tawait sourceStore.close();\n\t\t}\n\t\tconst { entries, blobs } = takeInlineToolOutput(source.entries, source.header.id);\n\t\tconst store =\n\t\t\tsessionDir === undefined\n\t\t\t\t? await resolveSessionStore(targetCwd)\n\t\t\t\t: await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false });\n\t\treturn SessionManager.constructWithStore(store, true, async () => {\n\t\t\tconst manager = new SessionManager(store, targetCwd, sessionDir ?? \"\", {\n\t\t\t\t...options,\n\t\t\t\tparentSession: source.header.id,\n\t\t\t});\n\t\t\tassertSessionBlobStore(store, manager.sessionId, blobs.length);\n\t\t\tmanager.fileEntries.push(...entries);\n\t\t\tawait manager.initialize();\n\t\t\tawait storeSessionBlobs(store, manager.sessionId, blobs);\n\t\t\tmanager._buildIndex();\n\t\t\treturn manager;\n\t\t});\n\t}\n\n\tstatic async findById(cwd: string, id: string, sessionDir?: string): Promise<string | undefined> {\n\t\tconst store =\n\t\t\tsessionDir === undefined\n\t\t\t\t? await resolveSessionStore(cwd)\n\t\t\t\t: await JsonlSessionStore.open(sessionDir, { exactDirectory: true, scanExisting: false });\n\t\ttry {\n\t\t\tconst header = await store.readHeader(id);\n\t\t\tif (\n\t\t\t\t!header ||\n\t\t\t\tclassifiedWorkflowMetadata(header) ||\n\t\t\t\t!createSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\treturn store instanceof JsonlSessionStore ? await store.findFile(id) : id;\n\t\t} catch (error) {\n\t\t\tif (error instanceof SessionFormatVersionError) return undefined;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t}\n\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string | SessionStore,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tconst signal = options && \"aborted\" in options ? options : options?.signal;\n\t\tif (typeof sessionDir !== \"string\") {\n\t\t\tconst store = sessionDir ?? (await resolveSessionStore(cwd));\n\t\t\ttry {\n\t\t\t\treturn await listSessionStore(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd: resolvePath(cwd),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tincludeInternal:\n\t\t\t\t\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\t\t\t},\n\t\t\t\t\tonProgress,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tif (sessionDir === undefined) await store.close();\n\t\t\t}\n\t\t}\n\t\treturn listProjectSessions(\n\t\t\tcwd,\n\t\t\tsessionDir,\n\t\t\tonProgress,\n\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tstatic async listAll(onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string | SessionStore,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tdirectoryOrProgress?: string | SessionStore | SessionListProgress,\n\t\tprogressOrSignal?: SessionListProgress | AbortSignal,\n\t\toptions?: { includeInternal?: boolean; signal?: AbortSignal } | AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tif (typeof directoryOrProgress !== \"string\") {\n\t\t\tconst supplied = typeof directoryOrProgress === \"object\" ? directoryOrProgress : undefined;\n\t\t\tconst store = supplied ?? (await resolveSessionStore(process.cwd()));\n\t\t\ttry {\n\t\t\t\treturn await listSessionStore(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tincludeInternal:\n\t\t\t\t\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\t\t\t\tsignal:\n\t\t\t\t\t\t\toptions && \"aborted\" in options\n\t\t\t\t\t\t\t\t? options\n\t\t\t\t\t\t\t\t: (options?.signal ?? (typeof progressOrSignal === \"object\" ? progressOrSignal : undefined)),\n\t\t\t\t\t},\n\t\t\t\t\ttypeof directoryOrProgress === \"function\"\n\t\t\t\t\t\t? directoryOrProgress\n\t\t\t\t\t\t: typeof progressOrSignal === \"function\"\n\t\t\t\t\t\t\t? progressOrSignal\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tif (!supplied) await store.close();\n\t\t\t}\n\t\t}\n\t\tconst { listAllSessions } = await import(\"./session-manager-list.ts\");\n\t\treturn listAllSessions(\n\t\t\tdirectoryOrProgress,\n\t\t\ttypeof progressOrSignal === \"function\" ? progressOrSignal : undefined,\n\t\t\toptions !== undefined && \"includeInternal\" in options && options.includeInternal === true,\n\t\t\toptions && \"aborted\" in options\n\t\t\t\t? options\n\t\t\t\t: (options?.signal ?? (typeof progressOrSignal === \"object\" ? progressOrSignal : undefined)),\n\t\t);\n\t}\n}\n"]}
|
|
@@ -22,7 +22,7 @@ export declare function buildContextEntries(entries: SessionEntry[], leafId?: st
|
|
|
22
22
|
* (after its `coveredThroughEntryId`) replay unchanged, and older boundaries among them
|
|
23
23
|
* contribute nothing.
|
|
24
24
|
*/
|
|
25
|
-
export declare function buildSessionProjection(entries: SessionEntry[], leafId?: string | null, byId?: Map<string, SessionEntry
|
|
25
|
+
export declare function buildSessionProjection(entries: SessionEntry[], leafId?: string | null, byId?: Map<string, SessionEntry>, sessionId?: string): SessionProjection;
|
|
26
26
|
/**
|
|
27
27
|
* Build the session context from entries using tree traversal.
|
|
28
28
|
* If leafId is provided, walks from that entry to root.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager-history.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAUlF,OAAO,KAAK,EACX,eAAe,EACf,gBAAgB,EAChB,SAAS,EAET,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,MAAM,4BAA4B,CAAC;AA+CpC,wEAAwE;AACxE,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAMnG;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,gBAAgB,GAAG,YAAY,EAAE,CAmBjG;AA2BD,wBAAgB,gCAAgC,CAC/C,OAAO,EAAE,YAAY,EAAE,GACrB,eAAe,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAQnD;AAED,2FAA2F;AAC3F,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,YAAY,GAAG,YAAY,EAAE,CAiCjF;AAaD,sFAAsF;AACtF,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,IAAI,4BAAqD,GACvD,YAAY,EAAE,CAahB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"session-manager-history.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAUlF,OAAO,KAAK,EACX,eAAe,EACf,gBAAgB,EAChB,SAAS,EAET,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,MAAM,4BAA4B,CAAC;AA+CpC,wEAAwE;AACxE,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAMnG;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,gBAAgB,GAAG,YAAY,EAAE,CAmBjG;AA2BD,wBAAgB,gCAAgC,CAC/C,OAAO,EAAE,YAAY,EAAE,GACrB,eAAe,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAQnD;AAED,2FAA2F;AAC3F,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,YAAY,GAAG,YAAY,EAAE,CAiCjF;AAaD,sFAAsF;AACtF,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,IAAI,4BAAqD,GACvD,YAAY,EAAE,CAahB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAChC,SAAS,CAAC,EAAE,MAAM,GAChB,iBAAiB,CAgFnB;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,YAAY,EAAE,EACvB,MAA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