@ai-agent-forge/agent-forge 0.86.2 → 0.86.4
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 +38 -1
- package/dist/bundle/.build-manifest.json +183 -177
- package/dist/bundle/chunks/{anthropic-messages-RJYU4TCY.js → anthropic-messages-EVFQ6MLR.js} +3 -3
- package/dist/bundle/chunks/{azure-openai-responses-LESTCUL7.js → azure-openai-responses-WQCZWFAH.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-MDOTREMR.js → chunk-3WE3W52L.js} +2 -2
- package/dist/bundle/chunks/chunk-F6SBZUJG.js +141 -0
- package/dist/bundle/chunks/{chunk-SER2HCLE.js → chunk-PE3XUHPT.js} +3 -3
- package/dist/bundle/chunks/chunk-TBPTHASB.js +2 -0
- package/dist/bundle/chunks/chunk-ZV3W36HK.js +1445 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-generative-ai-LQ375GYC.js +2 -0
- package/dist/bundle/chunks/google-vertex-HXSRAKEZ.js +2 -0
- package/dist/bundle/chunks/jiti-static-loader-CDSTNEDU.js +2 -0
- package/dist/bundle/chunks/mistral-conversations-CSNMFR4J.js +5 -0
- package/dist/bundle/chunks/{openai-codex-responses-UFH6O5K6.js → openai-codex-responses-YDJSZOIH.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-A55GHA4O.js → openai-completions-UPRWTQPT.js} +3 -3
- package/dist/bundle/chunks/openai-responses-O63W6HQ3.js +2 -0
- package/dist/bundle/chunks/virtual-modules-O72ICTMQ.js +2 -0
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +14 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/session-picker.d.ts +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +8 -2
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts +4 -4
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +161 -45
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +13 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +91 -93
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +15 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +20 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/export-html/template.css +10 -0
- package/dist/core/export-html/template.js +50 -17
- package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +1 -1
- package/dist/core/extensions/bootstrap-compaction-policy.js +1 -2
- package/dist/core/extensions/bootstrap-compaction-policy.js.map +1 -1
- package/dist/core/extensions/capability-plugin.d.ts.map +1 -1
- package/dist/core/extensions/capability-plugin.js +25 -30
- package/dist/core/extensions/capability-plugin.js.map +1 -1
- package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
- package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
- package/dist/core/extensions/jiti-static-loader.js +5 -0
- package/dist/core/extensions/jiti-static-loader.js.map +1 -0
- package/dist/core/extensions/microcompact.d.ts +16 -8
- package/dist/core/extensions/microcompact.d.ts.map +1 -1
- package/dist/core/extensions/microcompact.js +9 -7
- package/dist/core/extensions/microcompact.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +3 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +32 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/facade/coding-agent-facade.d.ts +3 -3
- package/dist/core/facade/coding-agent-facade.d.ts.map +1 -1
- package/dist/core/facade/coding-agent-facade.js.map +1 -1
- package/dist/core/facade/coding-agent-runtime-facade.d.ts +2 -2
- package/dist/core/facade/coding-agent-runtime-facade.d.ts.map +1 -1
- package/dist/core/facade/coding-agent-runtime-facade.js +4 -4
- package/dist/core/facade/coding-agent-runtime-facade.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +2 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-install-host.d.ts +1 -1
- package/dist/core/package-install-host.d.ts.map +1 -1
- package/dist/core/package-install-host.js +4 -3
- package/dist/core/package-install-host.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +6 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +61 -35
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +6 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/session-manager.d.ts +23 -4
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +146 -108
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +5 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +27 -13
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +6 -7
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +8 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +40 -4
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +5 -5
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +74 -50
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +18 -9
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +35 -32
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +14 -6
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +47 -10
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +9 -10
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +10 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/remote/server-assembly.d.ts.map +1 -1
- package/dist/remote/server-assembly.js +1 -1
- package/dist/remote/server-assembly.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +1 -12
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +88 -13
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/mime.d.ts.map +1 -1
- package/dist/utils/mime.js +1 -1
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/shell.d.ts +1 -3
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +3 -30
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/wsl.d.ts +3 -0
- package/dist/utils/wsl.d.ts.map +1 -0
- package/dist/utils/wsl.js +15 -0
- package/dist/utils/wsl.js.map +1 -0
- package/docs/rpc.md +7 -5
- package/docs/sdk.md +9 -8
- package/package.json +1 -1
- package/dist/bundle/chunks/chunk-JR3Q27QP.js +0 -1581
- package/dist/bundle/chunks/chunk-KQEGUM34.js +0 -2
- package/dist/bundle/chunks/google-generative-ai-NZ66X6K7.js +0 -2
- package/dist/bundle/chunks/google-vertex-2ZZOFBNQ.js +0 -2
- package/dist/bundle/chunks/mistral-conversations-B6DZRMEK.js +0 -5
- package/dist/bundle/chunks/openai-responses-TJLXRAXR.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager.d.ts","sourceRoot":"","sources":["../../src/core/session-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EAAE,KAAK,WAAW,EAAiB,KAAK,KAAK,EAAU,MAAM,iBAAiB,CAAC;AASvH,OAAO,KAAK,EACX,yBAAyB,EACzB,wBAAwB,EACxB,iBAAiB,EACjB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAKlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAGN,KAAK,sBAAsB,EAC3B,MAAM,sBAAsB,CAAC;AAE9B,eAAO,MAAM,uBAAuB,IAAI,CAAC;AA2DzC,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oGAAsD;IACtD,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yHAAiD;IAC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Aa,OAAO,CAAC,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAC/E,OAAa,OAAO,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CA4DpG","sourcesContent":["import type { AgentMessage } from \"@agent-forge/agent-core\";\nimport { type ImageContent, type Message, type TextContent, type ToolCall, type Usage, uuidv7 } from \"@agent-forge/ai\";\nimport { randomUUID } from \"crypto\";\nimport { createReadStream, existsSync, mkdirSync } from \"fs\";\nimport { readdir, stat } from \"fs/promises\";\nimport { join, resolve } from \"path\";\nimport { createInterface } from \"readline\";\nimport { isDeepStrictEqual } from \"util\";\nimport { APP_NAME, getAgentDir as getDefaultAgentDir, getSessionsDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type {\n\tCompactionCommitRequestV1,\n\tCompactionCommitResultV1,\n\tSessionRevisionV1,\n} from \"./extensions/public-api.ts\";\nimport {\n\ttype BashExecutionMessage,\n\ttype CustomMessage,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n\tcreateInterruptedToolResultMessage,\n} from \"./messages.ts\";\nimport {\n\tFileSessionStorageProvider,\n\tSessionHeaderScanLimitError,\n\ttype SessionStorageProvider,\n} from \"./session-storage.ts\";\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nfunction sameSessionRevision(left: SessionRevisionV1, right: SessionRevisionV1): boolean {\n\treturn (\n\t\tleft.version === 1 &&\n\t\tright.version === 1 &&\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.sequence === right.sequence &&\n\t\tleft.leafId === right.leafId\n\t);\n}\n\nfunction assertJsonSerializable(value: unknown, field: string, seen = new WeakSet<object>(), path = field): void {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow new Error(`${field} must be JSON-serializable: non-finite number at ${path}`);\n\t}\n\tif (\n\t\ttypeof value === \"undefined\" ||\n\t\ttypeof value === \"function\" ||\n\t\ttypeof value === \"symbol\" ||\n\t\ttypeof value === \"bigint\"\n\t) {\n\t\tthrow new Error(`${field} must be JSON-serializable: unsupported value at ${path}`);\n\t}\n\tif (typeof value !== \"object\") throw new Error(`${field} must be JSON-serializable: unsupported value at ${path}`);\n\tif (seen.has(value)) throw new Error(`${field} must be JSON-serializable: cyclic value at ${path}`);\n\n\tif (!Array.isArray(value)) {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new Error(`${field} must be JSON-serializable: non-plain object at ${path}`);\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new Error(`${field} must be JSON-serializable: symbol key at ${path}`);\n\t\t}\n\t}\n\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tassertJsonSerializable(value[index], field, seen, `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) {\n\t\t\t\tthrow new Error(`${field} must be JSON-serializable: accessor at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertJsonSerializable(descriptor.value, field, seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nexport interface SessionHeader {\n\ttype: \"session\";\n\tversion?: number; // v1 sessions don't have this\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n\t/**\n\t * Profile locked at session creation (passed by remote create). Written\n\t * only when present; older session files have no such fields and readers\n\t * tolerate their absence (non-string values are treated as missing).\n\t */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\t/** 子代理血缘:本会话是哪个 agent 会话的子会话(父 agent 的 sessionId)。 */\n\tparentAgentSession?: string;\n\t/** 子代理血缘:创建该子会话的角色 id(角色定义的 id,仅审计用途,不是权限判据)。 */\n\tagentRole?: string;\n\t/**\n\t * 回合级血缘:创建该子会话的父回合 correlationId。创建事实随头定格,resume\n\t * 打开既有会话不适用(不重写头)。\n\t */\n\tparentTraceId?: string;\n}\n\nexport interface NewSessionOptions {\n\tid?: string;\n\tparentSession?: string;\n\t/** Optional profile lock recorded in the session header at creation. */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\t/** 子代理血缘(见 SessionHeader):父 agent 会话 id 与创建它的角色 id。 */\n\tparentAgentSession?: string;\n\tagentRole?: string;\n\t/** 回合级血缘(见 SessionHeader):创建该子会话的父回合 correlationId。 */\n\tparentTraceId?: string;\n}\n\nexport interface SessionEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface SessionMessageEntry extends SessionEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"compaction\";\n\t/** Host operation identity for an optimistic compaction commit, if one was used. */\n\toperationId?: string;\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension; undefined/false means core-generated for legacy session compatibility. */\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\t/** Extension-specific data (not sent to LLM) */\n\tdetails?: T;\n\t/** Usage from the LLM call that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension; false means core-generated for legacy session compatibility. */\n\tfromHook?: boolean;\n}\n\n/**\n * Custom entry for extensions to store extension-specific data in the session.\n * Use customType to identify your extension's entries.\n *\n * Purpose: Persist extension state across session reloads. On reload, extensions can\n * scan entries for their customType and reconstruct internal state.\n *\n * Does NOT participate in LLM context (ignored by buildSessionContext).\n * For injecting content into context, see CustomMessageEntry.\n */\nexport interface CustomEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\n/** Label entry for user-defined bookmarks/markers on entries. */\nexport interface LabelEntry extends SessionEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\n/** Session metadata entry (e.g., user-defined display name). */\nexport interface SessionInfoEntry extends SessionEntryBase {\n\ttype: \"session_info\";\n\tname?: string;\n}\n\n/**\n * Custom message entry for extensions to inject messages into LLM context.\n * Use customType to identify your extension's entries.\n *\n * Unlike CustomEntry, this DOES participate in LLM context.\n * The content is converted to a user message in buildSessionContext().\n * Use details for extension-specific metadata (not sent to LLM).\n *\n * display controls TUI rendering:\n * - false: hidden entirely\n * - true: rendered with distinct styling (different from user messages)\n */\nexport interface CustomMessageEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\n/** Session entry - has id/parentId for tree structure (returned by \"read\" methods in SessionManager) */\nexport type SessionEntry =\n\t| SessionMessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\n/** Raw file entry (includes header) */\nexport type FileEntry = SessionHeader | SessionEntry;\n\n/** Tree node for getTree() - defensive copy of session structure */\nexport interface SessionTreeNode {\n\tentry: SessionEntry;\n\tchildren: SessionTreeNode[];\n\t/** Resolved label for this entry, if any */\n\tlabel?: string;\n\t/** Timestamp of the latest label change for this entry, if any */\n\tlabelTimestamp?: string;\n}\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionInfo {\n\tpath: string;\n\tid: string;\n\t/** Working directory where the session was started. Empty string for old sessions. */\n\tcwd: string;\n\t/** User-defined display name from session_info entries. */\n\tname?: string;\n\t/** Path to the parent session (if this session was forked). */\n\tparentSessionPath?: string;\n\t/**\n\t * Profile locked at session creation, read back from the header. Absent\n\t * for sessions created without a profile and for older session files.\n\t */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\tcreated: Date;\n\tmodified: Date;\n\tmessageCount: number;\n\tfirstMessage: string;\n\tallMessagesText: string;\n}\n\nexport type ReadonlySessionManager = Pick<\n\tSessionManager,\n\t| \"getCwd\"\n\t| \"getSessionDir\"\n\t| \"getSessionId\"\n\t| \"getSessionFile\"\n\t| \"getRevision\"\n\t| \"getLeafId\"\n\t| \"getLeafEntry\"\n\t| \"getEntry\"\n\t| \"getLabel\"\n\t| \"getBranch\"\n\t| \"buildContextEntries\"\n\t| \"getHeader\"\n\t| \"getEntries\"\n\t| \"getTree\"\n\t| \"getSessionName\"\n>;\n\nfunction createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function assertValidSessionId(id: string): void {\n\tif (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {\n\t\tthrow new Error(\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\n/** Generate a unique short ID (8 hex chars, collision-checked) */\nfunction generateId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = randomUUID().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\t// Fallback to full UUID if somehow we have collisions\n\treturn randomUUID();\n}\n\n/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */\nfunction migrateV1ToV2(entries: FileEntry[]): void {\n\tconst ids = new Set<string>();\n\tlet prevId: string | null = null;\n\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.id = generateId(ids);\n\t\tentry.parentId = prevId;\n\t\tprevId = entry.id;\n\n\t\t// Convert firstKeptEntryIndex to firstKeptEntryId for compaction\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };\n\t\t\tif (typeof comp.firstKeptEntryIndex === \"number\") {\n\t\t\t\tconst targetEntry = entries[comp.firstKeptEntryIndex];\n\t\t\t\tif (targetEntry && targetEntry.type !== \"session\") {\n\t\t\t\t\tcomp.firstKeptEntryId = targetEntry.id;\n\t\t\t\t}\n\t\t\t\tdelete comp.firstKeptEntryIndex;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */\nfunction migrateV2ToV3(entries: FileEntry[]): void {\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 3;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Update message entries with hookMessage role\n\t\tif (entry.type === \"message\") {\n\t\t\tconst msgEntry = entry as SessionMessageEntry;\n\t\t\tif (msgEntry.message && (msgEntry.message as { role: string }).role === \"hookMessage\") {\n\t\t\t\t(msgEntry.message as { role: string }).role = \"custom\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run all necessary migrations to bring entries to current version.\n * Mutates entries in place. Returns true if any migration was applied.\n */\nfunction migrateToCurrentVersion(entries: FileEntry[]): boolean {\n\tconst header = entries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\tconst version = header?.version ?? 1;\n\n\tif (version >= CURRENT_SESSION_VERSION) return false;\n\n\tif (version < 2) migrateV1ToV2(entries);\n\tif (version < 3) migrateV2ToV3(entries);\n\n\treturn true;\n}\n\n/** Exported for testing */\nexport function migrateSessionEntries(entries: FileEntry[]): void {\n\tmigrateToCurrentVersion(entries);\n}\n\n/** Exported for compaction.test.ts */\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tconst lines = content.trim().split(\"\\n\");\n\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\ttry {\n\t\t\tconst entry = JSON.parse(line) as FileEntry;\n\t\t\tentries.push(entry);\n\t\t} catch {\n\t\t\t// Skip malformed lines\n\t\t}\n\t}\n\n\treturn entries;\n}\n\nexport function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tif (entries[i].type === \"compaction\") {\n\t\t\treturn entries[i] as CompactionEntry;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction buildEntryIndex(entries: SessionEntry[], byId?: Map<string, SessionEntry>): Map<string, SessionEntry> {\n\tif (byId) return byId;\n\tconst index = new Map<string, SessionEntry>();\n\tfor (const entry of entries) {\n\t\tindex.set(entry.id, entry);\n\t}\n\treturn index;\n}\n\nfunction buildSessionPath(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionEntry[] {\n\tconst index = buildEntryIndex(entries, byId);\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\treturn [];\n\t}\n\tif (leafId) {\n\t\tleaf = index.get(leafId);\n\t}\n\tleaf ??= entries[entries.length - 1];\n\tif (!leaf) {\n\t\treturn [];\n\t}\n\n\tconst path: SessionEntry[] = [];\n\tlet current: SessionEntry | undefined = leaf;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? index.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nfunction getSessionContextSettings(path: SessionEntry[]): Pick<SessionContext, \"thinkingLevel\" | \"model\"> {\n\tlet thinkingLevel = \"off\";\n\t// 显式 /model 切换(model_change)优先于回合推导:assistant 消息的 provider 只\n\t// 反映\"当时用了什么\",若让它按顺序覆盖显式切换,一次错误的恢复回合会把用户\n\t// 的切换永久毒化(dogfood 2026-09-25 实测)。没有显式切换时才回退到最近回合\n\t// 实际使用的模型。\n\tlet explicitModel: { provider: string; modelId: string } | null = null;\n\tlet derivedModel: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\texplicitModel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tderivedModel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\treturn { thinkingLevel, model: explicitModel ?? derivedModel };\n}\n\n/**\n * Assistant messages that ended in error, were aborted, or are deferred are\n * runtime outcomes, not conversation content. They stay in the session file\n * for history and rendering of the live turn, but must not re-enter the model\n * context on rebuild (compaction, tree navigation, resume).\n */\nfunction isContextMessage(message: AgentMessage): boolean {\n\treturn (\n\t\tmessage.role !== \"assistant\" ||\n\t\t(message.stopReason !== \"error\" && message.stopReason !== \"aborted\" && message.stopReason !== \"deferred\")\n\t);\n}\n\n/**\n * Backfill dangling toolCalls left by a crash or force-kill between an\n * assistant message and its toolResult messages: providers reject that\n * half-paired sequence on resume. Mirroring the live cancel path\n * (failUnexecutedToolCalls), each dangling call gets one deterministic error\n * toolResult inserted immediately after its assistant message — the position\n * providers require for tool_call/tool_result pairing. This is a pure\n * in-memory projection repair; the session file is never rewritten.\n *\n * O(n) over the projected sequence and idempotent: the synthetic results are\n * derived from fixed session data (the assistant message's timestamp, not\n * Date.now()), and a sequence without dangling calls is returned unchanged\n * (same reference).\n */\nfunction backfillDanglingToolResults(messages: AgentMessage[]): AgentMessage[] {\n\tconst answeredToolCallIds = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role === \"toolResult\") answeredToolCallIds.add(message.toolCallId);\n\t}\n\n\tconst repaired: AgentMessage[] = [];\n\tlet changed = false;\n\tfor (const message of messages) {\n\t\trepaired.push(message);\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst danglingCalls = message.content.filter(\n\t\t\t\t(block): block is ToolCall => block.type === \"toolCall\" && !answeredToolCallIds.has(block.id),\n\t\t\t);\n\t\t\tif (danglingCalls.length > 0) {\n\t\t\t\tfor (const call of danglingCalls) {\n\t\t\t\t\tansweredToolCallIds.add(call.id);\n\t\t\t\t\trepaired.push(createInterruptedToolResultMessage(call, message.timestamp));\n\t\t\t\t}\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Project one selected session entry into LLM/runtime messages.\n * Plain custom entries are display/state entries and do not participate in context.\n */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") {\n\t\tconst message = entry.message;\n\t\t// Session files are parsed without validation; old versions, forks, or\n\t\t// hand-edited files can contain messages with null/missing content.\n\t\tif (\n\t\t\t(message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") &&\n\t\t\tmessage.content == null\n\t\t) {\n\t\t\treturn [{ ...message, content: [] }];\n\t\t}\n\t\treturn [message];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];\n\t}\n\treturn [];\n}\n\n/**\n * Build the active, compaction-aware session entry list.\n *\n * This follows the current leaf path. If the path contains compaction entries,\n * the latest compaction is represented by the compaction entry itself, followed\n * by the kept entries starting at firstKeptEntryId and all entries after the\n * compaction entry. Older summarized entries are omitted.\n */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionEntry[] {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tif (!compaction) {\n\t\treturn path;\n\t}\n\n\tconst compactionIdx = path.findIndex((entry) => entry.id === compaction.id);\n\tif (compactionIdx < 0) {\n\t\treturn path;\n\t}\n\n\tconst contextEntries: SessionEntry[] = [compaction];\n\tlet foundFirstKept = false;\n\tfor (let i = 0; i < compactionIdx; i++) {\n\t\tconst entry = path[i];\n\t\tif (entry.id === compaction.firstKeptEntryId) {\n\t\t\tfoundFirstKept = true;\n\t\t}\n\t\tif (foundFirstKept) {\n\t\t\tcontextEntries.push(entry);\n\t\t}\n\t}\n\tcontextEntries.push(...path.slice(compactionIdx + 1));\n\treturn contextEntries;\n}\n\n/**\n * A registered generic transform over the projected session entry list.\n * Registered per SessionManager instance via {@link registerEntryProjection};\n * the kernel applies whatever projections are registered during context\n * projection and knows nothing about any specific one.\n */\nexport interface SessionEntryProjection {\n\t/** The plugin-owned custom entry type this projection is associated with. */\n\treadonly customType: string;\n\treadonly project: (entries: SessionEntry[]) => SessionEntry[];\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Handles compaction and branch summaries along the path.\n *\n * `entryProjections` are REGISTERED generic transforms (see\n * {@link SessionManager.registerEntryProjection}): each receives the projected\n * entry list and may replace entries (e.g. a policy plugin eliding bulky old\n * tool results). The kernel applies whatever projections are registered and\n * knows nothing about any specific one.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n\tentryProjections?: readonly SessionEntryProjection[],\n): SessionContext {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tconst { thinkingLevel, model } = getSessionContextSettings(path);\n\t// The filter lives here, not in sessionEntryToContextMessages: rendering\n\t// reuses this projection and must still show failed turns after a reload.\n\tconst contextEntries = buildContextEntries(entries, leafId, byId);\n\tconst projected =\n\t\tentryProjections === undefined ? contextEntries : applyEntryProjections(contextEntries, entryProjections);\n\tconst messages = backfillDanglingToolResults(\n\t\tprojected.flatMap(sessionEntryToContextMessages).filter(isContextMessage),\n\t);\n\treturn { messages, thinkingLevel, model };\n}\n\nfunction applyEntryProjections(\n\tentries: SessionEntry[],\n\tprojections: readonly SessionEntryProjection[],\n): SessionEntry[] {\n\tlet projected = entries;\n\tfor (const projection of projections) {\n\t\tprojected = projection.project(projected);\n\t}\n\treturn projected;\n}\n\n/**\n * Compute the default session directory for a cwd.\n * Encodes cwd into a safe directory name under ~/.agent-forge/agent/sessions/.\n */\nfunction getDefaultSessionDirPath(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst safePath = `--${resolvedCwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\treturn join(resolvedAgentDir, \"sessions\", safePath);\n}\n\nexport function getDefaultSessionDir(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst sessionDir = getDefaultSessionDirPath(cwd, agentDir);\n\tif (!existsSync(sessionDir)) {\n\t\tmkdirSync(sessionDir, { recursive: true });\n\t}\n\treturn sessionDir;\n}\n\n/**\n * Compute the trace file path paired with a session file path: the single\n * source of truth for the session/trace pairing convention (X.jsonl ->\n * X.trace.jsonl in the same directory).\n *\n * A trailing \".jsonl\" (case-sensitive, matching how this codebase generates\n * session file names) is replaced with \".trace.jsonl\"; any other path gets\n * \".trace.jsonl\" appended. Idempotent by convention: an input already ending\n * in \".trace.jsonl\" is returned unchanged, so applying the mapping twice\n * cannot produce \".trace.jsonl.trace.jsonl\".\n *\n * Pure function: no IO, no state, no filesystem access.\n */\nexport function getTraceFilePathForSession(sessionFilePath: string): string {\n\tif (sessionFilePath.endsWith(\".trace.jsonl\")) {\n\t\treturn sessionFilePath;\n\t}\n\tif (sessionFilePath.endsWith(\".jsonl\")) {\n\t\treturn `${sessionFilePath.slice(0, -\".jsonl\".length)}.trace.jsonl`;\n\t}\n\treturn `${sessionFilePath}.trace.jsonl`;\n}\n\nfunction parseSessionEntryLine(line: string): FileEntry | null {\n\tif (!line.trim()) return null;\n\ttry {\n\t\treturn JSON.parse(line) as FileEntry;\n\t} catch {\n\t\t// Skip malformed lines\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing; delegates to the default file storage provider. */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\treturn FileSessionStorageProvider.instance.loadEntries(filePath);\n}\n\nfunction readSessionHeaderForDiscovery(storage: SessionStorageProvider, filePath: string): SessionHeader | null {\n\ttry {\n\t\treturn storage.readHeader(filePath);\n\t} catch {\n\t\t// Discovery is best-effort: unreadable or oversized files are not sessions,\n\t\t// and one corrupt file must not prevent other sessions from being found.\n\t\treturn null;\n\t}\n}\n\nfunction getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\nfunction sessionCwdMatches(cwd: string | undefined, resolvedCwd: string): boolean {\n\treturn cwd !== undefined && cwd !== \"\" && resolvePath(cwd) === resolvedCwd;\n}\n\nfunction findMostRecentSessionWithStorage(\n\tstorage: SessionStorageProvider,\n\tsessionDir: string,\n\tcwd?: string,\n): string | null {\n\tconst resolvedCwd = cwd ? resolvePath(cwd) : undefined;\n\ttry {\n\t\tconst files = storage\n\t\t\t.listSessionFiles(sessionDir)\n\t\t\t.map((path) => ({ path, header: readSessionHeaderForDiscovery(storage, path) }))\n\t\t\t.filter(\n\t\t\t\t(file): file is { path: string; header: SessionHeader } =>\n\t\t\t\t\tfile.header !== null &&\n\t\t\t\t\t(!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)),\n\t\t\t)\n\t\t\t.map(({ path }) => ({ path, mtime: storage.modifiedTime(path) }))\n\t\t\t.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n\n\t\treturn files[0]?.path || null;\n\t} catch {\n\t\t// Directory access and stat races make recent-session discovery unavailable.\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing; delegates to the default file storage provider. */\nexport function findMostRecentSession(sessionDir: string, cwd?: string): string | null {\n\treturn findMostRecentSessionWithStorage(FileSessionStorageProvider.instance, sessionDir, cwd);\n}\n\nfunction isMessageWithContent(message: AgentMessage): message is Message {\n\treturn typeof (message as Message).role === \"string\" && \"content\" in message;\n}\n\nfunction extractTextContent(message: Message): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\" \");\n}\n\nfunction getMessageActivityTime(entry: SessionMessageEntry): number | undefined {\n\tconst message = entry.message;\n\tif (!isMessageWithContent(message)) return undefined;\n\tif (message.role !== \"user\" && message.role !== \"assistant\") return undefined;\n\n\tconst msgTimestamp = (message as { timestamp?: number }).timestamp;\n\tif (typeof msgTimestamp === \"number\") {\n\t\treturn msgTimestamp;\n\t}\n\n\tconst t = new Date(entry.timestamp).getTime();\n\treturn Number.isNaN(t) ? undefined : t;\n}\n\nasync function buildSessionInfo(filePath: string): Promise<SessionInfo | null> {\n\ttry {\n\t\tconst stats = await stat(filePath);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet messageCount = 0;\n\t\tlet firstMessage = \"\";\n\t\tconst allMessages: string[] = [];\n\t\tlet name: string | undefined;\n\t\tlet lastActivityTime: number | undefined;\n\n\t\tconst rl = createInterface({\n\t\t\tinput: createReadStream(filePath, { encoding: \"utf8\" }),\n\t\t\tcrlfDelay: Infinity,\n\t\t});\n\n\t\tfor await (const line of rl) {\n\t\t\tconst entry = parseSessionEntryLine(line);\n\t\t\tif (!entry) continue;\n\n\t\t\tif (!header) {\n\t\t\t\tif (entry.type !== \"session\") return null;\n\t\t\t\theader = entry;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract session name (use latest, including explicit clears)\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\tname = entry.name?.trim() || undefined;\n\t\t\t}\n\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tmessageCount++;\n\n\t\t\tconst activityTime = getMessageActivityTime(entry);\n\t\t\tif (typeof activityTime === \"number\") {\n\t\t\t\tlastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);\n\t\t\t}\n\n\t\t\tconst message = entry.message;\n\t\t\tif (!isMessageWithContent(message)) continue;\n\t\t\tif (message.role !== \"user\" && message.role !== \"assistant\") continue;\n\n\t\t\tconst textContent = extractTextContent(message);\n\t\t\tif (!textContent) continue;\n\n\t\t\tallMessages.push(textContent);\n\t\t\tif (!firstMessage && message.role === \"user\") {\n\t\t\t\tfirstMessage = textContent;\n\t\t\t}\n\t\t}\n\n\t\tif (!header) return null;\n\n\t\tconst cwd = typeof header.cwd === \"string\" ? header.cwd : \"\";\n\t\tconst parentSessionPath = header.parentSession;\n\t\t// Same guard style as cwd: parsed headers are untyped, so non-string\n\t\t// values (hand-edited files) read back as missing.\n\t\tconst profileId = typeof header.profileId === \"string\" ? header.profileId : undefined;\n\t\tconst profileVersion = typeof header.profileVersion === \"string\" ? header.profileVersion : undefined;\n\t\tconst headerTime = typeof header.timestamp === \"string\" ? new Date(header.timestamp).getTime() : NaN;\n\t\tconst modified =\n\t\t\ttypeof lastActivityTime === \"number\" && lastActivityTime > 0\n\t\t\t\t? new Date(lastActivityTime)\n\t\t\t\t: !Number.isNaN(headerTime)\n\t\t\t\t\t? new Date(headerTime)\n\t\t\t\t\t: stats.mtime;\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tid: header.id,\n\t\t\tcwd,\n\t\t\tname,\n\t\t\tparentSessionPath,\n\t\t\tprofileId,\n\t\t\tprofileVersion,\n\t\t\tcreated: new Date(header.timestamp),\n\t\t\tmodified,\n\t\t\tmessageCount,\n\t\t\tfirstMessage: firstMessage || \"(no messages)\",\n\t\t\tallMessagesText: allMessages.join(\" \"),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport type SessionListProgress = (loaded: number, total: number) => void;\n\nconst MAX_CONCURRENT_SESSION_INFO_LOADS = 10;\n\nasync function buildSessionInfosWithConcurrency(\n\tfiles: string[],\n\tonLoaded: () => void,\n): Promise<(SessionInfo | null)[]> {\n\tconst results: (SessionInfo | null)[] = new Array(files.length).fill(null);\n\tconst inFlight = new Set<Promise<void>>();\n\tlet nextIndex = 0;\n\n\tconst startNext = (): void => {\n\t\tconst index = nextIndex++;\n\t\tconst file = files[index];\n\t\tif (!file) return;\n\n\t\tlet task: Promise<void>;\n\t\ttask = buildSessionInfo(file)\n\t\t\t.then((info) => {\n\t\t\t\tresults[index] = info;\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tresults[index] = null;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tinFlight.delete(task);\n\t\t\t\tonLoaded();\n\t\t\t});\n\t\tinFlight.add(task);\n\t};\n\n\twhile (nextIndex < files.length || inFlight.size > 0) {\n\t\twhile (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {\n\t\t\tstartNext();\n\t\t}\n\t\tif (inFlight.size > 0) {\n\t\t\tawait Promise.race(inFlight);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nasync function listSessionsFromDir(\n\tdir: string,\n\tonProgress?: SessionListProgress,\n\tprogressOffset = 0,\n\tprogressTotal?: number,\n): Promise<SessionInfo[]> {\n\tconst sessions: SessionInfo[] = [];\n\tif (!existsSync(dir)) {\n\t\treturn sessions;\n\t}\n\n\ttry {\n\t\tconst dirEntries = await readdir(dir);\n\t\tconst files = dirEntries.filter((f) => f.endsWith(\".jsonl\")).map((f) => join(dir, f));\n\t\tconst total = progressTotal ?? files.length;\n\n\t\tlet loaded = 0;\n\t\tconst results = await buildSessionInfosWithConcurrency(files, () => {\n\t\t\tloaded++;\n\t\t\tonProgress?.(progressOffset + loaded, total);\n\t\t});\n\t\tfor (const info of results) {\n\t\t\tif (info) {\n\t\t\t\tsessions.push(info);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Return empty list on error\n\t}\n\n\treturn sessions;\n}\n\n/**\n * Manages conversation sessions as append-only trees stored in JSONL files.\n *\n * Each session entry has an id and parentId forming a tree structure. The \"leaf\"\n * pointer tracks the current position. Appending creates a child of the current leaf.\n * Branching moves the leaf to an earlier entry, allowing new branches without\n * modifying history.\n *\n * Use buildSessionContext() to get the resolved message list for the LLM, which\n * handles compaction summaries and follows the path from root to current leaf.\n */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate entryProjections: SessionEntryProjection[] = [];\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 compactionOperations: Map<string, CompactionEntry> = new Map();\n\tprivate leafId: string | null = null;\n\tprivate readonly storage: SessionStorageProvider;\n\t/** Cross-process write-arbitration identity (D-067 phase 2 S5); assigned lazily. */\n\tprivate storageWriterId: string | undefined;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t\tpreloadedFileEntries?: FileEntry[],\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tthis.storage = storage;\n\t\tif (persist && this.sessionDir) {\n\t\t\tthis.storage.ensureDir(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis._setSessionFile(sessionFile, preloadedFileEntries);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis._setSessionFile(sessionFile);\n\t}\n\n\tprivate _setSessionFile(sessionFile: string, preloadedFileEntries?: FileEntry[]): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (this.storage.exists(this.sessionFile)) {\n\t\t\tthis.fileEntries = preloadedFileEntries ?? this.storage.loadEntries(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was\n\t\t\t// non-empty but did not parse as a valid Agent Forge session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (this.storage.size(explicitPath) > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid ${APP_NAME} session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: this.sessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: options?.parentSession,\n\t\t\t// Optional profile lock: omit the keys entirely when absent so the\n\t\t\t// header matches the \"optional field\" semantics end to end.\n\t\t\t...(options?.profileId === undefined ? {} : { profileId: options.profileId }),\n\t\t\t...(options?.profileVersion === undefined ? {} : { profileVersion: options.profileVersion }),\n\t\t\t// 子代理血缘(可选,见 SessionHeader)\n\t\t\t...(options?.parentAgentSession === undefined ? {} : { parentAgentSession: options.parentAgentSession }),\n\t\t\t...(options?.agentRole === undefined ? {} : { agentRole: options.agentRole }),\n\t\t\t// 回合级血缘(可选,见 SessionHeader):缺席时键整个省略。\n\t\t\t...(options?.parentTraceId === undefined ? {} : { parentTraceId: options.parentTraceId }),\n\t\t};\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.compactionOperations.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\t\tthis.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.compactionOperations.clear();\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"session\") continue;\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t\tif (entry.type === \"compaction\" && entry.operationId !== undefined) {\n\t\t\t\tif (typeof entry.operationId !== \"string\" || entry.operationId.trim() === \"\") {\n\t\t\t\t\tthrow new Error(`Invalid compaction operationId in session entry: ${entry.id}`);\n\t\t\t\t}\n\t\t\t\tif (this.compactionOperations.has(entry.operationId)) {\n\t\t\t\t\tthrow new Error(`Duplicate compaction operationId in session: ${entry.operationId}`);\n\t\t\t\t}\n\t\t\t\tthis.compactionOperations.set(entry.operationId, entry);\n\t\t\t}\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tif (entry.label) {\n\t\t\t\t\tthis.labelsById.set(entry.targetId, entry.label);\n\t\t\t\t\tthis.labelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t\t} else {\n\t\t\t\t\tthis.labelsById.delete(entry.targetId);\n\t\t\t\t\tthis.labelTimestampsById.delete(entry.targetId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.assertWritable();\n\t\tthis.storage.rewrite(this.sessionFile, this.fileEntries);\n\t}\n\n\t/**\n\t * Cross-process write arbitration (D-067 phase 2 S5): a conflicting live\n\t * foreign owner fails the write explicitly — concurrent writers must never\n\t * silently fork the session history. Dead owners (closed or crashed\n\t * processes) are taken over and same-process writers are allowed by the\n\t * guard itself; the append rollback below keeps memory consistent when it\n\t * throws.\n\t */\n\tprivate assertWritable(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.storageWriterId ??= randomUUID();\n\t\tthis.storage.guard?.ensureWritable(this.sessionFile, this.storageWriterId);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\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 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\t/** Return a stable host fact for optimistic session operations. */\n\tgetRevision(): SessionRevisionV1 {\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tsessionId: this.sessionId,\n\t\t\tsequence: Math.max(0, this.fileEntries.length - 1),\n\t\t\tleafId: this.leafId,\n\t\t};\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.assertWritable();\n\n\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\tif (!hasAssistant) {\n\t\t\tif (this.flushed) {\n\t\t\t\tthis.storage.append(this.sessionFile, entry);\n\t\t\t} else {\n\t\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tthis.storage.createExclusive(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tthis.storage.append(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tconst previousEntries = this.fileEntries.slice();\n\t\tconst previousById = new Map(this.byId);\n\t\tconst previousLeafId = this.leafId;\n\t\tconst previousFlushed = this.flushed;\n\t\tconst sessionFile = this.sessionFile;\n\t\tconst fileExisted = sessionFile !== undefined && this.storage.exists(sessionFile);\n\t\tconst previousFileSize = fileExisted ? this.storage.size(sessionFile as string) : undefined;\n\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\ttry {\n\t\t\tthis._persist(entry);\n\t\t} catch (error) {\n\t\t\tthis.fileEntries = previousEntries;\n\t\t\tthis.byId = previousById;\n\t\t\tthis.leafId = previousLeafId;\n\t\t\tthis.flushed = previousFlushed;\n\n\t\t\ttry {\n\t\t\t\tif (sessionFile && previousFileSize !== undefined) {\n\t\t\t\t\tthis.storage.truncate(sessionFile, previousFileSize);\n\t\t\t\t} else if (sessionFile && !fileExisted && this.storage.exists(sessionFile)) {\n\t\t\t\t\t// The first flushed append may create the session file. Remove only\n\t\t\t\t\t// the file created by this failed append.\n\t\t\t\t\tthis.storage.remove(sessionFile);\n\t\t\t\t}\n\t\t\t} catch (rollbackError) {\n\t\t\t\tthrow new AggregateError([error, rollbackError], \"Session append failed and rollback failed\");\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id.\n\t * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.\n\t * Reason: we want these to be top-level entries in the session, not message session entries,\n\t * so it is easier to find them.\n\t * These need to be appended via appendCompaction() and appendBranchSummary() methods.\n\t */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry: SessionMessageEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\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): string {\n\t\tconst entry: ThinkingLevelChangeEntry = {\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry: ModelChangeEntry = {\n\t\t\ttype: \"model_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tconst entry: CompactionEntry<T> = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Commit one compaction entry against an exact session revision.\n\t *\n\t * This is deliberately a host-only single-append boundary. It does not\n\t * orchestrate compaction, replace context, or form a cross-plugin\n\t * transaction.\n\t */\n\tcommitCompaction<TDetails = unknown>(request: CompactionCommitRequestV1<TDetails>): CompactionCommitResultV1 {\n\t\tthis._validateCompactionCommitRequest(request);\n\n\t\tconst previousOperation = this.compactionOperations.get(request.operationId);\n\t\tif (previousOperation) {\n\t\t\tif (this._matchesCompactionCommitRequest(previousOperation, request)) {\n\t\t\t\treturn {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstatus: \"replayed\",\n\t\t\t\t\tentryId: previousOperation.id,\n\t\t\t\t\trevision: this._revisionAfterEntry(previousOperation),\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(`operation_id_reused: ${request.operationId}`);\n\t\t}\n\n\t\tconst currentRevision = this.getRevision();\n\t\tif (!sameSessionRevision(request.expectedRevision, currentRevision)) {\n\t\t\treturn { version: 1, status: \"revision_conflict\", currentRevision };\n\t\t}\n\n\t\tconst currentBranchContainsFirstKeptEntry = this.getBranch().some(\n\t\t\t(entry) => entry.id === request.firstKeptEntryId,\n\t\t);\n\t\tif (!currentBranchContainsFirstKeptEntry) {\n\t\t\tthrow new Error(`first_kept_entry_not_on_current_branch: ${request.firstKeptEntryId}`);\n\t\t}\n\n\t\tconst entry: CompactionEntry = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\toperationId: request.operationId,\n\t\t\tsummary: request.summary,\n\t\t\tfirstKeptEntryId: request.firstKeptEntryId,\n\t\t\ttokensBefore: request.tokensBefore,\n\t\t\tdetails: request.details,\n\t\t\tusage: request.usage as Usage | undefined,\n\t\t\tfromHook: request.fromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tthis.compactionOperations.set(request.operationId, entry);\n\t\treturn { version: 1, status: \"committed\", entryId: entry.id, revision: this.getRevision() };\n\t}\n\n\tprivate _validateCompactionCommitRequest(request: CompactionCommitRequestV1): void {\n\t\tif (!request || typeof request !== \"object\") throw new Error(\"Compaction commit request must be an object\");\n\t\tif (request.version !== 1) throw new Error(\"Unsupported compaction commit request version\");\n\t\tif (typeof request.operationId !== \"string\" || request.operationId.trim() === \"\") {\n\t\t\tthrow new Error(\"operationId must be a non-empty string\");\n\t\t}\n\t\tif (typeof request.summary !== \"string\" || request.summary.trim() === \"\") {\n\t\t\tthrow new Error(\"summary must be a non-empty string\");\n\t\t}\n\t\tif (typeof request.firstKeptEntryId !== \"string\" || request.firstKeptEntryId === \"\") {\n\t\t\tthrow new Error(\"firstKeptEntryId must be a non-empty string\");\n\t\t}\n\t\tif (\n\t\t\ttypeof request.tokensBefore !== \"number\" ||\n\t\t\t!Number.isFinite(request.tokensBefore) ||\n\t\t\trequest.tokensBefore < 0\n\t\t) {\n\t\t\tthrow new Error(\"tokensBefore must be a non-negative finite number\");\n\t\t}\n\t\tif (request.details !== undefined) assertJsonSerializable(request.details, \"details\");\n\t\tif (request.usage !== undefined) assertJsonSerializable(request.usage, \"usage\");\n\t\tconst revision = request.expectedRevision;\n\t\tif (\n\t\t\trevision?.version !== 1 ||\n\t\t\ttypeof revision.sessionId !== \"string\" ||\n\t\t\trevision.sessionId === \"\" ||\n\t\t\t!Number.isInteger(revision.sequence) ||\n\t\t\trevision.sequence < 0 ||\n\t\t\t(revision.leafId !== null && typeof revision.leafId !== \"string\")\n\t\t) {\n\t\t\tthrow new Error(\"expectedRevision must be a valid SessionRevisionV1\");\n\t\t}\n\t}\n\n\tprivate _matchesCompactionCommitRequest<TDetails>(\n\t\tentry: CompactionEntry,\n\t\trequest: CompactionCommitRequestV1<TDetails>,\n\t): boolean {\n\t\tconst entryIndex = this.fileEntries.indexOf(entry);\n\t\tif (entryIndex <= 0) throw new Error(`Compaction operation entry is missing: ${entry.id}`);\n\t\treturn (\n\t\t\trequest.expectedRevision.version === 1 &&\n\t\t\trequest.expectedRevision.sessionId === this.sessionId &&\n\t\t\trequest.expectedRevision.sequence === entryIndex - 1 &&\n\t\t\trequest.expectedRevision.leafId === entry.parentId &&\n\t\t\trequest.summary === entry.summary &&\n\t\t\trequest.firstKeptEntryId === entry.firstKeptEntryId &&\n\t\t\trequest.tokensBefore === entry.tokensBefore &&\n\t\t\trequest.fromHook === entry.fromHook &&\n\t\t\tisDeepStrictEqual(request.details, entry.details) &&\n\t\t\tisDeepStrictEqual(request.usage, entry.usage)\n\t\t);\n\t}\n\n\tprivate _revisionAfterEntry(entry: CompactionEntry): SessionRevisionV1 {\n\t\tconst entryIndex = this.fileEntries.indexOf(entry);\n\t\tif (entryIndex <= 0) throw new Error(`Compaction operation entry is missing: ${entry.id}`);\n\t\treturn { version: 1, sessionId: this.sessionId, sequence: entryIndex, leafId: entry.id };\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry: CustomEntry = {\n\t\t\ttype: \"custom\",\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst sanitizedName = name.replace(/[\\r\\n]+/g, \" \").trim();\n\t\tconst entry: SessionInfoEntry = {\n\t\t\ttype: \"session_info\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: sanitizedName,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\t// Walk entries in reverse to find the latest session_info entry.\n\t\t// Empty names explicitly clear the session title.\n\t\tconst entries = this.getEntries();\n\t\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = entries[i];\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\treturn entry.name?.trim() || undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Append a custom message entry (for extensions) that participates in LLM context.\n\t * @param customType Extension identifier for filtering on reload\n\t * @param content Message content (string or TextContent/ImageContent array)\n\t * @param display Whether to show in TUI (true = styled display, false = hidden)\n\t * @param details Optional extension-specific metadata (not sent to LLM)\n\t * @returns Entry id\n\t */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): string {\n\t\tconst entry: CustomMessageEntry<T> = {\n\t\t\ttype: \"custom_message\",\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t// =========================================================================\n\t// Tree Traversal\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/**\n\t * Get all direct children of an entry.\n\t */\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/**\n\t * Get the label for an entry, if any.\n\t */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/**\n\t * Set or clear a label on an entry.\n\t * Labels are user-defined markers for bookmarking/navigation.\n\t * Pass undefined or empty string to clear the label.\n\t */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Walk from entry to root, returning all entries in path order.\n\t * Includes all entry types (messages, compaction, model changes, etc.).\n\t * Use buildSessionContext() to get the resolved messages for the LLM.\n\t */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\tconst path: SessionEntry[] = [];\n\t\tconst startId = fromId ?? this.leafId;\n\t\tlet current = startId ? this.byId.get(startId) : undefined;\n\t\twhile (current) {\n\t\t\tpath.push(current);\n\t\t\tcurrent = current.parentId ? this.byId.get(current.parentId) : undefined;\n\t\t}\n\t\tpath.reverse();\n\t\treturn path;\n\t}\n\n\t/**\n\t * Build the active, compaction-aware entry list for context/rendering.\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Build the session context (what gets sent to the LLM).\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId, this.entryProjections);\n\t}\n\n\t/**\n\t * Registers a GENERIC entry projection applied during context projection\n\t * (see {@link buildSessionContext}). The kernel neither interprets nor\n\t * persists projections — plugins own their semantics and remove them via\n\t * the returned disposer. Same channel for first-party and third-party\n\t * plugins; the `customType` is the plugin-owned entry type the projection\n\t * is associated with (used for diagnostics only).\n\t */\n\tregisterEntryProjection(projection: SessionEntryProjection): () => void {\n\t\tthis.entryProjections.push(projection);\n\t\treturn () => {\n\t\t\tconst index = this.entryProjections.indexOf(projection);\n\t\t\tif (index >= 0) this.entryProjections.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Get session header.\n\t */\n\tgetHeader(): SessionHeader | null {\n\t\tconst h = this.fileEntries.find((e) => e.type === \"session\");\n\t\treturn h ? (h as SessionHeader) : null;\n\t}\n\n\t/**\n\t * Get all session entries (excludes header). Returns a shallow copy.\n\t * The session is append-only: use appendXXX() to add entries, branch() to\n\t * change the leaf pointer. Entries cannot be modified or deleted.\n\t */\n\tgetEntries(): SessionEntry[] {\n\t\treturn this.fileEntries.filter((e): e is SessionEntry => e.type !== \"session\");\n\t}\n\n\t/**\n\t * Get the session as a tree structure. Returns a shallow defensive copy of all entries.\n\t * A well-formed session has exactly one root (first entry with parentId === null).\n\t * Orphaned entries (broken parent chain) are also returned as roots.\n\t */\n\tgetTree(): SessionTreeNode[] {\n\t\tconst entries = this.getEntries();\n\t\tconst nodeMap = new Map<string, SessionTreeNode>();\n\t\tconst roots: SessionTreeNode[] = [];\n\n\t\t// Create nodes with resolved labels\n\t\tfor (const entry of entries) {\n\t\t\tconst label = this.labelsById.get(entry.id);\n\t\t\tconst labelTimestamp = this.labelTimestampsById.get(entry.id);\n\t\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t\t}\n\n\t\t// Build tree\n\t\tfor (const entry of entries) {\n\t\t\tconst node = nodeMap.get(entry.id)!;\n\t\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\t\troots.push(node);\n\t\t\t} else {\n\t\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(node);\n\t\t\t\t} else {\n\t\t\t\t\t// Orphan - treat as root\n\t\t\t\t\troots.push(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Sort children by timestamp (oldest first, newest at bottom)\n\t\t// Use iterative approach to avoid stack overflow on deep trees\n\t\tconst stack: SessionTreeNode[] = [...roots];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop()!;\n\t\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\t\tstack.push(...node.children);\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\t// =========================================================================\n\t// Branching\n\t// =========================================================================\n\n\t/**\n\t * Start a new branch from an earlier entry.\n\t * Moves the leaf pointer to the specified entry. The next appendXXX() call\n\t * will create a child of that entry, forming a new branch. Existing entries\n\t * are not modified or deleted.\n\t */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/**\n\t * Reset the leaf pointer to null (before any entries).\n\t * The next appendXXX() call will create a new root entry (parentId = null).\n\t * Use this when navigating to re-edit the first user message.\n\t */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/**\n\t * Start a new branch with a summary of the abandoned path.\n\t * Same as branch(), but also appends a branch_summary entry that captures\n\t * context from the abandoned conversation path.\n\t */\n\tbranchWithSummary(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: unknown,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tconst fromId = this.leafId ?? \"root\";\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = {\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: branchFromId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId,\n\t\t\tsummary,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Create a new session file containing only the path from root to the specified leaf.\n\t * Useful for extracting a single conversation path from a branched session.\n\t * Returns the new session file path, or undefined if not persisting.\n\t */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst previousSessionFile = this.sessionFile;\n\t\tconst path = this.getBranch(leafId);\n\t\tif (path.length === 0) {\n\t\t\tthrow new Error(`Entry ${leafId} not found`);\n\t\t}\n\n\t\t// Filter out LabelEntry from path - we'll recreate them from the resolved map.\n\t\t// Because labels are real tree entries, later entries can be children of labels;\n\t\t// removing labels requires re-chaining the retained path to avoid orphaned subtrees.\n\t\tconst pathWithoutLabels: SessionEntry[] = [];\n\t\tconst replacementByLabelId = new Map<string, string>();\n\t\tconst pendingLabelIds: string[] = [];\n\t\tlet pathParentId: string | null = null;\n\t\tfor (const entry of path) {\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tpendingLabelIds.push(entry.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const labelId of pendingLabelIds) {\n\t\t\t\treplacementByLabelId.set(labelId, entry.id);\n\t\t\t}\n\t\t\tpendingLabelIds.length = 0;\n\t\t\tpathWithoutLabels.push(\n\t\t\t\tentry.type === \"compaction\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...entry,\n\t\t\t\t\t\t\tparentId: pathParentId,\n\t\t\t\t\t\t\tfirstKeptEntryId: replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { ...entry, parentId: pathParentId },\n\t\t\t);\n\t\t\tpathParentId = entry.id;\n\t\t}\n\n\t\tconst newSessionId = createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: this.persist ? previousSessionFile : undefined,\n\t\t};\n\n\t\t// Collect labels for entries in the path\n\t\tconst pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));\n\t\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\t\tfor (const [targetId, label] of this.labelsById) {\n\t\t\tif (pathEntryIds.has(targetId)) {\n\t\t\t\tlabelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });\n\t\t\t}\n\t\t}\n\n\t\tif (this.persist) {\n\t\t\t// Build label entries\n\t\t\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\t\tlet parentId = lastEntryId;\n\t\t\tconst labelEntries: LabelEntry[] = [];\n\t\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\t\ttype: \"label\",\n\t\t\t\t\tid: generateId(new Set(pathEntryIds)),\n\t\t\t\t\tparentId,\n\t\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tlabel,\n\t\t\t\t};\n\t\t\t\tpathEntryIds.add(labelEntry.id);\n\t\t\t\tlabelEntries.push(labelEntry);\n\t\t\t\tparentId = labelEntry.id;\n\t\t\t}\n\n\t\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\t\tthis.sessionId = newSessionId;\n\t\t\tthis.sessionFile = newSessionFile;\n\t\t\tthis._buildIndex();\n\n\t\t\t// Only write the file now if it contains an assistant message.\n\t\t\t// Otherwise defer to _persist(), which creates the file on the\n\t\t\t// first assistant response, matching the newSession() contract\n\t\t\t// and avoiding the duplicate-header bug when _persist()'s\n\t\t\t// no-assistant guard later resets flushed to false.\n\t\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\t\tif (hasAssistant) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t} else {\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\n\t\t\treturn newSessionFile;\n\t\t}\n\n\t\t// In-memory mode: replace current session with the path + labels\n\t\tconst labelEntries: LabelEntry[] = [];\n\t\tlet parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\ttype: \"label\",\n\t\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\t\tparentId,\n\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\ttargetId,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tlabelEntries.push(labelEntry);\n\t\t\tparentId = labelEntry.id;\n\t\t}\n\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\tthis.sessionId = newSessionId;\n\t\tthis._buildIndex();\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create a new session.\n\t * @param cwd Working directory (stored in session header)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param options Optional new-session header options.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic create(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options, undefined, storage);\n\t}\n\n\t/**\n\t * Open a specific session file.\n\t * @param path Path to session file\n\t * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.\n\t * @param cwdOverride Optional cwd override instead of the session header cwd.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic open(\n\t\tpath: string,\n\t\tsessionDir?: string,\n\t\tcwdOverride?: string,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet preloadedFileEntries: FileEntry[] | undefined;\n\t\tif (cwdOverride === undefined && storage.exists(resolvedPath)) {\n\t\t\ttry {\n\t\t\t\theader = storage.readHeader(resolvedPath);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof SessionHeaderScanLimitError)) throw error;\n\t\t\t\t// The bounded scan is only a discovery optimization. A full load remains\n\t\t\t\t// authoritative for legacy files with very large headers or prefixes.\n\t\t\t\tpreloadedFileEntries = storage.loadEntries(resolvedPath);\n\t\t\t\tconst firstEntry = preloadedFileEntries[0];\n\t\t\t\theader = firstEntry?.type === \"session\" ? firstEntry : null;\n\t\t\t}\n\t\t}\n\t\tconst cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd();\n\t\t// If no sessionDir provided, derive from file's parent directory\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true, undefined, preloadedFileEntries, storage);\n\t}\n\n\t/**\n\t * Continue the most recent session, or create new if none.\n\t * @param cwd Working directory\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSessionWithStorage(storage, dir, filterCwd ? cwd : undefined);\n\t\tif (mostRecent) {\n\t\t\treturn new SessionManager(cwd, dir, mostRecent, true, undefined, undefined, storage);\n\t\t}\n\t\treturn new SessionManager(cwd, dir, undefined, true, undefined, undefined, storage);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/**\n\t * Fork a session from another project directory into the current project.\n\t * Creates a new session in the target cwd with the full history from the source session.\n\t * @param sourcePath Path to the source session file\n\t * @param targetCwd Target working directory (where the new session will be stored)\n\t * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.\n\t * @param options Optional new-session header options.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst resolvedSourcePath = resolvePath(sourcePath);\n\t\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\t\tconst sourceEntries = storage.loadEntries(resolvedSourcePath);\n\t\tif (sourceEntries.length === 0) {\n\t\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst sourceHeader = sourceEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\tif (!sourceHeader) {\n\t\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);\n\t\tstorage.ensureDir(dir);\n\n\t\t// Create new session file with new ID but forked content\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tconst newSessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\t// Write new header pointing to source as parent, with updated cwd\n\t\tconst newHeader: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: resolvedTargetCwd,\n\t\t\tparentSession: resolvedSourcePath,\n\t\t};\n\t\tstorage.createExclusive(newSessionFile, [\n\t\t\tnewHeader,\n\t\t\t// Copy all non-header entries from source\n\t\t\t...sourceEntries.filter((entry) => entry.type !== \"session\"),\n\t\t]);\n\n\t\treturn new SessionManager(resolvedTargetCwd, dir, newSessionFile, true, undefined, undefined, storage);\n\t}\n\n\t/**\n\t * List all sessions for a directory.\n\t * @param cwd Working directory (used to compute default session directory)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress): Promise<SessionInfo[]> {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst sessions = (await listSessionsFromDir(dir, onProgress)).filter(\n\t\t\t(session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd),\n\t\t);\n\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\treturn sessions;\n\t}\n\n\t/**\n\t * List all sessions across all project directories.\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(sessionDir?: string, onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t): Promise<SessionInfo[]> {\n\t\tconst customSessionDir =\n\t\t\ttypeof sessionDirOrOnProgress === \"string\" ? normalizePath(sessionDirOrOnProgress) : undefined;\n\t\tconst progress = typeof sessionDirOrOnProgress === \"function\" ? sessionDirOrOnProgress : onProgress;\n\t\tif (customSessionDir) {\n\t\t\tconst sessions = await listSessionsFromDir(customSessionDir, progress);\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t}\n\n\t\tconst sessionsDir = getSessionsDir();\n\n\t\ttry {\n\t\t\tif (!existsSync(sessionsDir)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst entries = await readdir(sessionsDir, { withFileTypes: true });\n\t\t\tconst dirs = entries\n\t\t\t\t.filter((entry) => entry.isDirectory() || entry.isSymbolicLink())\n\t\t\t\t.map((entry) => join(sessionsDir, entry.name));\n\n\t\t\t// Count total files first for accurate progress\n\t\t\tlet totalFiles = 0;\n\t\t\tconst dirFiles: string[][] = [];\n\t\t\tfor (const dir of dirs) {\n\t\t\t\ttry {\n\t\t\t\t\tconst files = (await readdir(dir)).filter((f) => f.endsWith(\".jsonl\"));\n\t\t\t\t\tdirFiles.push(files.map((f) => join(dir, f)));\n\t\t\t\t\ttotalFiles += files.length;\n\t\t\t\t} catch {\n\t\t\t\t\tdirFiles.push([]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Process all files with progress tracking\n\t\t\tlet loaded = 0;\n\t\t\tconst sessions: SessionInfo[] = [];\n\t\t\tconst allFiles = dirFiles.flat();\n\n\t\t\tconst results = await buildSessionInfosWithConcurrency(allFiles, () => {\n\t\t\t\tloaded++;\n\t\t\t\tprogress?.(loaded, totalFiles);\n\t\t\t});\n\n\t\t\tfor (const info of results) {\n\t\t\t\tif (info) {\n\t\t\t\t\tsessions.push(info);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-manager.d.ts","sourceRoot":"","sources":["../../src/core/session-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EAAE,KAAK,WAAW,EAAiB,KAAK,KAAK,EAAU,MAAM,iBAAiB,CAAC;AASvH,OAAO,KAAK,EACX,yBAAyB,EAC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ageContent, type Message, type TextContent, type ToolCall, type Usage, uuidv7 } from \"@agent-forge/ai\";\nimport { randomUUID } from \"crypto\";\nimport { createReadStream, existsSync, mkdirSync, type Stats } from \"fs\";\nimport { readdir, stat } from \"fs/promises\";\nimport { basename, join, resolve } from \"path\";\nimport { createInterface } from \"readline\";\nimport { isDeepStrictEqual } from \"util\";\nimport { APP_NAME, getAgentDir as getDefaultAgentDir, getSessionsDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type {\n\tCompactionCommitRequestV1,\n\tCompactionCommitResultV1,\n\tSessionRevisionV1,\n} from \"./extensions/public-api.ts\";\nimport {\n\ttype BashExecutionMessage,\n\ttype CustomMessage,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n\tcreateInterruptedToolResultMessage,\n} from \"./messages.ts\";\nimport {\n\tFileSessionStorageProvider,\n\tSessionHeaderScanLimitError,\n\ttype SessionStorageProvider,\n} from \"./session-storage.ts\";\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nfunction sameSessionRevision(left: SessionRevisionV1, right: SessionRevisionV1): boolean {\n\treturn (\n\t\tleft.version === 1 &&\n\t\tright.version === 1 &&\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.sequence === right.sequence &&\n\t\tleft.leafId === right.leafId\n\t);\n}\n\nfunction assertJsonSerializable(value: unknown, field: string, seen = new WeakSet<object>(), path = field): void {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n\tif (typeof value === \"number\") {\n\t\tif (Number.isFinite(value)) return;\n\t\tthrow new Error(`${field} must be JSON-serializable: non-finite number at ${path}`);\n\t}\n\tif (\n\t\ttypeof value === \"undefined\" ||\n\t\ttypeof value === \"function\" ||\n\t\ttypeof value === \"symbol\" ||\n\t\ttypeof value === \"bigint\"\n\t) {\n\t\tthrow new Error(`${field} must be JSON-serializable: unsupported value at ${path}`);\n\t}\n\tif (typeof value !== \"object\") throw new Error(`${field} must be JSON-serializable: unsupported value at ${path}`);\n\tif (seen.has(value)) throw new Error(`${field} must be JSON-serializable: cyclic value at ${path}`);\n\n\tif (!Array.isArray(value)) {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new Error(`${field} must be JSON-serializable: non-plain object at ${path}`);\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new Error(`${field} must be JSON-serializable: symbol key at ${path}`);\n\t\t}\n\t}\n\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tassertJsonSerializable(value[index], field, seen, `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (!descriptor || !(\"value\" in descriptor)) {\n\t\t\t\tthrow new Error(`${field} must be JSON-serializable: accessor at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertJsonSerializable(descriptor.value, field, seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nexport interface SessionHeader {\n\ttype: \"session\";\n\tversion?: number; // v1 sessions don't have this\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n\t/**\n\t * Profile locked at session creation (passed by remote create). Written\n\t * only when present; older session files have no such fields and readers\n\t * tolerate their absence (non-string values are treated as missing).\n\t */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\t/** 子代理血缘:本会话是哪个 agent 会话的子会话(父 agent 的 sessionId)。 */\n\tparentAgentSession?: string;\n\t/** 子代理血缘:创建该子会话的角色 id(角色定义的 id,仅审计用途,不是权限判据)。 */\n\tagentRole?: string;\n\t/**\n\t * 回合级血缘:创建该子会话的父回合 correlationId。创建事实随头定格,resume\n\t * 打开既有会话不适用(不重写头)。\n\t */\n\tparentTraceId?: string;\n}\n\nexport interface NewSessionOptions {\n\tid?: string;\n\tparentSession?: string;\n\t/** Optional profile lock recorded in the session header at creation. */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\t/** 子代理血缘(见 SessionHeader):父 agent 会话 id 与创建它的角色 id。 */\n\tparentAgentSession?: string;\n\tagentRole?: string;\n\t/** 回合级血缘(见 SessionHeader):创建该子会话的父回合 correlationId。 */\n\tparentTraceId?: string;\n}\n\nexport interface SessionEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface SessionMessageEntry extends SessionEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"compaction\";\n\t/** Host operation identity for an optimistic compaction commit, if one was used. */\n\toperationId?: string;\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension; undefined/false means core-generated for legacy session compatibility. */\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\t/** Extension-specific data (not sent to LLM) */\n\tdetails?: T;\n\t/** Usage from the LLM call that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension; false means core-generated for legacy session compatibility. */\n\tfromHook?: boolean;\n}\n\n/**\n * Custom entry for extensions to store extension-specific data in the session.\n * Use customType to identify your extension's entries.\n *\n * Purpose: Persist extension state across session reloads. On reload, extensions can\n * scan entries for their customType and reconstruct internal state.\n *\n * Does NOT participate in LLM context (ignored by buildSessionContext).\n * For injecting content into context, see CustomMessageEntry.\n */\nexport interface CustomEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\n/** Label entry for user-defined bookmarks/markers on entries. */\nexport interface LabelEntry extends SessionEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\n/** Session metadata entry (e.g., user-defined display name). */\nexport interface SessionInfoEntry extends SessionEntryBase {\n\ttype: \"session_info\";\n\tname?: string;\n}\n\n/**\n * Custom message entry for extensions to inject messages into LLM context.\n * Use customType to identify your extension's entries.\n *\n * Unlike CustomEntry, this DOES participate in LLM context.\n * The content is converted to a user message in buildSessionContext().\n * Use details for extension-specific metadata (not sent to LLM).\n *\n * display controls TUI rendering:\n * - false: hidden entirely\n * - true: rendered with distinct styling (different from user messages)\n */\nexport interface CustomMessageEntry<T = unknown> extends SessionEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\n/** Session entry - has id/parentId for tree structure (returned by \"read\" methods in SessionManager) */\nexport type SessionEntry =\n\t| SessionMessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\n/** Raw file entry (includes header) */\nexport type FileEntry = SessionHeader | SessionEntry;\n\n/** Tree node for getTree() - defensive copy of session structure */\nexport interface SessionTreeNode {\n\tentry: SessionEntry;\n\tchildren: SessionTreeNode[];\n\t/** Resolved label for this entry, if any */\n\tlabel?: string;\n\t/** Timestamp of the latest label change for this entry, if any */\n\tlabelTimestamp?: string;\n}\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionInfo {\n\tpath: string;\n\tid: string;\n\t/** Working directory where the session was started. Empty string for old sessions. */\n\tcwd: string;\n\t/** User-defined display name from session_info entries. */\n\tname?: string;\n\t/** Path to the parent session (if this session was forked). */\n\tparentSessionPath?: string;\n\t/**\n\t * Profile locked at session creation, read back from the header. Absent\n\t * for sessions created without a profile and for older session files.\n\t */\n\tprofileId?: string;\n\tprofileVersion?: string;\n\tcreated: Date;\n\tmodified: Date;\n\tmessageCount: number;\n\tfirstMessage: string;\n\tallMessagesText: string;\n}\n\nexport type ReadonlySessionManager = Pick<\n\tSessionManager,\n\t| \"getCwd\"\n\t| \"getSessionDir\"\n\t| \"getSessionId\"\n\t| \"getSessionFile\"\n\t| \"getRevision\"\n\t| \"getLeafId\"\n\t| \"getLeafEntry\"\n\t| \"getEntry\"\n\t| \"getLabel\"\n\t| \"getBranch\"\n\t| \"buildContextEntries\"\n\t| \"getHeader\"\n\t| \"getEntries\"\n\t| \"getTree\"\n\t| \"getSessionName\"\n>;\n\nfunction createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function assertValidSessionId(id: string): void {\n\tif (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {\n\t\tthrow new Error(\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\n/** Generate a unique short ID (8 hex chars, collision-checked) */\nfunction generateId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = randomUUID().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\t// Fallback to full UUID if somehow we have collisions\n\treturn randomUUID();\n}\n\n/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */\nfunction migrateV1ToV2(entries: FileEntry[]): void {\n\tconst ids = new Set<string>();\n\tlet prevId: string | null = null;\n\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.id = generateId(ids);\n\t\tentry.parentId = prevId;\n\t\tprevId = entry.id;\n\n\t\t// Convert firstKeptEntryIndex to firstKeptEntryId for compaction\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };\n\t\t\tif (typeof comp.firstKeptEntryIndex === \"number\") {\n\t\t\t\tconst targetEntry = entries[comp.firstKeptEntryIndex];\n\t\t\t\tif (targetEntry && targetEntry.type !== \"session\") {\n\t\t\t\t\tcomp.firstKeptEntryId = targetEntry.id;\n\t\t\t\t}\n\t\t\t\tdelete comp.firstKeptEntryIndex;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */\nfunction migrateV2ToV3(entries: FileEntry[]): void {\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 3;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Update message entries with hookMessage role\n\t\tif (entry.type === \"message\") {\n\t\t\tconst msgEntry = entry as SessionMessageEntry;\n\t\t\tif (msgEntry.message && (msgEntry.message as { role: string }).role === \"hookMessage\") {\n\t\t\t\t(msgEntry.message as { role: string }).role = \"custom\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run all necessary migrations to bring entries to current version.\n * Mutates entries in place. Returns true if any migration was applied.\n */\nfunction migrateToCurrentVersion(entries: FileEntry[]): boolean {\n\tconst header = entries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\tconst version = header?.version ?? 1;\n\n\tif (version >= CURRENT_SESSION_VERSION) return false;\n\n\tif (version < 2) migrateV1ToV2(entries);\n\tif (version < 3) migrateV2ToV3(entries);\n\n\treturn true;\n}\n\n/** Exported for testing */\nexport function migrateSessionEntries(entries: FileEntry[]): void {\n\tmigrateToCurrentVersion(entries);\n}\n\n/** Exported for compaction.test.ts */\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tconst lines = content.trim().split(\"\\n\");\n\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\ttry {\n\t\t\tconst entry = JSON.parse(line) as FileEntry;\n\t\t\tentries.push(entry);\n\t\t} catch {\n\t\t\t// Skip malformed lines\n\t\t}\n\t}\n\n\treturn entries;\n}\n\nexport function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tif (entries[i].type === \"compaction\") {\n\t\t\treturn entries[i] as CompactionEntry;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction buildEntryIndex(entries: SessionEntry[], byId?: Map<string, SessionEntry>): Map<string, SessionEntry> {\n\tif (byId) return byId;\n\tconst index = new Map<string, SessionEntry>();\n\tfor (const entry of entries) {\n\t\tindex.set(entry.id, entry);\n\t}\n\treturn index;\n}\n\nfunction buildSessionPath(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionEntry[] {\n\tconst index = buildEntryIndex(entries, byId);\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\treturn [];\n\t}\n\tif (leafId) {\n\t\tleaf = index.get(leafId);\n\t}\n\tleaf ??= entries[entries.length - 1];\n\tif (!leaf) {\n\t\treturn [];\n\t}\n\n\tconst path: SessionEntry[] = [];\n\tlet current: SessionEntry | undefined = leaf;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? index.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nfunction getSessionContextSettings(path: SessionEntry[]): Pick<SessionContext, \"thinkingLevel\" | \"model\"> {\n\tlet thinkingLevel = \"off\";\n\t// 显式 /model 切换(model_change)优先于回合推导:assistant 消息的 provider 只\n\t// 反映\"当时用了什么\",若让它按顺序覆盖显式切换,一次错误的恢复回合会把用户\n\t// 的切换永久毒化(dogfood 2026-09-25 实测)。没有显式切换时才回退到最近回合\n\t// 实际使用的模型。\n\tlet explicitModel: { provider: string; modelId: string } | null = null;\n\tlet derivedModel: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\texplicitModel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tderivedModel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\treturn { thinkingLevel, model: explicitModel ?? derivedModel };\n}\n\n/**\n * Assistant messages that ended in error, were aborted, or are deferred are\n * runtime outcomes, not conversation content. They stay in the session file\n * for history and rendering of the live turn, but must not re-enter the model\n * context on rebuild (compaction, tree navigation, resume).\n */\nfunction isContextMessage(message: AgentMessage): boolean {\n\treturn (\n\t\tmessage.role !== \"assistant\" ||\n\t\t(message.stopReason !== \"error\" && message.stopReason !== \"aborted\" && message.stopReason !== \"deferred\")\n\t);\n}\n\n/**\n * Backfill dangling toolCalls left by a crash or force-kill between an\n * assistant message and its toolResult messages: providers reject that\n * half-paired sequence on resume. Mirroring the live cancel path\n * (failUnexecutedToolCalls), each dangling call gets one deterministic error\n * toolResult inserted immediately after its assistant message — the position\n * providers require for tool_call/tool_result pairing. This is a pure\n * in-memory projection repair; the session file is never rewritten.\n *\n * O(n) over the projected sequence and idempotent: the synthetic results are\n * derived from fixed session data (the assistant message's timestamp, not\n * Date.now()), and a sequence without dangling calls is returned unchanged\n * (same reference).\n */\nfunction backfillDanglingToolResults(messages: AgentMessage[]): AgentMessage[] {\n\tconst answeredToolCallIds = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role === \"toolResult\") answeredToolCallIds.add(message.toolCallId);\n\t}\n\n\tconst repaired: AgentMessage[] = [];\n\tlet changed = false;\n\tfor (const message of messages) {\n\t\trepaired.push(message);\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst danglingCalls = message.content.filter(\n\t\t\t\t(block): block is ToolCall => block.type === \"toolCall\" && !answeredToolCallIds.has(block.id),\n\t\t\t);\n\t\t\tif (danglingCalls.length > 0) {\n\t\t\t\tfor (const call of danglingCalls) {\n\t\t\t\t\tansweredToolCallIds.add(call.id);\n\t\t\t\t\trepaired.push(createInterruptedToolResultMessage(call, message.timestamp));\n\t\t\t\t}\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Project one selected session entry into LLM/runtime messages.\n * Plain custom entries are display/state entries and do not participate in context.\n */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") {\n\t\tconst message = entry.message;\n\t\t// Session files are parsed without validation; old versions, forks, or\n\t\t// hand-edited files can contain messages with null/missing content.\n\t\tif (\n\t\t\t(message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") &&\n\t\t\tmessage.content == null\n\t\t) {\n\t\t\treturn [{ ...message, content: [] }];\n\t\t}\n\t\treturn [message];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];\n\t}\n\treturn [];\n}\n\n/**\n * Build the active, compaction-aware session entry list.\n *\n * This follows the current leaf path. If the path contains compaction entries,\n * the latest compaction is represented by the compaction entry itself, followed\n * by the kept entries starting at firstKeptEntryId and all entries after the\n * compaction entry. Older summarized entries are omitted.\n */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionEntry[] {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tif (!compaction) {\n\t\treturn path;\n\t}\n\n\tconst compactionIdx = path.findIndex((entry) => entry.id === compaction.id);\n\tif (compactionIdx < 0) {\n\t\treturn path;\n\t}\n\n\tconst contextEntries: SessionEntry[] = [compaction];\n\tlet foundFirstKept = false;\n\tfor (let i = 0; i < compactionIdx; i++) {\n\t\tconst entry = path[i];\n\t\tif (entry.id === compaction.firstKeptEntryId) {\n\t\t\tfoundFirstKept = true;\n\t\t}\n\t\tif (foundFirstKept) {\n\t\t\tcontextEntries.push(entry);\n\t\t}\n\t}\n\tcontextEntries.push(...path.slice(compactionIdx + 1));\n\treturn contextEntries;\n}\n\n/**\n * A registered generic transform over the projected session entry list.\n * Registered per SessionManager instance via {@link registerEntryProjection};\n * the kernel applies whatever projections are registered during context\n * projection and knows nothing about any specific one.\n */\nexport interface SessionEntryProjection {\n\t/** The plugin-owned custom entry type this projection is associated with. */\n\treadonly customType: string;\n\treadonly project: (entries: SessionEntry[]) => SessionEntry[];\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Handles compaction and branch summaries along the path.\n *\n * `entryProjections` are REGISTERED generic transforms (see\n * {@link SessionManager.registerEntryProjection}): each receives the projected\n * entry list and may replace entries (e.g. a policy plugin eliding bulky old\n * tool results). The kernel applies whatever projections are registered and\n * knows nothing about any specific one.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n\tentryProjections?: readonly SessionEntryProjection[],\n): SessionContext {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tconst { thinkingLevel, model } = getSessionContextSettings(path);\n\t// The filter lives here, not in sessionEntryToContextMessages: rendering\n\t// reuses this projection and must still show failed turns after a reload.\n\tconst contextEntries = buildContextEntries(entries, leafId, byId);\n\tconst projected =\n\t\tentryProjections === undefined ? contextEntries : applyEntryProjections(contextEntries, entryProjections);\n\tconst messages = backfillDanglingToolResults(\n\t\tprojected.flatMap(sessionEntryToContextMessages).filter(isContextMessage),\n\t);\n\treturn { messages, thinkingLevel, model };\n}\n\nfunction applyEntryProjections(\n\tentries: SessionEntry[],\n\tprojections: readonly SessionEntryProjection[],\n): SessionEntry[] {\n\tlet projected = entries;\n\tfor (const projection of projections) {\n\t\tprojected = projection.project(projected);\n\t}\n\treturn projected;\n}\n\n/**\n * Compute the default session directory for a cwd.\n * Encodes cwd into a safe directory name under ~/.agent-forge/agent/sessions/.\n */\nfunction getDefaultSessionDirPath(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst safePath = `--${resolvedCwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\treturn join(resolvedAgentDir, \"sessions\", safePath);\n}\n\nexport function getDefaultSessionDir(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst sessionDir = getDefaultSessionDirPath(cwd, agentDir);\n\tif (!existsSync(sessionDir)) {\n\t\tmkdirSync(sessionDir, { recursive: true });\n\t}\n\treturn sessionDir;\n}\n\n/**\n * Compute the trace file path paired with a session file path: the single\n * source of truth for the session/trace pairing convention (X.jsonl ->\n * X.trace.jsonl in the same directory).\n *\n * A trailing \".jsonl\" (case-sensitive, matching how this codebase generates\n * session file names) is replaced with \".trace.jsonl\"; any other path gets\n * \".trace.jsonl\" appended. Idempotent by convention: an input already ending\n * in \".trace.jsonl\" is returned unchanged, so applying the mapping twice\n * cannot produce \".trace.jsonl.trace.jsonl\".\n *\n * Pure function: no IO, no state, no filesystem access.\n */\nexport function getTraceFilePathForSession(sessionFilePath: string): string {\n\tif (sessionFilePath.endsWith(\".trace.jsonl\")) {\n\t\treturn sessionFilePath;\n\t}\n\tif (sessionFilePath.endsWith(\".jsonl\")) {\n\t\treturn `${sessionFilePath.slice(0, -\".jsonl\".length)}.trace.jsonl`;\n\t}\n\treturn `${sessionFilePath}.trace.jsonl`;\n}\n\nfunction parseSessionEntryLine(line: string): FileEntry | null {\n\tif (!line.trim()) return null;\n\ttry {\n\t\treturn JSON.parse(line) as FileEntry;\n\t} catch {\n\t\t// Skip malformed lines\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing; delegates to the default file storage provider. */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\treturn FileSessionStorageProvider.instance.loadEntries(filePath);\n}\n\nfunction readSessionHeaderForDiscovery(storage: SessionStorageProvider, filePath: string): SessionHeader | null {\n\ttry {\n\t\treturn storage.readHeader(filePath);\n\t} catch {\n\t\t// Discovery is best-effort: unreadable or oversized files are not sessions,\n\t\t// and one corrupt file must not prevent other sessions from being found.\n\t\treturn null;\n\t}\n}\n\nfunction getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\nfunction sessionCwdMatches(cwd: string | undefined, resolvedCwd: string): boolean {\n\treturn cwd !== undefined && cwd !== \"\" && resolvePath(cwd) === resolvedCwd;\n}\n\nfunction findMostRecentSessionWithStorage(\n\tstorage: SessionStorageProvider,\n\tsessionDir: string,\n\tcwd?: string,\n): string | null {\n\tconst resolvedCwd = cwd ? resolvePath(cwd) : undefined;\n\ttry {\n\t\tconst files = storage\n\t\t\t.listSessionFiles(sessionDir)\n\t\t\t.map((path) => ({ path, mtime: storage.modifiedTime(path).getTime() }))\n\t\t\t.sort((a, b) => b.mtime - a.mtime);\n\n\t\t// mtime-ordered short-circuit: only the newest files need a header read\n\t\t// before one matches, instead of reading every header up front.\n\t\tfor (const { path } of files) {\n\t\t\tconst header = readSessionHeaderForDiscovery(storage, path);\n\t\t\tif (header && (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd))) return path;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\t// Directory access and stat races make recent-session discovery unavailable.\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing; delegates to the default file storage provider. */\nexport function findMostRecentSession(sessionDir: string, cwd?: string): string | null {\n\treturn findMostRecentSessionWithStorage(FileSessionStorageProvider.instance, sessionDir, cwd);\n}\n\nfunction isMessageWithContent(message: AgentMessage): message is Message {\n\treturn typeof (message as Message).role === \"string\" && \"content\" in message;\n}\n\nfunction extractTextContent(message: Message): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\" \");\n}\n\nfunction getMessageActivityTime(entry: SessionMessageEntry): number | undefined {\n\tconst message = entry.message;\n\tif (!isMessageWithContent(message)) return undefined;\n\tif (message.role !== \"user\" && message.role !== \"assistant\") return undefined;\n\n\tconst msgTimestamp = (message as { timestamp?: number }).timestamp;\n\tif (typeof msgTimestamp === \"number\") {\n\t\treturn msgTimestamp;\n\t}\n\n\tconst t = new Date(entry.timestamp).getTime();\n\treturn Number.isNaN(t) ? undefined : t;\n}\n\nasync function buildSessionInfo(\n\tfilePath: string,\n\tsignal?: AbortSignal,\n\tfileStats?: Stats,\n): Promise<SessionInfo | null> {\n\ttry {\n\t\tconst stats = fileStats ?? (await stat(filePath));\n\t\tlet header: SessionHeader | null = null;\n\t\tlet messageCount = 0;\n\t\tlet firstMessage = \"\";\n\t\tconst allMessages: string[] = [];\n\t\tlet name: string | undefined;\n\t\tlet lastActivityTime: number | undefined;\n\n\t\tconst rl = createInterface({\n\t\t\tinput: createReadStream(filePath, { encoding: \"utf8\", signal }),\n\t\t\tcrlfDelay: Infinity,\n\t\t});\n\n\t\tfor await (const line of rl) {\n\t\t\tconst entry = parseSessionEntryLine(line);\n\t\t\tif (!entry) continue;\n\n\t\t\tif (!header) {\n\t\t\t\tif (entry.type !== \"session\") return null;\n\t\t\t\theader = entry;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract session name (use latest, including explicit clears)\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\tname = entry.name?.trim() || undefined;\n\t\t\t}\n\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tmessageCount++;\n\n\t\t\tconst activityTime = getMessageActivityTime(entry);\n\t\t\tif (typeof activityTime === \"number\") {\n\t\t\t\tlastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);\n\t\t\t}\n\n\t\t\tconst message = entry.message;\n\t\t\tif (!isMessageWithContent(message)) continue;\n\t\t\tif (message.role !== \"user\" && message.role !== \"assistant\") continue;\n\n\t\t\tconst textContent = extractTextContent(message);\n\t\t\tif (!textContent) continue;\n\n\t\t\tallMessages.push(textContent);\n\t\t\tif (!firstMessage && message.role === \"user\") {\n\t\t\t\tfirstMessage = textContent;\n\t\t\t}\n\t\t}\n\n\t\tif (!header) return null;\n\n\t\tconst cwd = typeof header.cwd === \"string\" ? header.cwd : \"\";\n\t\tconst parentSessionPath = header.parentSession;\n\t\t// Same guard style as cwd: parsed headers are untyped, so non-string\n\t\t// values (hand-edited files) read back as missing.\n\t\tconst profileId = typeof header.profileId === \"string\" ? header.profileId : undefined;\n\t\tconst profileVersion = typeof header.profileVersion === \"string\" ? header.profileVersion : undefined;\n\t\tconst headerTime = typeof header.timestamp === \"string\" ? new Date(header.timestamp).getTime() : NaN;\n\t\tconst modified =\n\t\t\ttypeof lastActivityTime === \"number\" && lastActivityTime > 0\n\t\t\t\t? new Date(lastActivityTime)\n\t\t\t\t: !Number.isNaN(headerTime)\n\t\t\t\t\t? new Date(headerTime)\n\t\t\t\t\t: stats.mtime;\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tid: header.id,\n\t\t\tcwd,\n\t\t\tname,\n\t\t\tparentSessionPath,\n\t\t\tprofileId,\n\t\t\tprofileVersion,\n\t\t\tcreated: new Date(header.timestamp),\n\t\t\tmodified,\n\t\t\tmessageCount,\n\t\t\tfirstMessage: firstMessage || \"(no messages)\",\n\t\t\tallMessagesText: allMessages.join(\" \"),\n\t\t};\n\t} catch {\n\t\tsignal?.throwIfAborted();\n\t\treturn null;\n\t}\n}\n\nexport type SessionListProgress = (\n\tloaded: number,\n\ttotal: number,\n\t/** Sessions loaded so far, sorted by activity. Present on periodic updates. */\n\tpartialSessions?: readonly SessionInfo[],\n) => void;\n\nconst MAX_CONCURRENT_SESSION_INFO_LOADS = 10;\nconst MAX_CONCURRENT_SESSION_DISCOVERY_LOADS = 64;\nconst CURRENT_SESSION_LIST_PUBLISH_INTERVAL = 10;\nconst ALL_SESSION_LIST_PUBLISH_INTERVAL = 100;\n\ninterface SessionFileCandidate {\n\tpath: string;\n\tstats?: Stats;\n}\n\nasync function mapWithConcurrency<T, R>(\n\titems: T[],\n\tlimit: number,\n\tmap: (item: T, index: number) => Promise<R>,\n\tsignal?: AbortSignal,\n): Promise<R[]> {\n\tconst results = new Array<R>(items.length);\n\tlet nextIndex = 0;\n\tconst worker = async (): Promise<void> => {\n\t\twhile (nextIndex < items.length) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tconst index = nextIndex++;\n\t\t\tresults[index] = await map(items[index]!, index);\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));\n\treturn results;\n}\n\nfunction sortSessionInfos(sessions: SessionInfo[]): SessionInfo[] {\n\treturn sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n}\n\nfunction buildSessionInfosWithConcurrency(\n\tfiles: SessionFileCandidate[],\n\tonLoaded: (info: SessionInfo | null, index: number) => void,\n\tsignal?: AbortSignal,\n): Promise<(SessionInfo | null)[]> {\n\treturn mapWithConcurrency(\n\t\tfiles,\n\t\tMAX_CONCURRENT_SESSION_INFO_LOADS,\n\t\tasync (file, index) => {\n\t\t\tconst info = await buildSessionInfo(file.path, signal, file.stats);\n\t\t\tonLoaded(info, index);\n\t\t\treturn info;\n\t\t},\n\t\tsignal,\n\t);\n}\n\nasync function listSessionsFromDir(\n\tdir: string,\n\tonProgress?: SessionListProgress,\n\tsignal?: AbortSignal,\n): Promise<SessionInfo[]> {\n\tsignal?.throwIfAborted();\n\tif (!existsSync(dir)) return [];\n\n\ttry {\n\t\tconst dirEntries = await readdir(dir);\n\t\tconst files = dirEntries\n\t\t\t.filter((file) => file.endsWith(\".jsonl\"))\n\t\t\t.sort((a, b) => b.localeCompare(a))\n\t\t\t.map((file) => ({ path: join(dir, file) }));\n\t\tconst total = files.length;\n\t\tconst partialSessions: SessionInfo[] = [];\n\t\tlet loaded = 0;\n\t\tconst results = await buildSessionInfosWithConcurrency(\n\t\t\tfiles,\n\t\t\t(info) => {\n\t\t\t\tloaded++;\n\t\t\t\tif (info) partialSessions.push(info);\n\t\t\t\tconst publishPartial =\n\t\t\t\t\tloaded === 1 || loaded % CURRENT_SESSION_LIST_PUBLISH_INTERVAL === 0 || loaded === total;\n\t\t\t\tonProgress?.(loaded, total, publishPartial ? sortSessionInfos([...partialSessions]) : undefined);\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\treturn results.filter((info): info is SessionInfo => info !== null);\n\t} catch {\n\t\tsignal?.throwIfAborted();\n\t\treturn [];\n\t}\n}\n\n/**\n * Manages conversation sessions as append-only trees stored in JSONL files.\n *\n * Each session entry has an id and parentId forming a tree structure. The \"leaf\"\n * pointer tracks the current position. Appending creates a child of the current leaf.\n * Branching moves the leaf to an earlier entry, allowing new branches without\n * modifying history.\n *\n * Use buildSessionContext() to get the resolved message list for the LLM, which\n * handles compaction summaries and follows the path from root to current leaf.\n */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate entryProjections: SessionEntryProjection[] = [];\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 compactionOperations: Map<string, CompactionEntry> = new Map();\n\tprivate leafId: string | null = null;\n\tprivate readonly storage: SessionStorageProvider;\n\t/** Cross-process write-arbitration identity (D-067 phase 2 S5); assigned lazily. */\n\tprivate storageWriterId: string | undefined;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t\tpreloadedFileEntries?: FileEntry[],\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tthis.storage = storage;\n\t\tif (persist && this.sessionDir) {\n\t\t\tthis.storage.ensureDir(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis._setSessionFile(sessionFile, preloadedFileEntries);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis._setSessionFile(sessionFile);\n\t}\n\n\tprivate _setSessionFile(sessionFile: string, preloadedFileEntries?: FileEntry[]): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (this.storage.exists(this.sessionFile)) {\n\t\t\tthis.fileEntries = preloadedFileEntries ?? this.storage.loadEntries(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was\n\t\t\t// non-empty but did not parse as a valid Agent Forge session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (this.storage.size(explicitPath) > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid ${APP_NAME} session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: this.sessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: options?.parentSession,\n\t\t\t// Optional profile lock: omit the keys entirely when absent so the\n\t\t\t// header matches the \"optional field\" semantics end to end.\n\t\t\t...(options?.profileId === undefined ? {} : { profileId: options.profileId }),\n\t\t\t...(options?.profileVersion === undefined ? {} : { profileVersion: options.profileVersion }),\n\t\t\t// 子代理血缘(可选,见 SessionHeader)\n\t\t\t...(options?.parentAgentSession === undefined ? {} : { parentAgentSession: options.parentAgentSession }),\n\t\t\t...(options?.agentRole === undefined ? {} : { agentRole: options.agentRole }),\n\t\t\t// 回合级血缘(可选,见 SessionHeader):缺席时键整个省略。\n\t\t\t...(options?.parentTraceId === undefined ? {} : { parentTraceId: options.parentTraceId }),\n\t\t};\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.compactionOperations.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\t\tthis.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.compactionOperations.clear();\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"session\") continue;\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t\tif (entry.type === \"compaction\" && entry.operationId !== undefined) {\n\t\t\t\tif (typeof entry.operationId !== \"string\" || entry.operationId.trim() === \"\") {\n\t\t\t\t\tthrow new Error(`Invalid compaction operationId in session entry: ${entry.id}`);\n\t\t\t\t}\n\t\t\t\tif (this.compactionOperations.has(entry.operationId)) {\n\t\t\t\t\tthrow new Error(`Duplicate compaction operationId in session: ${entry.operationId}`);\n\t\t\t\t}\n\t\t\t\tthis.compactionOperations.set(entry.operationId, entry);\n\t\t\t}\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tif (entry.label) {\n\t\t\t\t\tthis.labelsById.set(entry.targetId, entry.label);\n\t\t\t\t\tthis.labelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t\t} else {\n\t\t\t\t\tthis.labelsById.delete(entry.targetId);\n\t\t\t\t\tthis.labelTimestampsById.delete(entry.targetId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.assertWritable();\n\t\tthis.storage.rewrite(this.sessionFile, this.fileEntries);\n\t}\n\n\t/**\n\t * Cross-process write arbitration (D-067 phase 2 S5): a conflicting live\n\t * foreign owner fails the write explicitly — concurrent writers must never\n\t * silently fork the session history. Dead owners (closed or crashed\n\t * processes) are taken over and same-process writers are allowed by the\n\t * guard itself; the append rollback below keeps memory consistent when it\n\t * throws.\n\t */\n\tprivate assertWritable(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.storageWriterId ??= randomUUID();\n\t\tthis.storage.guard?.ensureWritable(this.sessionFile, this.storageWriterId);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\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 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\t/** Return a stable host fact for optimistic session operations. */\n\tgetRevision(): SessionRevisionV1 {\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tsessionId: this.sessionId,\n\t\t\tsequence: Math.max(0, this.fileEntries.length - 1),\n\t\t\tleafId: this.leafId,\n\t\t};\n\t}\n\n\t/**\n\t * A new session file is created only once the session contains a user or assistant message.\n\t * Setup entries alone (model, thinking level) stay in memory so opening and closing without\n\t * chatting leaves no file behind. Starting at the user message (not the first assistant\n\t * reply) keeps the prompt on disk if the first turn never completes.\n\t */\n\tprivate _hasConversation(): boolean {\n\t\treturn this.fileEntries.some(\n\t\t\t(e) => e.type === \"message\" && (e.message.role === \"user\" || e.message.role === \"assistant\"),\n\t\t);\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tthis.assertWritable();\n\n\t\tif (!this.flushed) {\n\t\t\tif (!this._hasConversation()) return;\n\t\t\tthis.storage.createExclusive(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tthis.storage.append(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tconst previousEntries = this.fileEntries.slice();\n\t\tconst previousById = new Map(this.byId);\n\t\tconst previousLeafId = this.leafId;\n\t\tconst previousFlushed = this.flushed;\n\t\tconst sessionFile = this.sessionFile;\n\t\tconst fileExisted = sessionFile !== undefined && this.storage.exists(sessionFile);\n\t\tconst previousFileSize = fileExisted ? this.storage.size(sessionFile as string) : undefined;\n\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\ttry {\n\t\t\tthis._persist(entry);\n\t\t} catch (error) {\n\t\t\tthis.fileEntries = previousEntries;\n\t\t\tthis.byId = previousById;\n\t\t\tthis.leafId = previousLeafId;\n\t\t\tthis.flushed = previousFlushed;\n\n\t\t\ttry {\n\t\t\t\tif (sessionFile && previousFileSize !== undefined) {\n\t\t\t\t\tthis.storage.truncate(sessionFile, previousFileSize);\n\t\t\t\t} else if (sessionFile && !fileExisted && this.storage.exists(sessionFile)) {\n\t\t\t\t\t// The first flushed append may create the session file. Remove only\n\t\t\t\t\t// the file created by this failed append.\n\t\t\t\t\tthis.storage.remove(sessionFile);\n\t\t\t\t}\n\t\t\t} catch (rollbackError) {\n\t\t\t\tthrow new AggregateError([error, rollbackError], \"Session append failed and rollback failed\");\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id.\n\t * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.\n\t * Reason: we want these to be top-level entries in the session, not message session entries,\n\t * so it is easier to find them.\n\t * These need to be appended via appendCompaction() and appendBranchSummary() methods.\n\t */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry: SessionMessageEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\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): string {\n\t\tconst entry: ThinkingLevelChangeEntry = {\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry: ModelChangeEntry = {\n\t\t\ttype: \"model_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tconst entry: CompactionEntry<T> = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Commit one compaction entry against an exact session revision.\n\t *\n\t * This is deliberately a host-only single-append boundary. It does not\n\t * orchestrate compaction, replace context, or form a cross-plugin\n\t * transaction.\n\t */\n\tcommitCompaction<TDetails = unknown>(request: CompactionCommitRequestV1<TDetails>): CompactionCommitResultV1 {\n\t\tthis._validateCompactionCommitRequest(request);\n\n\t\tconst previousOperation = this.compactionOperations.get(request.operationId);\n\t\tif (previousOperation) {\n\t\t\tif (this._matchesCompactionCommitRequest(previousOperation, request)) {\n\t\t\t\treturn {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstatus: \"replayed\",\n\t\t\t\t\tentryId: previousOperation.id,\n\t\t\t\t\trevision: this._revisionAfterEntry(previousOperation),\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(`operation_id_reused: ${request.operationId}`);\n\t\t}\n\n\t\tconst currentRevision = this.getRevision();\n\t\tif (!sameSessionRevision(request.expectedRevision, currentRevision)) {\n\t\t\treturn { version: 1, status: \"revision_conflict\", currentRevision };\n\t\t}\n\n\t\tconst currentBranchContainsFirstKeptEntry = this.getBranch().some(\n\t\t\t(entry) => entry.id === request.firstKeptEntryId,\n\t\t);\n\t\tif (!currentBranchContainsFirstKeptEntry) {\n\t\t\tthrow new Error(`first_kept_entry_not_on_current_branch: ${request.firstKeptEntryId}`);\n\t\t}\n\n\t\tconst entry: CompactionEntry = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\toperationId: request.operationId,\n\t\t\tsummary: request.summary,\n\t\t\tfirstKeptEntryId: request.firstKeptEntryId,\n\t\t\ttokensBefore: request.tokensBefore,\n\t\t\tdetails: request.details,\n\t\t\tusage: request.usage as Usage | undefined,\n\t\t\tfromHook: request.fromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tthis.compactionOperations.set(request.operationId, entry);\n\t\treturn { version: 1, status: \"committed\", entryId: entry.id, revision: this.getRevision() };\n\t}\n\n\tprivate _validateCompactionCommitRequest(request: CompactionCommitRequestV1): void {\n\t\tif (!request || typeof request !== \"object\") throw new Error(\"Compaction commit request must be an object\");\n\t\tif (request.version !== 1) throw new Error(\"Unsupported compaction commit request version\");\n\t\tif (typeof request.operationId !== \"string\" || request.operationId.trim() === \"\") {\n\t\t\tthrow new Error(\"operationId must be a non-empty string\");\n\t\t}\n\t\tif (typeof request.summary !== \"string\" || request.summary.trim() === \"\") {\n\t\t\tthrow new Error(\"summary must be a non-empty string\");\n\t\t}\n\t\tif (typeof request.firstKeptEntryId !== \"string\" || request.firstKeptEntryId === \"\") {\n\t\t\tthrow new Error(\"firstKeptEntryId must be a non-empty string\");\n\t\t}\n\t\tif (\n\t\t\ttypeof request.tokensBefore !== \"number\" ||\n\t\t\t!Number.isFinite(request.tokensBefore) ||\n\t\t\trequest.tokensBefore < 0\n\t\t) {\n\t\t\tthrow new Error(\"tokensBefore must be a non-negative finite number\");\n\t\t}\n\t\tif (request.details !== undefined) assertJsonSerializable(request.details, \"details\");\n\t\tif (request.usage !== undefined) assertJsonSerializable(request.usage, \"usage\");\n\t\tconst revision = request.expectedRevision;\n\t\tif (\n\t\t\trevision?.version !== 1 ||\n\t\t\ttypeof revision.sessionId !== \"string\" ||\n\t\t\trevision.sessionId === \"\" ||\n\t\t\t!Number.isInteger(revision.sequence) ||\n\t\t\trevision.sequence < 0 ||\n\t\t\t(revision.leafId !== null && typeof revision.leafId !== \"string\")\n\t\t) {\n\t\t\tthrow new Error(\"expectedRevision must be a valid SessionRevisionV1\");\n\t\t}\n\t}\n\n\tprivate _matchesCompactionCommitRequest<TDetails>(\n\t\tentry: CompactionEntry,\n\t\trequest: CompactionCommitRequestV1<TDetails>,\n\t): boolean {\n\t\tconst entryIndex = this.fileEntries.indexOf(entry);\n\t\tif (entryIndex <= 0) throw new Error(`Compaction operation entry is missing: ${entry.id}`);\n\t\treturn (\n\t\t\trequest.expectedRevision.version === 1 &&\n\t\t\trequest.expectedRevision.sessionId === this.sessionId &&\n\t\t\trequest.expectedRevision.sequence === entryIndex - 1 &&\n\t\t\trequest.expectedRevision.leafId === entry.parentId &&\n\t\t\trequest.summary === entry.summary &&\n\t\t\trequest.firstKeptEntryId === entry.firstKeptEntryId &&\n\t\t\trequest.tokensBefore === entry.tokensBefore &&\n\t\t\trequest.fromHook === entry.fromHook &&\n\t\t\tisDeepStrictEqual(request.details, entry.details) &&\n\t\t\tisDeepStrictEqual(request.usage, entry.usage)\n\t\t);\n\t}\n\n\tprivate _revisionAfterEntry(entry: CompactionEntry): SessionRevisionV1 {\n\t\tconst entryIndex = this.fileEntries.indexOf(entry);\n\t\tif (entryIndex <= 0) throw new Error(`Compaction operation entry is missing: ${entry.id}`);\n\t\treturn { version: 1, sessionId: this.sessionId, sequence: entryIndex, leafId: entry.id };\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry: CustomEntry = {\n\t\t\ttype: \"custom\",\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst sanitizedName = name.replace(/[\\r\\n]+/g, \" \").trim();\n\t\tconst entry: SessionInfoEntry = {\n\t\t\ttype: \"session_info\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: sanitizedName,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\t// Walk entries in reverse to find the latest session_info entry.\n\t\t// Empty names explicitly clear the session title.\n\t\tconst entries = this.getEntries();\n\t\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = entries[i];\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\treturn entry.name?.trim() || undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Append a custom message entry (for extensions) that participates in LLM context.\n\t * @param customType Extension identifier for filtering on reload\n\t * @param content Message content (string or TextContent/ImageContent array)\n\t * @param display Whether to show in TUI (true = styled display, false = hidden)\n\t * @param details Optional extension-specific metadata (not sent to LLM)\n\t * @returns Entry id\n\t */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): string {\n\t\tconst entry: CustomMessageEntry<T> = {\n\t\t\ttype: \"custom_message\",\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t// =========================================================================\n\t// Tree Traversal\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/**\n\t * Get all direct children of an entry.\n\t */\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/**\n\t * Get the label for an entry, if any.\n\t */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/**\n\t * Set or clear a label on an entry.\n\t * Labels are user-defined markers for bookmarking/navigation.\n\t * Pass undefined or empty string to clear the label.\n\t */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Walk from entry to root, returning all entries in path order.\n\t * Includes all entry types (messages, compaction, model changes, etc.).\n\t * Use buildSessionContext() to get the resolved messages for the LLM.\n\t */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\tconst path: SessionEntry[] = [];\n\t\tconst startId = fromId ?? this.leafId;\n\t\tlet current = startId ? this.byId.get(startId) : undefined;\n\t\twhile (current) {\n\t\t\tpath.push(current);\n\t\t\tcurrent = current.parentId ? this.byId.get(current.parentId) : undefined;\n\t\t}\n\t\tpath.reverse();\n\t\treturn path;\n\t}\n\n\t/**\n\t * Build the active, compaction-aware entry list for context/rendering.\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Build the session context (what gets sent to the LLM).\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId, this.entryProjections);\n\t}\n\n\t/**\n\t * Registers a GENERIC entry projection applied during context projection\n\t * (see {@link buildSessionContext}). The kernel neither interprets nor\n\t * persists projections — plugins own their semantics and remove them via\n\t * the returned disposer. Same channel for first-party and third-party\n\t * plugins; the `customType` is the plugin-owned entry type the projection\n\t * is associated with (used for diagnostics only).\n\t */\n\tregisterEntryProjection(projection: SessionEntryProjection): () => void {\n\t\tthis.entryProjections.push(projection);\n\t\treturn () => {\n\t\t\tconst index = this.entryProjections.indexOf(projection);\n\t\t\tif (index >= 0) this.entryProjections.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Get session header.\n\t */\n\tgetHeader(): SessionHeader | null {\n\t\tconst h = this.fileEntries.find((e) => e.type === \"session\");\n\t\treturn h ? (h as SessionHeader) : null;\n\t}\n\n\t/**\n\t * Get all session entries (excludes header). Returns a shallow copy.\n\t * The session is append-only: use appendXXX() to add entries, branch() to\n\t * change the leaf pointer. Entries cannot be modified or deleted.\n\t */\n\tgetEntries(): SessionEntry[] {\n\t\treturn this.fileEntries.filter((e): e is SessionEntry => e.type !== \"session\");\n\t}\n\n\t/**\n\t * Get the session as a tree structure. Returns a shallow defensive copy of all entries.\n\t * A well-formed session has exactly one root (first entry with parentId === null).\n\t * Orphaned entries (broken parent chain) are also returned as roots.\n\t */\n\tgetTree(): SessionTreeNode[] {\n\t\tconst entries = this.getEntries();\n\t\tconst nodeMap = new Map<string, SessionTreeNode>();\n\t\tconst roots: SessionTreeNode[] = [];\n\n\t\t// Create nodes with resolved labels\n\t\tfor (const entry of entries) {\n\t\t\tconst label = this.labelsById.get(entry.id);\n\t\t\tconst labelTimestamp = this.labelTimestampsById.get(entry.id);\n\t\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t\t}\n\n\t\t// Build tree\n\t\tfor (const entry of entries) {\n\t\t\tconst node = nodeMap.get(entry.id)!;\n\t\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\t\troots.push(node);\n\t\t\t} else {\n\t\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(node);\n\t\t\t\t} else {\n\t\t\t\t\t// Orphan - treat as root\n\t\t\t\t\troots.push(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Sort children by timestamp (oldest first, newest at bottom)\n\t\t// Use iterative approach to avoid stack overflow on deep trees\n\t\tconst stack: SessionTreeNode[] = [...roots];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop()!;\n\t\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\t\tstack.push(...node.children);\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\t// =========================================================================\n\t// Branching\n\t// =========================================================================\n\n\t/**\n\t * Start a new branch from an earlier entry.\n\t * Moves the leaf pointer to the specified entry. The next appendXXX() call\n\t * will create a child of that entry, forming a new branch. Existing entries\n\t * are not modified or deleted.\n\t */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/**\n\t * Reset the leaf pointer to null (before any entries).\n\t * The next appendXXX() call will create a new root entry (parentId = null).\n\t * Use this when navigating to re-edit the first user message.\n\t */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/**\n\t * Start a new branch with a summary of the abandoned path.\n\t * Same as branch(), but also appends a branch_summary entry that captures\n\t * context from the abandoned conversation path.\n\t */\n\tbranchWithSummary(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: unknown,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tconst fromId = this.leafId ?? \"root\";\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = {\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: branchFromId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId,\n\t\t\tsummary,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Create a new session file containing only the path from root to the specified leaf.\n\t * Useful for extracting a single conversation path from a branched session.\n\t * Returns the new session file path, or undefined if not persisting.\n\t */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst previousSessionFile = this.sessionFile;\n\t\tconst path = this.getBranch(leafId);\n\t\tif (path.length === 0) {\n\t\t\tthrow new Error(`Entry ${leafId} not found`);\n\t\t}\n\n\t\t// Filter out LabelEntry from path - we'll recreate them from the resolved map.\n\t\t// Because labels are real tree entries, later entries can be children of labels;\n\t\t// removing labels requires re-chaining the retained path to avoid orphaned subtrees.\n\t\tconst pathWithoutLabels: SessionEntry[] = [];\n\t\tconst replacementByLabelId = new Map<string, string>();\n\t\tconst pendingLabelIds: string[] = [];\n\t\tlet pathParentId: string | null = null;\n\t\tfor (const entry of path) {\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tpendingLabelIds.push(entry.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const labelId of pendingLabelIds) {\n\t\t\t\treplacementByLabelId.set(labelId, entry.id);\n\t\t\t}\n\t\t\tpendingLabelIds.length = 0;\n\t\t\tpathWithoutLabels.push(\n\t\t\t\tentry.type === \"compaction\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...entry,\n\t\t\t\t\t\t\tparentId: pathParentId,\n\t\t\t\t\t\t\tfirstKeptEntryId: replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { ...entry, parentId: pathParentId },\n\t\t\t);\n\t\t\tpathParentId = entry.id;\n\t\t}\n\n\t\tconst newSessionId = createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: this.persist ? previousSessionFile : undefined,\n\t\t};\n\n\t\t// Collect labels for entries in the path\n\t\tconst pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));\n\t\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\t\tfor (const [targetId, label] of this.labelsById) {\n\t\t\tif (pathEntryIds.has(targetId)) {\n\t\t\t\tlabelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });\n\t\t\t}\n\t\t}\n\n\t\tif (this.persist) {\n\t\t\t// Build label entries\n\t\t\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\t\tlet parentId = lastEntryId;\n\t\t\tconst labelEntries: LabelEntry[] = [];\n\t\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\t\ttype: \"label\",\n\t\t\t\t\tid: generateId(new Set(pathEntryIds)),\n\t\t\t\t\tparentId,\n\t\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tlabel,\n\t\t\t\t};\n\t\t\t\tpathEntryIds.add(labelEntry.id);\n\t\t\t\tlabelEntries.push(labelEntry);\n\t\t\t\tparentId = labelEntry.id;\n\t\t\t}\n\n\t\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\t\tthis.sessionId = newSessionId;\n\t\t\tthis.sessionFile = newSessionFile;\n\t\t\tthis._buildIndex();\n\n\t\t\t// Use the same rule as _persist(): write now if the branched path already\n\t\t\t// has a conversation, otherwise let _persist() create the file later.\n\t\t\tif (this._hasConversation()) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t} else {\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\n\t\t\treturn newSessionFile;\n\t\t}\n\n\t\t// In-memory mode: replace current session with the path + labels\n\t\tconst labelEntries: LabelEntry[] = [];\n\t\tlet parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\ttype: \"label\",\n\t\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\t\tparentId,\n\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\ttargetId,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tlabelEntries.push(labelEntry);\n\t\t\tparentId = labelEntry.id;\n\t\t}\n\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\tthis.sessionId = newSessionId;\n\t\tthis._buildIndex();\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create a new session.\n\t * @param cwd Working directory (stored in session header)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param options Optional new-session header options.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic create(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options, undefined, storage);\n\t}\n\n\t/**\n\t * Open a specific session file.\n\t * @param path Path to session file\n\t * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.\n\t * @param cwdOverride Optional cwd override instead of the session header cwd.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic open(\n\t\tpath: string,\n\t\tsessionDir?: string,\n\t\tcwdOverride?: string,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet preloadedFileEntries: FileEntry[] | undefined;\n\t\tif (cwdOverride === undefined && storage.exists(resolvedPath)) {\n\t\t\ttry {\n\t\t\t\theader = storage.readHeader(resolvedPath);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof SessionHeaderScanLimitError)) throw error;\n\t\t\t\t// The bounded scan is only a discovery optimization. A full load remains\n\t\t\t\t// authoritative for legacy files with very large headers or prefixes.\n\t\t\t\tpreloadedFileEntries = storage.loadEntries(resolvedPath);\n\t\t\t\tconst firstEntry = preloadedFileEntries[0];\n\t\t\t\theader = firstEntry?.type === \"session\" ? firstEntry : null;\n\t\t\t}\n\t\t}\n\t\tconst cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd();\n\t\t// If no sessionDir provided, derive from file's parent directory\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true, undefined, preloadedFileEntries, storage);\n\t}\n\n\t/**\n\t * Continue the most recent session, or create new if none.\n\t * @param cwd Working directory\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSessionWithStorage(storage, dir, filterCwd ? cwd : undefined);\n\t\tif (mostRecent) {\n\t\t\treturn new SessionManager(cwd, dir, mostRecent, true, undefined, undefined, storage);\n\t\t}\n\t\treturn new SessionManager(cwd, dir, undefined, true, undefined, undefined, storage);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/**\n\t * Fork a session from another project directory into the current project.\n\t * Creates a new session in the target cwd with the full history from the source session.\n\t * @param sourcePath Path to the source session file\n\t * @param targetCwd Target working directory (where the new session will be stored)\n\t * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.\n\t * @param options Optional new-session header options.\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): SessionManager {\n\t\tconst resolvedSourcePath = resolvePath(sourcePath);\n\t\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\t\tconst sourceEntries = storage.loadEntries(resolvedSourcePath);\n\t\tif (sourceEntries.length === 0) {\n\t\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst sourceHeader = sourceEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\tif (!sourceHeader) {\n\t\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);\n\t\tstorage.ensureDir(dir);\n\n\t\t// Create new session file with new ID but forked content\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tconst newSessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\t// Write new header pointing to source as parent, with updated cwd\n\t\tconst newHeader: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: resolvedTargetCwd,\n\t\t\tparentSession: resolvedSourcePath,\n\t\t};\n\t\tstorage.createExclusive(newSessionFile, [\n\t\t\tnewHeader,\n\t\t\t// Copy all non-header entries from source\n\t\t\t...sourceEntries.filter((entry) => entry.type !== \"session\"),\n\t\t]);\n\n\t\treturn new SessionManager(resolvedTargetCwd, dir, newSessionFile, true, undefined, undefined, storage);\n\t}\n\n\t/**\n\t * Find an exact session ID without loading transcript bodies.\n\t * @param cwd Working directory (used to compute default session directory)\n\t * @param id Exact session ID\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param storage Optional storage provider; defaults to the local file protocol.\n\t */\n\tstatic findById(\n\t\tcwd: string,\n\t\tid: string,\n\t\tsessionDir?: string,\n\t\tstorage: SessionStorageProvider = FileSessionStorageProvider.instance,\n\t): string | undefined {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst resolvedCwd = resolvePath(cwd);\n\n\t\ttry {\n\t\t\tfor (const path of storage.listSessionFiles(dir)) {\n\t\t\t\tconst header = readSessionHeaderForDiscovery(storage, path);\n\t\t\t\tif (header?.id !== id) continue;\n\t\t\t\tif (filterCwd && !sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd)) continue;\n\t\t\t\treturn path;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Exact session discovery is best-effort, matching list().\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * List all sessions for a directory.\n\t * @param cwd Working directory (used to compute default session directory)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.agent-forge/agent/sessions/<encoded-cwd>/).\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t * @param signal Optional abort signal; an aborted listing rejects with AbortError\n\t */\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\tsignal?: AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst includeSession = (session: SessionInfo) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd);\n\t\tconst progress: SessionListProgress | undefined = onProgress\n\t\t\t? (loaded, total, partialSessions) => onProgress(loaded, total, partialSessions?.filter(includeSession))\n\t\t\t: undefined;\n\t\tconst sessions = (await listSessionsFromDir(dir, progress, signal)).filter(includeSession);\n\t\treturn sortSessionInfos(sessions);\n\t}\n\n\t/**\n\t * List all sessions across all project directories.\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t * @param signal Optional abort signal; an aborted listing rejects with AbortError\n\t */\n\tstatic async listAll(onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\tsignal?: AbortSignal,\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgressOrSignal?: SessionListProgress | AbortSignal,\n\t\tsignal?: AbortSignal,\n\t): Promise<SessionInfo[]> {\n\t\tconst customSessionDir =\n\t\t\ttypeof sessionDirOrOnProgress === \"string\" ? normalizePath(sessionDirOrOnProgress) : undefined;\n\t\tconst progress =\n\t\t\ttypeof sessionDirOrOnProgress === \"function\"\n\t\t\t\t? sessionDirOrOnProgress\n\t\t\t\t: typeof onProgressOrSignal === \"function\"\n\t\t\t\t\t? onProgressOrSignal\n\t\t\t\t\t: undefined;\n\t\tconst abortSignal =\n\t\t\ttypeof sessionDirOrOnProgress === \"string\" || typeof onProgressOrSignal === \"function\"\n\t\t\t\t? signal\n\t\t\t\t: (onProgressOrSignal ?? signal);\n\t\tabortSignal?.throwIfAborted();\n\t\tif (customSessionDir) {\n\t\t\treturn sortSessionInfos(await listSessionsFromDir(customSessionDir, progress, abortSignal));\n\t\t}\n\n\t\tconst sessionsDir = getSessionsDir();\n\n\t\ttry {\n\t\t\tif (!existsSync(sessionsDir)) return [];\n\t\t\tconst entries = await readdir(sessionsDir, { withFileTypes: true });\n\t\t\tconst dirs = entries\n\t\t\t\t.filter((entry) => entry.isDirectory() || entry.isSymbolicLink())\n\t\t\t\t.map((entry) => join(sessionsDir, entry.name));\n\n\t\t\tconst dirFiles = await mapWithConcurrency(\n\t\t\t\tdirs,\n\t\t\t\tMAX_CONCURRENT_SESSION_DISCOVERY_LOADS,\n\t\t\t\tasync (dir) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn (await readdir(dir)).filter((file) => file.endsWith(\".jsonl\")).map((file) => join(dir, file));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tabortSignal,\n\t\t\t);\n\t\t\tconst allFiles = dirFiles.flat();\n\t\t\tconst candidates = await mapWithConcurrency(\n\t\t\t\tallFiles,\n\t\t\t\tMAX_CONCURRENT_SESSION_DISCOVERY_LOADS,\n\t\t\t\tasync (path): Promise<SessionFileCandidate> => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn { path, stats: await stat(path) };\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn { path };\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tabortSignal,\n\t\t\t);\n\t\t\tcandidates.sort(\n\t\t\t\t(a, b) =>\n\t\t\t\t\t(b.stats?.mtimeMs ?? Number.NEGATIVE_INFINITY) - (a.stats?.mtimeMs ?? Number.NEGATIVE_INFINITY) ||\n\t\t\t\t\tbasename(b.path).localeCompare(basename(a.path)),\n\t\t\t);\n\n\t\t\tconst totalFiles = candidates.length;\n\t\t\tlet loaded = 0;\n\t\t\tlet firstCandidateLoaded = false;\n\t\t\tconst partialSessions: SessionInfo[] = [];\n\t\t\tconst results = await buildSessionInfosWithConcurrency(\n\t\t\t\tcandidates,\n\t\t\t\t(info, index) => {\n\t\t\t\t\tloaded++;\n\t\t\t\t\tif (index === 0) firstCandidateLoaded = true;\n\t\t\t\t\tif (info) partialSessions.push(info);\n\t\t\t\t\tconst publishPartial =\n\t\t\t\t\t\tfirstCandidateLoaded &&\n\t\t\t\t\t\t(index === 0 || loaded % ALL_SESSION_LIST_PUBLISH_INTERVAL === 0 || loaded === totalFiles);\n\t\t\t\t\tprogress?.(loaded, totalFiles, publishPartial ? sortSessionInfos([...partialSessions]) : undefined);\n\t\t\t\t},\n\t\t\t\tabortSignal,\n\t\t\t);\n\n\t\t\treturn sortSessionInfos(results.filter((info): info is SessionInfo => info !== null));\n\t\t} catch {\n\t\t\tabortSignal?.throwIfAborted();\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
|