@ponythewhite/base-context 1.0.10 → 1.0.11

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/base-context-runtime/pyproject.toml +1 -1
  3. package/dist/base-context-runtime/uv.lock +1 -1
  4. package/dist/build-info.json +1 -1
  5. package/dist/bundle/{bundled-modules-MX6YNAM2.js → bundled-modules-PEFT72QN.js} +2 -2
  6. package/dist/bundle/{chunk-UHLGPYMI.js → chunk-JZHGOOFM.js} +68 -18
  7. package/dist/bundle/{chunk-CDXQNS5P.js → chunk-TOOVREMP.js} +498 -82
  8. package/dist/bundle/{cli-main-D7W3WWCV.js → cli-main-BRXGYTGK.js} +2 -2
  9. package/dist/bundle/cli.js +1 -1
  10. package/dist/bundle/{main-5J3QBZ5Y.js → main-POUXGEL6.js} +2 -2
  11. package/dist/core/agent-session.d.ts +0 -1
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +85 -45
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/canonical-context.d.ts +19 -3
  16. package/dist/core/canonical-context.d.ts.map +1 -1
  17. package/dist/core/canonical-context.js +130 -9
  18. package/dist/core/canonical-context.js.map +1 -1
  19. package/dist/core/context-epoch-copy.d.ts +1 -1
  20. package/dist/core/context-epoch-copy.d.ts.map +1 -1
  21. package/dist/core/context-epoch-copy.js +18 -7
  22. package/dist/core/context-epoch-copy.js.map +1 -1
  23. package/dist/core/context-epoch.d.ts +4 -0
  24. package/dist/core/context-epoch.d.ts.map +1 -1
  25. package/dist/core/context-epoch.js +8 -1
  26. package/dist/core/context-epoch.js.map +1 -1
  27. package/dist/core/context-tree.d.ts +1 -1
  28. package/dist/core/context-tree.d.ts.map +1 -1
  29. package/dist/core/context-tree.js +98 -8
  30. package/dist/core/context-tree.js.map +1 -1
  31. package/dist/core/history-index-worker.d.ts.map +1 -1
  32. package/dist/core/history-index-worker.js +59 -6
  33. package/dist/core/history-index-worker.js.map +1 -1
  34. package/dist/core/history-index.d.ts +17 -0
  35. package/dist/core/history-index.d.ts.map +1 -1
  36. package/dist/core/history-index.js +22 -0
  37. package/dist/core/history-index.js.map +1 -1
  38. package/dist/core/inference-coordinator.d.ts.map +1 -1
  39. package/dist/core/inference-coordinator.js +5 -1
  40. package/dist/core/inference-coordinator.js.map +1 -1
  41. package/dist/core/request-view-selection.d.ts +2 -1
  42. package/dist/core/request-view-selection.d.ts.map +1 -1
  43. package/dist/core/request-view-selection.js +29 -2
  44. package/dist/core/request-view-selection.js.map +1 -1
  45. package/dist/core/session-fork-messages.d.ts +5 -0
  46. package/dist/core/session-fork-messages.d.ts.map +1 -1
  47. package/dist/core/session-fork-messages.js +44 -0
  48. package/dist/core/session-fork-messages.js.map +1 -1
  49. package/dist/core/session-history-index.d.ts +5 -0
  50. package/dist/core/session-history-index.d.ts.map +1 -1
  51. package/dist/core/session-history-index.js +7 -0
  52. package/dist/core/session-history-index.js.map +1 -1
  53. package/dist/core/session-manager.d.ts +2 -0
  54. package/dist/core/session-manager.d.ts.map +1 -1
  55. package/dist/core/session-manager.js +155 -13
  56. package/dist/core/session-manager.js.map +1 -1
  57. package/dist/core/session-tree.d.ts +9 -0
  58. package/dist/core/session-tree.d.ts.map +1 -1
  59. package/dist/core/session-tree.js +71 -11
  60. package/dist/core/session-tree.js.map +1 -1
  61. package/dist/modes/agent-connection/in-process-agent-connection.d.ts.map +1 -1
  62. package/dist/modes/agent-connection/in-process-agent-connection.js +4 -4
  63. package/dist/modes/agent-connection/in-process-agent-connection.js.map +1 -1
  64. package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
  65. package/dist/modes/daemon/daemon-mode.js +4 -4
  66. package/dist/modes/daemon/daemon-mode.js.map +1 -1
  67. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"context-tree.d.ts","sourceRoot":"","sources":["../../src/core/context-tree.ts"],"names":[],"mappings":"AAE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AAE,qBAAqB,EAC3C,MAAM,GAAE,OAAO,CAAC,wBAAwB,CAAC,GAAG,kBAAuB,EACnE,QAAQ,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,IAAI,GAAG,OAAO,GAAG,QAAQ,CAAC,GACzD,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAiCtC;AAED,+FAA+F;AAC/F,wBAAsB,+BAA+B,CACpD,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,oBAAoB,EAAE,qBAAqB,EAC3C,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,EAC7B,MAAM,GAAE,OAAO,CAAC,wBAAwB,CAAC,GAAG,kBAAuB,GACjE,OAAO,CAAC,eAAe,EAAE,CAAC,CA0B5B","sourcesContent":["import { existsSync, opendirSync, statSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { AssistantMessage, Usage } from \"@ponythewhite/base-context-ai\";\nimport type { RlmChildAgentStatus } from \"./agent-session.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { calculateContextTokens, estimateContextTokens } from \"./compaction/index.js\";\nimport { exportHistoryLimits, readSessionHistoryFile } from \"./export-html/history.js\";\nimport type { ContextUsage } from \"./extensions/index.js\";\nimport type { ParentPathCursor } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport {\n\tapplyChildUsageAttributions,\n\tbuildSessionContext,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"./session-manager.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, subtractAssistantUsage } from \"./usage.js\";\n\n/** Resolves a model's context window so disk-only nodes can report utilization. */\nexport type ContextWindowResolver = (provider: string, modelId: string) => number | undefined;\n\n/**\n * One agent in the context overview: the main session or an RLM (sub-)agent.\n * `ownUsage` excludes descendants; `totalUsage` includes completed descendants, matching /usage.\n */\nexport interface ContextTreeNode {\n\t/** \"root\" for the session itself; sub-xxxx for an RLM child. */\n\tid: string;\n\tlabel: string;\n\tstatus: \"active\" | RlmChildAgentStatus;\n\tmodel?: { provider: string; id: string };\n\townUsage: Usage;\n\ttotalUsage: Usage;\n\tcontextUsage?: ContextUsage;\n\tchildren: ContextTreeNode[];\n}\n\n/** Shared by one overview request, not by concurrent requests or the process. */\nexport interface ContextTreeRequestLimits extends SessionHistoryReadLimits {\n\tmaxNodes: number;\n\tmaxMetadataBytes: number;\n\tmaxDirectoryEntries: number;\n}\n\nclass ContextTreeLimitError extends Error {}\n\n/** Small request-local counters and one full-history reduction tail. */\nexport class ContextTreeRequest {\n\treadonly limits: Readonly<ContextTreeRequestLimits>;\n\tprivate nodes = 0;\n\tprivate metadataBytes = 0;\n\tprivate directoryEntries = 0;\n\tprivate readTail: Promise<void> = Promise.resolve();\n\n\tconstructor(limits: Partial<ContextTreeRequestLimits> = {}) {\n\t\tthis.limits = Object.freeze({\n\t\t\t...exportHistoryLimits(limits),\n\t\t\tmaxNodes: limits.maxNodes ?? 256,\n\t\t\tmaxMetadataBytes: limits.maxMetadataBytes ?? 4 * 1024 * 1024,\n\t\t\tmaxDirectoryEntries: limits.maxDirectoryEntries ?? 16_384,\n\t\t});\n\t\tif (!Object.values(this.limits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\t\tthrow new Error(\"Invalid context tree request limits\");\n\t}\n\n\tadmitNode(): void {\n\t\tif (this.nodes >= this.limits.maxNodes) throw new ContextTreeLimitError(\"Context tree node budget exceeded\");\n\t\tthis.nodes++;\n\t}\n\n\tretainMetadata(value: unknown): number {\n\t\tlet json: string;\n\t\ttry {\n\t\t\tjson = stringifyBoundedJson(value, this.limits.maxMetadataBytes - this.metadataBytes);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"JSON byte limit exceeded\")\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree metadata byte budget exceeded\", { cause: error });\n\t\t\tthrow error;\n\t\t}\n\t\tconst bytes = Buffer.byteLength(json);\n\t\tthis.metadataBytes += bytes;\n\t\treturn bytes;\n\t}\n\n\treleaseMetadata(bytes: number): void {\n\t\tthis.metadataBytes -= bytes;\n\t}\n\n\tdirectoryEntry(): void {\n\t\tif (this.directoryEntries >= this.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tthis.directoryEntries++;\n\t}\n\n\tread<T>(read: () => Promise<T>): Promise<T> {\n\t\tconst result = this.readTail.then(read);\n\t\tthis.readTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n}\n\nfunction treeRequest(limits: Partial<ContextTreeRequestLimits> | ContextTreeRequest): ContextTreeRequest {\n\treturn limits instanceof ContextTreeRequest ? limits : new ContextTreeRequest(limits);\n}\n\nfunction isAssistantEntry(entry: SessionEntry): entry is SessionEntry & {\n\ttype: \"message\";\n\tmessage: AssistantMessage;\n} {\n\treturn entry.type === \"message\" && entry.message.role === \"assistant\";\n}\n\nfunction readUserMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t(block as { type?: unknown }).type === \"text\" &&\n\t\t\t\ttypeof (block as { text?: unknown }).text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction compactLabel(text: string, maxLength = 80): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\tif (compact.length <= maxLength) {\n\t\treturn compact;\n\t}\n\treturn `${compact.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\n/**\n * Usage totals for one agent: `totalUsage` sums the branch's assistant usage\n * (attributed aggregates, so descendants are included), `ownUsage` removes the\n * attributions targeting those assistants. Attribution entries are matched by\n * target across ALL entries, not just the branch: attributions rewrite the\n * target assistant's usage no matter which branch they were appended on, so a\n * fork that keeps the assistant but drops the attribution entry must still\n * subtract it.\n *\n * Totals are deliberately cumulative across compactions: compaction shrinks\n * the model-facing context, not what the session has spent, so assistants\n * dropped from the resolved context still count here.\n */\nexport function computeOwnAndTotalUsage(\n\tbranch: SessionEntry[],\n\tallEntries: SessionEntry[],\n): { ownUsage: Usage; totalUsage: Usage } {\n\tconst totalUsage = emptyUsage();\n\tconst branchAssistantIds = new Set<string>();\n\tfor (const entry of branch) {\n\t\tif (isAssistantEntry(entry)) {\n\t\t\tbranchAssistantIds.add(entry.id);\n\t\t\taddAssistantUsage(totalUsage, entry.message.usage);\n\t\t} else if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) {\n\t\t\taddAssistantUsage(totalUsage, entry.usage);\n\t\t}\n\t}\n\tconst ownUsage = cloneUsage(totalUsage);\n\tfor (const entry of allEntries) {\n\t\tif (entry.type === \"child_usage_attributed\" && branchAssistantIds.has(entry.targetId)) {\n\t\t\tsubtractAssistantUsage(ownUsage, entry.childUsage);\n\t\t}\n\t}\n\treturn { ownUsage, totalUsage };\n}\n\n/** Complete bounded snapshot of an explicitly resident Manager, never an index-error fallback.\n * This synchronous reduction runs in the pre-await live-tree capture walk. It never\n * retains a decoded resident snapshot while native/disk work waits for a slot.\n */\nexport function readResidentContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\tavailabilityMaxSourceBytes?: number,\n): { ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } {\n\tconst snapshot = manager.materializeResidentHistory(limits);\n\tconst branch = branchEntries(snapshot.entries, snapshot.leafId, availabilityMaxSourceBytes !== undefined);\n\tif (availabilityMaxSourceBytes !== undefined) {\n\t\tif (!Number.isSafeInteger(availabilityMaxSourceBytes) || availabilityMaxSourceBytes <= 0)\n\t\t\tthrow new Error(\"Invalid parent-path materialization limits\");\n\t\tif (branch.length > 16_384) throw new Error(\"Parent-path entry budget exceeded\");\n\t\tlet bytes = 0;\n\t\tfor (const entry of branch) {\n\t\t\tbytes += Buffer.byteLength(stringifyBoundedJson(entry, availabilityMaxSourceBytes - bytes));\n\t\t}\n\t}\n\treturn {\n\t\t...computeOwnAndTotalUsage(branch, snapshot.entries),\n\t\t...(availabilityMaxSourceBytes === undefined ? {} : { hasPostCompactionUsage: hasPostCompactionUsage(branch) }),\n\t};\n}\n\n/** Detached, complete source usage and its exact captured parent branch. */\nexport async function readContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\trequest?: ContextTreeRequest,\n\tavailabilityMaxSourceBytes?: number,\n): Promise<\n\t{ source: SourceSnapshotRef; ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } | undefined\n> {\n\tif (!manager.supportsCapturedHistoryReads()) return undefined;\n\tconst sourceLimits = request?.limits ?? limits;\n\tconst capturedLimits = { maxEntries: sourceLimits.maxEntries, maxSourceBytes: sourceLimits.maxSourceBytes };\n\t// The actual source frontier binds NOW, never after waiting for the reduction slot.\n\treturn manager.readSourceHistory((history) => {\n\t\trequest?.retainMetadata(history.source);\n\t\tconst reduce = async () => {\n\t\t\tconst materialized = await history.materialize(capturedLimits);\n\t\t\tconst allEntries = materialized.entries.map(({ entry }) => entry);\n\t\t\tapplyChildUsageAttributions(allEntries);\n\t\t\tconst byId = new Map(allEntries.map((entry) => [entry.id, entry]));\n\t\t\tconst branch: SessionEntry[] = [];\n\t\t\tlet cursor: ParentPathCursor | undefined;\n\t\t\tdo {\n\t\t\t\tconst page = await history.parentPath({ cursor });\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tconst entry = byId.get(reference.id);\n\t\t\t\t\tif (!entry) throw new Error(\"Context-tree parent-path entry source is unavailable\");\n\t\t\t\t\tbranch.push(entry);\n\t\t\t\t}\n\t\t\t\tcursor = page.nextCursor ?? undefined;\n\t\t\t} while (cursor);\n\t\t\tlet available: boolean | undefined;\n\t\t\tif (availabilityMaxSourceBytes !== undefined) {\n\t\t\t\tconst bootstrap = await history.branchBootstrap();\n\t\t\t\tavailable = !bootstrap.latestCompaction;\n\t\t\t\tconst reference = bootstrap.contextUsageAssistant;\n\t\t\t\tif (bootstrap.latestCompaction && reference) {\n\t\t\t\t\tconst updates = await history.branchContext.contextUpdates({\n\t\t\t\t\t\tkind: \"assistant-usage\",\n\t\t\t\t\t\ttargetId: reference.id,\n\t\t\t\t\t});\n\t\t\t\t\tconst bytes =\n\t\t\t\t\t\treference.locator.length + updates.refs.reduce((sum, update) => sum + update.locator.length, 0);\n\t\t\t\t\tif (bytes > availabilityMaxSourceBytes) throw new Error(\"Context usage source byte budget exceeded\");\n\t\t\t\t\tconst assistant = byId.get(reference.id);\n\t\t\t\t\tif (!assistant || !isAssistantEntry(assistant))\n\t\t\t\t\t\tthrow new Error(\"Context usage assistant source is unavailable\");\n\t\t\t\t\t// Full-source ordered projection above includes off-branch attributions.\n\t\t\t\t\tavailable = calculateContextTokens(assistant.message.usage) > 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst usage = {\n\t\t\t\t...computeOwnAndTotalUsage(branch, allEntries),\n\t\t\t\t...(available === undefined ? {} : { hasPostCompactionUsage: available }),\n\t\t\t};\n\t\t\trequest?.retainMetadata(usage);\n\t\t\treturn { source: history.source, ...usage };\n\t\t};\n\t\treturn request ? request.read(reduce) : reduce();\n\t});\n}\n\nfunction hasPostCompactionUsage(branch: SessionEntry[]): boolean {\n\tlet boundary = -1;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tif (branch[index].type === \"compaction\") {\n\t\t\tboundary = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (boundary < 0) return true;\n\tfor (let index = branch.length - 1; index > boundary; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isAssistantEntry(entry)) continue;\n\t\tif (entry.message.stopReason !== \"aborted\" && entry.message.stopReason !== \"error\")\n\t\t\treturn calculateContextTokens(entry.message.usage) > 0;\n\t}\n\treturn false;\n}\n\n/**\n * Current context utilization from persisted entries, mirroring\n * AgentSession.getContextUsage(): unknown right after a compaction until the\n * next assistant response, otherwise the last assistant usage plus an\n * estimate for trailing messages (tool results, queued user input) that have\n * not hit the model yet.\n */\nfunction computeContextUsageFromEntries(\n\tallEntries: SessionEntry[],\n\tbranch: SessionEntry[],\n\tcontextWindow: number | undefined,\n): ContextUsage | undefined {\n\tif (!contextWindow || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tif (!hasPostCompactionUsage(branch)) {\n\t\treturn { tokens: null, contextWindow, percent: null };\n\t}\n\n\tconst estimate = estimateContextTokens(buildSessionContext(allEntries).messages);\n\tif (estimate.tokens <= 0) {\n\t\treturn undefined;\n\t}\n\treturn { tokens: estimate.tokens, contextWindow, percent: (estimate.tokens / contextWindow) * 100 };\n}\n\n/**\n * Entries on the current branch, root to leaf, mirroring\n * SessionManager.getBranch(): the leaf is the last appended entry and the\n * branch is its parentId chain. Keeps forked/abandoned paths out of usage\n * sums so disk nodes match what a live session would report.\n */\nfunction branchEntries(entries: SessionEntry[], leafId?: string | null, strict = false): SessionEntry[] {\n\tif (entries.length === 0) {\n\t\tif (strict && leafId !== undefined && leafId !== null) throw new Error(\"Parent path lineage is unresolved\");\n\t\treturn [];\n\t}\n\tconst byId = new Map(entries.map((entry) => [entry.id, entry]));\n\tconst branch: SessionEntry[] = [];\n\tconst seen = new Set<string>();\n\tlet current: SessionEntry | undefined =\n\t\tleafId === undefined ? entries[entries.length - 1] : leafId === null ? undefined : byId.get(leafId);\n\tif (strict && leafId !== undefined && leafId !== null && !current)\n\t\tthrow new Error(\"Parent path lineage is unresolved\");\n\twhile (current && !seen.has(current.id)) {\n\t\tseen.add(current.id);\n\t\tbranch.push(current);\n\t\tconst parentId = current.parentId;\n\t\tconst hasParent = strict ? parentId !== null : !!parentId;\n\t\tcurrent = hasParent ? byId.get(parentId!) : undefined;\n\t\tif (strict && hasParent && !current) throw new Error(\"Parent path lineage is unresolved\");\n\t}\n\tif (strict && current) throw new Error(\"Parent path lineage is unresolved\");\n\treturn branch.reverse();\n}\n\n/**\n * Terminal status for a persisted child, inferred from how its last assistant\n * turn ended: errored and aborted runs should not render as successful.\n */\nfunction statusFromBranch(entries: SessionEntry[]): \"done\" | \"error\" | \"cancelled\" {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (!isAssistantEntry(entry)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.message.stopReason === \"error\") {\n\t\t\treturn \"error\";\n\t\t}\n\t\tif (entry.message.stopReason === \"aborted\") {\n\t\t\treturn \"cancelled\";\n\t\t}\n\t\treturn \"done\";\n\t}\n\treturn \"done\";\n}\n\n/** Stream names; opening/reading errors keep the caller's existing policy. */\nfunction visitDirectory(dirPath: string, request: ContextTreeRequest, visit: (name: string) => void): void {\n\tconst dir = opendirSync(dirPath);\n\ttry {\n\t\tfor (let entry = dir.readSync(); entry !== null; entry = dir.readSync()) {\n\t\t\trequest.directoryEntry();\n\t\t\tvisit(entry.name);\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdir.closeSync();\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Context tree directory read and close failed\");\n\t\t}\n\t\tthrow error;\n\t}\n\tdir.closeSync();\n}\n\n// readdirSync used UTF8 lexical order; retain its stable mtime-tie ordering.\nfunction comparePaths(a: string, b: string): number {\n\treturn Buffer.compare(Buffer.from(a), Buffer.from(b));\n}\n\nfunction findSessionFile(dir: string, request: ContextTreeRequest): { path: string; bytes: number } | undefined {\n\tlet newest: { path: string; mtime: number; bytes: number } | undefined;\n\ttry {\n\t\tvisitDirectory(dir, request, (name) => {\n\t\t\tif (!name.endsWith(\".jsonl\")) return;\n\t\t\tconst path = join(dir, name);\n\t\t\tlet mtime: number;\n\t\t\ttry {\n\t\t\t\tmtime = statSync(path).mtime.getTime();\n\t\t\t} catch {\n\t\t\t\treturn; // Skip unreadable files.\n\t\t\t}\n\t\t\tif (!newest || mtime > newest.mtime || (mtime === newest.mtime && comparePaths(path, newest.path) < 0)) {\n\t\t\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\t\t\tnewest = undefined;\n\t\t\t\tconst bytes = request.retainMetadata(path);\n\t\t\t\tnewest = { path, mtime, bytes };\n\t\t\t}\n\t\t});\n\t\treturn newest;\n\t} catch (error) {\n\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\tthrow error;\n\t}\n}\n\nfunction listChildSessionDirs(rlmSessionDir: string, request: ContextTreeRequest): { paths: string[]; bytes: number } {\n\tconst paths: string[] = [];\n\tlet bytes = 0;\n\ttry {\n\t\tvisitDirectory(rlmSessionDir, request, (name) => {\n\t\t\tif (!name.startsWith(\"sub-\")) return;\n\t\t\tconst path = join(rlmSessionDir, name);\n\t\t\ttry {\n\t\t\t\tif (!statSync(path).isDirectory()) return;\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes += request.retainMetadata(path);\n\t\t\tpaths.push(path);\n\t\t});\n\t} catch (error) {\n\t\trequest.releaseMetadata(bytes);\n\t\tif (error instanceof ContextTreeLimitError || error instanceof AggregateError) throw error;\n\t\treturn { paths: [], bytes: 0 };\n\t}\n\tpaths.sort(comparePaths).sort((a, b) => {\n\t\ttry {\n\t\t\treturn statSync(a).mtime.getTime() - statSync(b).mtime.getTime();\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t});\n\treturn { paths, bytes };\n}\n\n/**\n * Build a context node for a completed RLM child from its persisted session\n * dir (sub-xxxx/). Children that already attributed grandchild usage carry the\n * aggregate on their assistant messages (applyChildUsageAttributions), so own\n * usage is recovered by subtracting the attribution entries. Returns undefined\n * when the dir holds no readable session.\n */\nasync function readContextTreeChildNodeFromDisk(\n\tchildSessionDir: string,\n\tsessionFile: string,\n\tresolveContextWindow: ContextWindowResolver,\n\trequest: ContextTreeRequest,\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst allEntries = (await readSessionHistoryFile(sessionFile, request.limits)).filter(\n\t\t(entry): entry is SessionEntry => entry.type !== \"session\",\n\t);\n\tconst branch = branchEntries(allEntries);\n\tif (branch.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tconst { ownUsage, totalUsage } = computeOwnAndTotalUsage(branch, allEntries);\n\n\tlet model: { provider: string; id: string } | undefined;\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, id: entry.modelId };\n\t\t}\n\t}\n\n\tlet label = \"\";\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"user\") {\n\t\t\tlabel = compactLabel(readUserMessageText(entry.message.content));\n\t\t\tif (label) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst contextWindow = model ? resolveContextWindow(model.provider, model.id) : undefined;\n\n\tconst metadata = {\n\t\t...(identity ?? {\n\t\t\tid: basename(childSessionDir),\n\t\t\tlabel: label || \"child agent\",\n\t\t\tstatus: statusFromBranch(branch),\n\t\t}),\n\t\tmodel,\n\t\townUsage,\n\t\ttotalUsage,\n\t\tcontextUsage: computeContextUsageFromEntries(allEntries, branch, contextWindow),\n\t};\n\t// A registered run's identity was already admitted by its live parent.\n\trequest.retainMetadata(identity ? { model, ownUsage, totalUsage, contextUsage: metadata.contextUsage } : metadata);\n\treturn { ...metadata, children: [] };\n}\n\n/** Complete or refuse, sharing the request's slot and counters with descendants.\n * Internal identity is an already-admitted registered run, including its empty placeholder.\n */\nexport async function loadContextTreeChildFromDisk(\n\tchildSessionDir: string,\n\tresolveContextWindow: ContextWindowResolver,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst request = treeRequest(limits);\n\tconst directoryBytes = request.retainMetadata(childSessionDir);\n\tlet sessionFile: { path: string; bytes: number } | undefined;\n\tlet node: ContextTreeNode | undefined;\n\ttry {\n\t\tsessionFile = findSessionFile(childSessionDir, request);\n\t\tif (sessionFile && existsSync(sessionFile.path)) {\n\t\t\t// A header-only history still consumes one bounded source admission.\n\t\t\tif (!identity) request.admitNode();\n\t\t\tnode = await request.read(() =>\n\t\t\t\treadContextTreeChildNodeFromDisk(\n\t\t\t\t\tchildSessionDir,\n\t\t\t\t\tsessionFile!.path,\n\t\t\t\t\tresolveContextWindow,\n\t\t\t\t\trequest,\n\t\t\t\t\tidentity,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tif (sessionFile) request.releaseMetadata(sessionFile.bytes);\n\t\trequest.releaseMetadata(directoryBytes);\n\t}\n\tif (node) {\n\t\t// The full source has been reduced and the serial slot released before recursion.\n\t\tnode.children = await loadContextTreeChildrenFromDisk(childSessionDir, resolveContextWindow, undefined, request);\n\t} else if (identity) {\n\t\tconst usage = { ownUsage: emptyUsage(), totalUsage: emptyUsage() };\n\t\trequest.retainMetadata(usage);\n\t\tnode = { ...identity, ...usage, children: [] };\n\t}\n\treturn node;\n}\n\n/** Persisted children, in existing directory order, excluding already represented live IDs. */\nexport async function loadContextTreeChildrenFromDisk(\n\trlmSessionDir: string | undefined,\n\tresolveContextWindow: ContextWindowResolver,\n\tskipIds?: ReadonlySet<string>,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n): Promise<ContextTreeNode[]> {\n\tconst request = treeRequest(limits);\n\tconst skippedIds = new Set<string>();\n\tlet metadataBytes = 0;\n\ttry {\n\t\t// A caller-provided skip set is bounded before copying, too.\n\t\tif (skipIds && skipIds.size > request.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tfor (const id of skipIds ?? []) {\n\t\t\tmetadataBytes += request.retainMetadata(id);\n\t\t\tskippedIds.add(id);\n\t\t}\n\t\tif (!rlmSessionDir || !existsSync(rlmSessionDir)) return [];\n\t\tmetadataBytes += request.retainMetadata(rlmSessionDir);\n\t\tconst directories = listChildSessionDirs(rlmSessionDir, request);\n\t\tmetadataBytes += directories.bytes;\n\t\tconst nodes: ContextTreeNode[] = [];\n\t\tfor (const childDir of directories.paths) {\n\t\t\tif (skippedIds.has(basename(childDir))) continue;\n\t\t\tconst node = await loadContextTreeChildFromDisk(childDir, resolveContextWindow, request);\n\t\t\tif (node) nodes.push(node);\n\t\t}\n\t\treturn nodes;\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n"]}
1
+ {"version":3,"file":"context-tree.d.ts","sourceRoot":"","sources":["../../src/core/context-tree.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,KAAK,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAI9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAE3E,OAAO,EAIN,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,MAAM,sBAAsB,CAAC;AAG9B,mFAAmF;AACnF,MAAM,MAAM,qBAAqB,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;AAE9F;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,gEAAgE;IAChE,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,QAAQ,GAAG,mBAAmB,CAAC;IACvC,KAAK,CAAC,EAAE;QAAE,QAAQ,EAAE,MA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,GACjC;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC,UAAU,EAAE,KAAK,CAAC;IAAC,sBAAsB,CAAC,EAAE,OAAO,CAAA;CAAE,CAgB1E;AAWD,4EAA4E;AAC5E,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,cAAc,EACvB,MAAM,GAAE,wBAAmF,EAC3F,OAAO,CAAC,EAAE,kBAAkB,EAC5B,0BAA0B,CAAC,EAAE,MAAM,GACjC,OAAO,CACT;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,QAAQ,EAAE,KAAK,CAAC;IAAC,UAAU,EAAE,KAAK,CAAC;IAAC,sBAAsB,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,CAC/G,CAyEA;AAmSD;;GAEG;AACH,wBAAsB,4BAA4B,CACjD,eAAe,EAAE,MAAM,EACvB,oBAAoB,EAAE,qBAAqB,EAC3C,MAAM,GAAE,OAAO,CAAC,wBAAwB,CAAC,GAAG,kBAAuB,EACnE,QAAQ,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,IAAI,GAAG,OAAO,GAAG,QAAQ,CAAC,GACzD,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAiCtC;AAED,+FAA+F;AAC/F,wBAAsB,+BAA+B,CACpD,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,oBAAoB,EAAE,qBAAqB,EAC3C,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,EAC7B,MAAM,GAAE,OAAO,CAAC,wBAAwB,CAAC,GAAG,kBAAuB,GACjE,OAAO,CAAC,eAAe,EAAE,CAAC,CA0B5B","sourcesContent":["import { existsSync, opendirSync, statSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { AssistantMessage, Usage } from \"@ponythewhite/base-context-ai\";\nimport type { RlmChildAgentStatus } from \"./agent-session.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { calculateContextTokens, estimateContextTokens } from \"./compaction/index.js\";\nimport { exportHistoryLimits } from \"./export-html/history.js\";\nimport type { ContextUsage } from \"./extensions/index.js\";\nimport type { IndexedSourceEvent, ParentPathCursor } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport { readCapturedSessionJournal } from \"./session-journal-reader.js\";\nimport {\n\tapplyChildUsageAttributions,\n\tbuildSessionContext,\n\ttype FileEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"./session-manager.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, subtractAssistantUsage } from \"./usage.js\";\n\n/** Resolves a model's context window so disk-only nodes can report utilization. */\nexport type ContextWindowResolver = (provider: string, modelId: string) => number | undefined;\n\n/**\n * One agent in the context overview: the main session or an RLM (sub-)agent.\n * `ownUsage` excludes descendants; `totalUsage` includes completed descendants, matching /usage.\n */\nexport interface ContextTreeNode {\n\t/** \"root\" for the session itself; sub-xxxx for an RLM child. */\n\tid: string;\n\tlabel: string;\n\tstatus: \"active\" | RlmChildAgentStatus;\n\tmodel?: { provider: string; id: string };\n\townUsage: Usage;\n\ttotalUsage: Usage;\n\tcontextUsage?: ContextUsage;\n\tchildren: ContextTreeNode[];\n}\n\n/** Shared by one overview request, not by concurrent requests or the process. */\nexport interface ContextTreeRequestLimits extends SessionHistoryReadLimits {\n\tmaxNodes: number;\n\tmaxMetadataBytes: number;\n\tmaxDirectoryEntries: number;\n}\n\nclass ContextTreeLimitError extends Error {}\n\n/** Small request-local counters and one history-projection reduction tail. */\nexport class ContextTreeRequest {\n\treadonly limits: Readonly<ContextTreeRequestLimits>;\n\tprivate nodes = 0;\n\tprivate metadataBytes = 0;\n\tprivate directoryEntries = 0;\n\tprivate readTail: Promise<void> = Promise.resolve();\n\n\tconstructor(limits: Partial<ContextTreeRequestLimits> = {}) {\n\t\tthis.limits = Object.freeze({\n\t\t\t...exportHistoryLimits(limits),\n\t\t\tmaxNodes: limits.maxNodes ?? 256,\n\t\t\tmaxMetadataBytes: limits.maxMetadataBytes ?? 4 * 1024 * 1024,\n\t\t\tmaxDirectoryEntries: limits.maxDirectoryEntries ?? 16_384,\n\t\t});\n\t\tif (!Object.values(this.limits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\t\tthrow new Error(\"Invalid context tree request limits\");\n\t}\n\n\tadmitNode(): void {\n\t\tif (this.nodes >= this.limits.maxNodes) throw new ContextTreeLimitError(\"Context tree node budget exceeded\");\n\t\tthis.nodes++;\n\t}\n\n\tretainMetadata(value: unknown): number {\n\t\tlet json: string;\n\t\ttry {\n\t\t\tjson = stringifyBoundedJson(value, this.limits.maxMetadataBytes - this.metadataBytes);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"JSON byte limit exceeded\")\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree metadata byte budget exceeded\", { cause: error });\n\t\t\tthrow error;\n\t\t}\n\t\tconst bytes = Buffer.byteLength(json);\n\t\tthis.metadataBytes += bytes;\n\t\treturn bytes;\n\t}\n\n\treleaseMetadata(bytes: number): void {\n\t\tthis.metadataBytes -= bytes;\n\t}\n\n\tdirectoryEntry(): void {\n\t\tif (this.directoryEntries >= this.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tthis.directoryEntries++;\n\t}\n\n\tread<T>(read: () => Promise<T>): Promise<T> {\n\t\tconst result = this.readTail.then(read);\n\t\tthis.readTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n}\n\nfunction treeRequest(limits: Partial<ContextTreeRequestLimits> | ContextTreeRequest): ContextTreeRequest {\n\treturn limits instanceof ContextTreeRequest ? limits : new ContextTreeRequest(limits);\n}\n\nfunction isAssistantEntry(entry: SessionEntry): entry is SessionEntry & {\n\ttype: \"message\";\n\tmessage: AssistantMessage;\n} {\n\treturn entry.type === \"message\" && entry.message.role === \"assistant\";\n}\n\nfunction readUserMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t(block as { type?: unknown }).type === \"text\" &&\n\t\t\t\ttypeof (block as { text?: unknown }).text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction compactLabel(text: string, maxLength = 80): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\tif (compact.length <= maxLength) {\n\t\treturn compact;\n\t}\n\treturn `${compact.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\n/**\n * Usage totals for one agent: `totalUsage` sums the branch's assistant usage\n * (attributed aggregates, so descendants are included), `ownUsage` removes the\n * attributions targeting those assistants. Attribution entries are matched by\n * target across ALL entries, not just the branch: attributions rewrite the\n * target assistant's usage no matter which branch they were appended on, so a\n * fork that keeps the assistant but drops the attribution entry must still\n * subtract it.\n *\n * Totals are deliberately cumulative across compactions: compaction shrinks\n * the model-facing context, not what the session has spent, so assistants\n * dropped from the resolved context still count here.\n */\nexport function computeOwnAndTotalUsage(\n\tbranch: SessionEntry[],\n\tallEntries: SessionEntry[],\n): { ownUsage: Usage; totalUsage: Usage } {\n\tconst totalUsage = emptyUsage();\n\tconst branchAssistantIds = new Set<string>();\n\tfor (const entry of branch) {\n\t\tif (isAssistantEntry(entry)) {\n\t\t\tbranchAssistantIds.add(entry.id);\n\t\t\taddAssistantUsage(totalUsage, entry.message.usage);\n\t\t} else if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) {\n\t\t\taddAssistantUsage(totalUsage, entry.usage);\n\t\t}\n\t}\n\tconst ownUsage = cloneUsage(totalUsage);\n\tfor (const entry of allEntries) {\n\t\tif (entry.type === \"child_usage_attributed\" && branchAssistantIds.has(entry.targetId)) {\n\t\t\tsubtractAssistantUsage(ownUsage, entry.childUsage);\n\t\t}\n\t}\n\treturn { ownUsage, totalUsage };\n}\n\n/** Complete bounded snapshot of an explicitly resident Manager, never an index-error fallback.\n * This synchronous reduction runs in the pre-await live-tree capture walk. It never\n * retains a decoded resident snapshot while native/disk work waits for a slot.\n */\nexport function readResidentContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\tavailabilityMaxSourceBytes?: number,\n): { ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } {\n\tconst snapshot = manager.materializeResidentHistory(limits);\n\tconst branch = branchEntries(snapshot.entries, snapshot.leafId, availabilityMaxSourceBytes !== undefined);\n\tif (availabilityMaxSourceBytes !== undefined) {\n\t\tif (!Number.isSafeInteger(availabilityMaxSourceBytes) || availabilityMaxSourceBytes <= 0)\n\t\t\tthrow new Error(\"Invalid parent-path materialization limits\");\n\t\tif (branch.length > 16_384) throw new Error(\"Parent-path entry budget exceeded\");\n\t\tlet bytes = 0;\n\t\tfor (const entry of branch) {\n\t\t\tbytes += Buffer.byteLength(stringifyBoundedJson(entry, availabilityMaxSourceBytes - bytes));\n\t\t}\n\t}\n\treturn {\n\t\t...computeOwnAndTotalUsage(branch, snapshot.entries),\n\t\t...(availabilityMaxSourceBytes === undefined ? {} : { hasPostCompactionUsage: hasPostCompactionUsage(branch) }),\n\t};\n}\n\nfunction isContextTreeUsageReference(reference: IndexedSourceEvent): boolean {\n\treturn (\n\t\t(reference.kind === \"message\" && reference.authority === \"assistant\") ||\n\t\treference.kind === \"compaction\" ||\n\t\treference.kind === \"branch_summary\" ||\n\t\treference.kind === \"child_usage_attributed\"\n\t);\n}\n\n/** Detached, complete source usage and its exact captured parent branch. */\nexport async function readContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\trequest?: ContextTreeRequest,\n\tavailabilityMaxSourceBytes?: number,\n): Promise<\n\t{ source: SourceSnapshotRef; ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } | undefined\n> {\n\tif (!manager.supportsCapturedHistoryReads()) return undefined;\n\tconst sourceLimits = request?.limits ?? limits;\n\tconst capturedLimits = { maxEntries: sourceLimits.maxEntries, maxSourceBytes: sourceLimits.maxSourceBytes };\n\tif (!Object.values(capturedLimits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\tthrow new Error(\"Invalid history materialization limits\");\n\t// The actual source frontier binds NOW, never after waiting for the reduction slot.\n\treturn manager.readSourceHistory((history) => {\n\t\trequest?.retainMetadata(history.source);\n\t\tconst reduce = async () => {\n\t\t\tconst allEntries: SessionEntry[] = [];\n\t\t\tlet sourceBytes = 0;\n\t\t\tlet after = 0;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await history.page(after);\n\t\t\t\tif (page.indexedThrough < history.source.sourceSequence)\n\t\t\t\t\tthrow new Error(\"Captured history has incomplete index coverage\");\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tif (!isContextTreeUsageReference(reference)) continue;\n\t\t\t\t\tif (allEntries.length >= capturedLimits.maxEntries) throw new Error(\"History entry budget exceeded\");\n\t\t\t\t\tif (sourceBytes + reference.locator.length > capturedLimits.maxSourceBytes)\n\t\t\t\t\t\tthrow new Error(\"History source byte budget exceeded\");\n\t\t\t\t\tconst hydrated = await history.hydrateEntry(reference.id, capturedLimits.maxSourceBytes - sourceBytes);\n\t\t\t\t\tif (!hydrated) throw new Error(\"Context-tree usage entry source is unavailable\");\n\t\t\t\t\tallEntries.push(hydrated.entry);\n\t\t\t\t\tsourceBytes += reference.locator.length;\n\t\t\t\t}\n\t\t\t\tif (page.nextAfter === null) break;\n\t\t\t\tafter = page.nextAfter;\n\t\t\t}\n\t\t\tapplyChildUsageAttributions(allEntries);\n\t\t\tconst byId = new Map(allEntries.map((entry) => [entry.id, entry]));\n\t\t\tconst branch: SessionEntry[] = [];\n\t\t\tlet cursor: ParentPathCursor | undefined;\n\t\t\tdo {\n\t\t\t\tconst page = await history.parentPath({ cursor });\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tif (!isContextTreeUsageReference(reference)) continue;\n\t\t\t\t\tconst entry = byId.get(reference.id);\n\t\t\t\t\tif (!entry) throw new Error(\"Context-tree parent-path entry source is unavailable\");\n\t\t\t\t\tbranch.push(entry);\n\t\t\t\t}\n\t\t\t\tcursor = page.nextCursor ?? undefined;\n\t\t\t} while (cursor);\n\t\t\tlet available: boolean | undefined;\n\t\t\tif (availabilityMaxSourceBytes !== undefined) {\n\t\t\t\tconst bootstrap = await history.branchBootstrap();\n\t\t\t\tavailable = !bootstrap.latestCompaction;\n\t\t\t\tconst reference = bootstrap.contextUsageAssistant;\n\t\t\t\tif (bootstrap.latestCompaction && reference) {\n\t\t\t\t\tconst updates = await history.branchContext.contextUpdates({\n\t\t\t\t\t\tkind: \"assistant-usage\",\n\t\t\t\t\t\ttargetId: reference.id,\n\t\t\t\t\t});\n\t\t\t\t\tconst bytes =\n\t\t\t\t\t\treference.locator.length + updates.refs.reduce((sum, update) => sum + update.locator.length, 0);\n\t\t\t\t\tif (bytes > availabilityMaxSourceBytes) throw new Error(\"Context usage source byte budget exceeded\");\n\t\t\t\t\tconst assistant = byId.get(reference.id);\n\t\t\t\t\tif (!assistant || !isAssistantEntry(assistant))\n\t\t\t\t\t\tthrow new Error(\"Context usage assistant source is unavailable\");\n\t\t\t\t\t// Full-source ordered projection above includes off-branch attributions.\n\t\t\t\t\tavailable = calculateContextTokens(assistant.message.usage) > 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst usage = {\n\t\t\t\t...computeOwnAndTotalUsage(branch, allEntries),\n\t\t\t\t...(available === undefined ? {} : { hasPostCompactionUsage: available }),\n\t\t\t};\n\t\t\trequest?.retainMetadata(usage);\n\t\t\treturn { source: history.source, ...usage };\n\t\t};\n\t\treturn request ? request.read(reduce) : reduce();\n\t});\n}\n\nfunction hasPostCompactionUsage(branch: SessionEntry[]): boolean {\n\tlet boundary = -1;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tif (branch[index].type === \"compaction\") {\n\t\t\tboundary = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (boundary < 0) return true;\n\tfor (let index = branch.length - 1; index > boundary; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isAssistantEntry(entry)) continue;\n\t\tif (entry.message.stopReason !== \"aborted\" && entry.message.stopReason !== \"error\")\n\t\t\treturn calculateContextTokens(entry.message.usage) > 0;\n\t}\n\treturn false;\n}\n\n/**\n * Current context utilization from persisted entries, mirroring\n * AgentSession.getContextUsage(): unknown right after a compaction until the\n * next assistant response, otherwise the last assistant usage plus an\n * estimate for trailing messages (tool results, queued user input) that have\n * not hit the model yet.\n */\nfunction computeContextUsageFromEntries(\n\tallEntries: SessionEntry[],\n\tbranch: SessionEntry[],\n\tcontextWindow: number | undefined,\n): ContextUsage | undefined {\n\tif (!contextWindow || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tif (!hasPostCompactionUsage(branch)) {\n\t\treturn { tokens: null, contextWindow, percent: null };\n\t}\n\n\tconst estimate = estimateContextTokens(buildSessionContext(allEntries, branch.at(-1)?.id ?? null).messages);\n\tif (estimate.tokens <= 0) {\n\t\treturn undefined;\n\t}\n\treturn { tokens: estimate.tokens, contextWindow, percent: (estimate.tokens / contextWindow) * 100 };\n}\n\n/**\n * Entries on the current branch, root to leaf, mirroring\n * SessionManager.getBranch(): the leaf is the last appended entry and the\n * branch is its parentId chain. Keeps forked/abandoned paths out of usage\n * sums so disk nodes match what a live session would report.\n */\nfunction branchEntries(entries: SessionEntry[], leafId?: string | null, strict = false): SessionEntry[] {\n\tif (entries.length === 0) {\n\t\tif (strict && leafId !== undefined && leafId !== null) throw new Error(\"Parent path lineage is unresolved\");\n\t\treturn [];\n\t}\n\tconst byId = new Map(entries.map((entry) => [entry.id, entry]));\n\tconst branch: SessionEntry[] = [];\n\tconst seen = new Set<string>();\n\tlet current: SessionEntry | undefined =\n\t\tleafId === undefined ? entries[entries.length - 1] : leafId === null ? undefined : byId.get(leafId);\n\tif (strict && leafId !== undefined && leafId !== null && !current)\n\t\tthrow new Error(\"Parent path lineage is unresolved\");\n\twhile (current && !seen.has(current.id)) {\n\t\tseen.add(current.id);\n\t\tbranch.push(current);\n\t\tconst parentId = current.parentId;\n\t\tconst hasParent = strict ? parentId !== null : !!parentId;\n\t\tcurrent = hasParent ? byId.get(parentId!) : undefined;\n\t\tif (strict && hasParent && !current) throw new Error(\"Parent path lineage is unresolved\");\n\t}\n\tif (strict && current) throw new Error(\"Parent path lineage is unresolved\");\n\treturn branch.reverse();\n}\n\n/**\n * Terminal status for a persisted child, inferred from how its last assistant\n * turn ended: errored and aborted runs should not render as successful.\n */\nfunction statusFromBranch(entries: SessionEntry[]): \"done\" | \"error\" | \"cancelled\" {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (!isAssistantEntry(entry)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.message.stopReason === \"error\") {\n\t\t\treturn \"error\";\n\t\t}\n\t\tif (entry.message.stopReason === \"aborted\") {\n\t\t\treturn \"cancelled\";\n\t\t}\n\t\treturn \"done\";\n\t}\n\treturn \"done\";\n}\n\n/** Stream names; opening/reading errors keep the caller's existing policy. */\nfunction visitDirectory(dirPath: string, request: ContextTreeRequest, visit: (name: string) => void): void {\n\tconst dir = opendirSync(dirPath);\n\ttry {\n\t\tfor (let entry = dir.readSync(); entry !== null; entry = dir.readSync()) {\n\t\t\trequest.directoryEntry();\n\t\t\tvisit(entry.name);\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdir.closeSync();\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Context tree directory read and close failed\");\n\t\t}\n\t\tthrow error;\n\t}\n\tdir.closeSync();\n}\n\n// readdirSync used UTF8 lexical order; retain its stable mtime-tie ordering.\nfunction comparePaths(a: string, b: string): number {\n\treturn Buffer.compare(Buffer.from(a), Buffer.from(b));\n}\n\nfunction findSessionFile(dir: string, request: ContextTreeRequest): { path: string; bytes: number } | undefined {\n\tlet newest: { path: string; mtime: number; bytes: number } | undefined;\n\ttry {\n\t\tvisitDirectory(dir, request, (name) => {\n\t\t\tif (!name.endsWith(\".jsonl\")) return;\n\t\t\tconst path = join(dir, name);\n\t\t\tlet mtime: number;\n\t\t\ttry {\n\t\t\t\tmtime = statSync(path).mtime.getTime();\n\t\t\t} catch {\n\t\t\t\treturn; // Skip unreadable files.\n\t\t\t}\n\t\t\tif (!newest || mtime > newest.mtime || (mtime === newest.mtime && comparePaths(path, newest.path) < 0)) {\n\t\t\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\t\t\tnewest = undefined;\n\t\t\t\tconst bytes = request.retainMetadata(path);\n\t\t\t\tnewest = { path, mtime, bytes };\n\t\t\t}\n\t\t});\n\t\treturn newest;\n\t} catch (error) {\n\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\tthrow error;\n\t}\n}\n\nfunction listChildSessionDirs(rlmSessionDir: string, request: ContextTreeRequest): { paths: string[]; bytes: number } {\n\tconst paths: string[] = [];\n\tlet bytes = 0;\n\ttry {\n\t\tvisitDirectory(rlmSessionDir, request, (name) => {\n\t\t\tif (!name.startsWith(\"sub-\")) return;\n\t\t\tconst path = join(rlmSessionDir, name);\n\t\t\ttry {\n\t\t\t\tif (!statSync(path).isDirectory()) return;\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes += request.retainMetadata(path);\n\t\t\tpaths.push(path);\n\t\t});\n\t} catch (error) {\n\t\trequest.releaseMetadata(bytes);\n\t\tif (error instanceof ContextTreeLimitError || error instanceof AggregateError) throw error;\n\t\treturn { paths: [], bytes: 0 };\n\t}\n\tpaths.sort(comparePaths).sort((a, b) => {\n\t\ttry {\n\t\t\treturn statSync(a).mtime.getTime() - statSync(b).mtime.getTime();\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t});\n\treturn { paths, bytes };\n}\n\n/** Read a fixed disk prefix without retaining private request or tool-intent bodies. */\nasync function readContextTreeProjectionFromDisk(\n\tsessionFile: string,\n\trequest: ContextTreeRequest,\n): Promise<{ entries: SessionEntry[]; leafId: string | null; hasSourceLeaf: boolean }> {\n\tconst entries: SessionEntry[] = [];\n\tconst hiddenParents = new Map<string, string | null>();\n\tlet leafId: string | null = null;\n\tlet hasHeader = false;\n\tlet sourceBytes = 0;\n\tlet metadataBytes = 0;\n\ttry {\n\t\tawait readCapturedSessionJournal(sessionFile, (record) => {\n\t\t\tconst value = record.entry;\n\t\t\tif (!value || typeof value !== \"object\" || !(\"type\" in value) || typeof value.type !== \"string\")\n\t\t\t\tthrow new Error(\"Invalid session journal entry\");\n\t\t\tconst entry = value as FileEntry;\n\t\t\tif (!hasHeader) {\n\t\t\t\tif (entry.type !== \"session\" || typeof entry.id !== \"string\")\n\t\t\t\t\tthrow new Error(\"Session source has no valid header\");\n\t\t\t\thasHeader = true;\n\t\t\t}\n\t\t\tif (entry.type !== \"session\") leafId = entry.id;\n\t\t\tif (entry.type === \"request\" || entry.type === \"tool_intent\") {\n\t\t\t\tmetadataBytes += request.retainMetadata([entry.id, entry.parentId]);\n\t\t\t\thiddenParents.set(entry.id, entry.parentId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst bytes = record.source?.locator.length ?? Buffer.byteLength(record.json) + 1;\n\t\t\tif (sourceBytes + bytes > request.limits.maxSourceBytes)\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree source byte budget exceeded\");\n\t\t\tsourceBytes += bytes;\n\t\t\tif (entry.type === \"session\") return;\n\t\t\tif (entries.length >= request.limits.maxEntries)\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree entry budget exceeded\");\n\t\t\tentries.push(entry);\n\t\t});\n\t\tconst visibleParent = (id: string | null): string | null => {\n\t\t\tlet remaining = hiddenParents.size;\n\t\t\twhile (id !== null && hiddenParents.has(id)) {\n\t\t\t\tif (remaining-- === 0) throw new Error(\"Parent path lineage is unresolved\");\n\t\t\t\tid = hiddenParents.get(id)!;\n\t\t\t}\n\t\t\treturn id;\n\t\t};\n\t\tfor (const entry of entries) entry.parentId = visibleParent(entry.parentId);\n\t\t// A trailing private record can select an older branch, not the last visible entry.\n\t\tconst hasSourceLeaf = leafId !== null;\n\t\tleafId = visibleParent(leafId);\n\t\tapplyChildUsageAttributions(entries);\n\t\treturn { entries, leafId, hasSourceLeaf };\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n\n/**\n * Build a context node for a completed RLM child from its persisted session\n * dir (sub-xxxx/). Children that already attributed grandchild usage carry the\n * aggregate on their assistant messages (applyChildUsageAttributions), so own\n * usage is recovered by subtracting the attribution entries. Returns undefined\n * when the dir holds no readable session.\n */\nasync function readContextTreeChildNodeFromDisk(\n\tchildSessionDir: string,\n\tsessionFile: string,\n\tresolveContextWindow: ContextWindowResolver,\n\trequest: ContextTreeRequest,\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst { entries: allEntries, leafId, hasSourceLeaf } = await readContextTreeProjectionFromDisk(sessionFile, request);\n\tconst branch = branchEntries(allEntries, leafId);\n\tif (branch.length === 0 && !hasSourceLeaf) {\n\t\treturn undefined;\n\t}\n\n\tconst { ownUsage, totalUsage } = computeOwnAndTotalUsage(branch, allEntries);\n\n\tlet model: { provider: string; id: string } | undefined;\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, id: entry.modelId };\n\t\t}\n\t}\n\n\tlet label = \"\";\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"user\") {\n\t\t\tlabel = compactLabel(readUserMessageText(entry.message.content));\n\t\t\tif (label) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst contextWindow = model ? resolveContextWindow(model.provider, model.id) : undefined;\n\n\tconst metadata = {\n\t\t...(identity ?? {\n\t\t\tid: basename(childSessionDir),\n\t\t\tlabel: label || \"child agent\",\n\t\t\tstatus: statusFromBranch(branch),\n\t\t}),\n\t\tmodel,\n\t\townUsage,\n\t\ttotalUsage,\n\t\tcontextUsage: computeContextUsageFromEntries(allEntries, branch, contextWindow),\n\t};\n\t// A registered run's identity was already admitted by its live parent.\n\trequest.retainMetadata(identity ? { model, ownUsage, totalUsage, contextUsage: metadata.contextUsage } : metadata);\n\treturn { ...metadata, children: [] };\n}\n\n/** Complete or refuse, sharing the request's slot and counters with descendants.\n * Internal identity is an already-admitted registered run, including its empty placeholder.\n */\nexport async function loadContextTreeChildFromDisk(\n\tchildSessionDir: string,\n\tresolveContextWindow: ContextWindowResolver,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst request = treeRequest(limits);\n\tconst directoryBytes = request.retainMetadata(childSessionDir);\n\tlet sessionFile: { path: string; bytes: number } | undefined;\n\tlet node: ContextTreeNode | undefined;\n\ttry {\n\t\tsessionFile = findSessionFile(childSessionDir, request);\n\t\tif (sessionFile && existsSync(sessionFile.path)) {\n\t\t\t// A header-only history still consumes one bounded source admission.\n\t\t\tif (!identity) request.admitNode();\n\t\t\tnode = await request.read(() =>\n\t\t\t\treadContextTreeChildNodeFromDisk(\n\t\t\t\t\tchildSessionDir,\n\t\t\t\t\tsessionFile!.path,\n\t\t\t\t\tresolveContextWindow,\n\t\t\t\t\trequest,\n\t\t\t\t\tidentity,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tif (sessionFile) request.releaseMetadata(sessionFile.bytes);\n\t\trequest.releaseMetadata(directoryBytes);\n\t}\n\tif (node) {\n\t\t// The full source has been reduced and the serial slot released before recursion.\n\t\tnode.children = await loadContextTreeChildrenFromDisk(childSessionDir, resolveContextWindow, undefined, request);\n\t} else if (identity) {\n\t\tconst usage = { ownUsage: emptyUsage(), totalUsage: emptyUsage() };\n\t\trequest.retainMetadata(usage);\n\t\tnode = { ...identity, ...usage, children: [] };\n\t}\n\treturn node;\n}\n\n/** Persisted children, in existing directory order, excluding already represented live IDs. */\nexport async function loadContextTreeChildrenFromDisk(\n\trlmSessionDir: string | undefined,\n\tresolveContextWindow: ContextWindowResolver,\n\tskipIds?: ReadonlySet<string>,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n): Promise<ContextTreeNode[]> {\n\tconst request = treeRequest(limits);\n\tconst skippedIds = new Set<string>();\n\tlet metadataBytes = 0;\n\ttry {\n\t\t// A caller-provided skip set is bounded before copying, too.\n\t\tif (skipIds && skipIds.size > request.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tfor (const id of skipIds ?? []) {\n\t\t\tmetadataBytes += request.retainMetadata(id);\n\t\t\tskippedIds.add(id);\n\t\t}\n\t\tif (!rlmSessionDir || !existsSync(rlmSessionDir)) return [];\n\t\tmetadataBytes += request.retainMetadata(rlmSessionDir);\n\t\tconst directories = listChildSessionDirs(rlmSessionDir, request);\n\t\tmetadataBytes += directories.bytes;\n\t\tconst nodes: ContextTreeNode[] = [];\n\t\tfor (const childDir of directories.paths) {\n\t\t\tif (skippedIds.has(basename(childDir))) continue;\n\t\t\tconst node = await loadContextTreeChildFromDisk(childDir, resolveContextWindow, request);\n\t\t\tif (node) nodes.push(node);\n\t\t}\n\t\treturn nodes;\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n"]}
@@ -2,12 +2,13 @@ import { existsSync, opendirSync, statSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { stringifyBoundedJson } from "./bounded-json.js";
4
4
  import { calculateContextTokens, estimateContextTokens } from "./compaction/index.js";
5
- import { exportHistoryLimits, readSessionHistoryFile } from "./export-html/history.js";
5
+ import { exportHistoryLimits } from "./export-html/history.js";
6
+ import { readCapturedSessionJournal } from "./session-journal-reader.js";
6
7
  import { applyChildUsageAttributions, buildSessionContext, } from "./session-manager.js";
7
8
  import { addAssistantUsage, cloneUsage, emptyUsage, subtractAssistantUsage } from "./usage.js";
8
9
  class ContextTreeLimitError extends Error {
9
10
  }
10
- /** Small request-local counters and one full-history reduction tail. */
11
+ /** Small request-local counters and one history-projection reduction tail. */
11
12
  export class ContextTreeRequest {
12
13
  limits;
13
14
  nodes = 0;
@@ -140,18 +141,48 @@ export function readResidentContextTreeUsage(manager, limits = { maxEntries: 16_
140
141
  ...(availabilityMaxSourceBytes === undefined ? {} : { hasPostCompactionUsage: hasPostCompactionUsage(branch) }),
141
142
  };
142
143
  }
144
+ function isContextTreeUsageReference(reference) {
145
+ return ((reference.kind === "message" && reference.authority === "assistant") ||
146
+ reference.kind === "compaction" ||
147
+ reference.kind === "branch_summary" ||
148
+ reference.kind === "child_usage_attributed");
149
+ }
143
150
  /** Detached, complete source usage and its exact captured parent branch. */
144
151
  export async function readContextTreeUsage(manager, limits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 }, request, availabilityMaxSourceBytes) {
145
152
  if (!manager.supportsCapturedHistoryReads())
146
153
  return undefined;
147
154
  const sourceLimits = request?.limits ?? limits;
148
155
  const capturedLimits = { maxEntries: sourceLimits.maxEntries, maxSourceBytes: sourceLimits.maxSourceBytes };
156
+ if (!Object.values(capturedLimits).every((value) => Number.isSafeInteger(value) && value > 0))
157
+ throw new Error("Invalid history materialization limits");
149
158
  // The actual source frontier binds NOW, never after waiting for the reduction slot.
150
159
  return manager.readSourceHistory((history) => {
151
160
  request?.retainMetadata(history.source);
152
161
  const reduce = async () => {
153
- const materialized = await history.materialize(capturedLimits);
154
- const allEntries = materialized.entries.map(({ entry }) => entry);
162
+ const allEntries = [];
163
+ let sourceBytes = 0;
164
+ let after = 0;
165
+ for (;;) {
166
+ const page = await history.page(after);
167
+ if (page.indexedThrough < history.source.sourceSequence)
168
+ throw new Error("Captured history has incomplete index coverage");
169
+ for (const reference of page.events) {
170
+ if (!isContextTreeUsageReference(reference))
171
+ continue;
172
+ if (allEntries.length >= capturedLimits.maxEntries)
173
+ throw new Error("History entry budget exceeded");
174
+ if (sourceBytes + reference.locator.length > capturedLimits.maxSourceBytes)
175
+ throw new Error("History source byte budget exceeded");
176
+ const hydrated = await history.hydrateEntry(reference.id, capturedLimits.maxSourceBytes - sourceBytes);
177
+ if (!hydrated)
178
+ throw new Error("Context-tree usage entry source is unavailable");
179
+ allEntries.push(hydrated.entry);
180
+ sourceBytes += reference.locator.length;
181
+ }
182
+ if (page.nextAfter === null)
183
+ break;
184
+ after = page.nextAfter;
185
+ }
155
186
  applyChildUsageAttributions(allEntries);
156
187
  const byId = new Map(allEntries.map((entry) => [entry.id, entry]));
157
188
  const branch = [];
@@ -159,6 +190,8 @@ export async function readContextTreeUsage(manager, limits = { maxEntries: 16_38
159
190
  do {
160
191
  const page = await history.parentPath({ cursor });
161
192
  for (const reference of page.events) {
193
+ if (!isContextTreeUsageReference(reference))
194
+ continue;
162
195
  const entry = byId.get(reference.id);
163
196
  if (!entry)
164
197
  throw new Error("Context-tree parent-path entry source is unavailable");
@@ -229,7 +262,7 @@ function computeContextUsageFromEntries(allEntries, branch, contextWindow) {
229
262
  if (!hasPostCompactionUsage(branch)) {
230
263
  return { tokens: null, contextWindow, percent: null };
231
264
  }
232
- const estimate = estimateContextTokens(buildSessionContext(allEntries).messages);
265
+ const estimate = estimateContextTokens(buildSessionContext(allEntries, branch.at(-1)?.id ?? null).messages);
233
266
  if (estimate.tokens <= 0) {
234
267
  return undefined;
235
268
  }
@@ -375,6 +408,63 @@ function listChildSessionDirs(rlmSessionDir, request) {
375
408
  });
376
409
  return { paths, bytes };
377
410
  }
411
+ /** Read a fixed disk prefix without retaining private request or tool-intent bodies. */
412
+ async function readContextTreeProjectionFromDisk(sessionFile, request) {
413
+ const entries = [];
414
+ const hiddenParents = new Map();
415
+ let leafId = null;
416
+ let hasHeader = false;
417
+ let sourceBytes = 0;
418
+ let metadataBytes = 0;
419
+ try {
420
+ await readCapturedSessionJournal(sessionFile, (record) => {
421
+ const value = record.entry;
422
+ if (!value || typeof value !== "object" || !("type" in value) || typeof value.type !== "string")
423
+ throw new Error("Invalid session journal entry");
424
+ const entry = value;
425
+ if (!hasHeader) {
426
+ if (entry.type !== "session" || typeof entry.id !== "string")
427
+ throw new Error("Session source has no valid header");
428
+ hasHeader = true;
429
+ }
430
+ if (entry.type !== "session")
431
+ leafId = entry.id;
432
+ if (entry.type === "request" || entry.type === "tool_intent") {
433
+ metadataBytes += request.retainMetadata([entry.id, entry.parentId]);
434
+ hiddenParents.set(entry.id, entry.parentId);
435
+ return;
436
+ }
437
+ const bytes = record.source?.locator.length ?? Buffer.byteLength(record.json) + 1;
438
+ if (sourceBytes + bytes > request.limits.maxSourceBytes)
439
+ throw new ContextTreeLimitError("Context tree source byte budget exceeded");
440
+ sourceBytes += bytes;
441
+ if (entry.type === "session")
442
+ return;
443
+ if (entries.length >= request.limits.maxEntries)
444
+ throw new ContextTreeLimitError("Context tree entry budget exceeded");
445
+ entries.push(entry);
446
+ });
447
+ const visibleParent = (id) => {
448
+ let remaining = hiddenParents.size;
449
+ while (id !== null && hiddenParents.has(id)) {
450
+ if (remaining-- === 0)
451
+ throw new Error("Parent path lineage is unresolved");
452
+ id = hiddenParents.get(id);
453
+ }
454
+ return id;
455
+ };
456
+ for (const entry of entries)
457
+ entry.parentId = visibleParent(entry.parentId);
458
+ // A trailing private record can select an older branch, not the last visible entry.
459
+ const hasSourceLeaf = leafId !== null;
460
+ leafId = visibleParent(leafId);
461
+ applyChildUsageAttributions(entries);
462
+ return { entries, leafId, hasSourceLeaf };
463
+ }
464
+ finally {
465
+ request.releaseMetadata(metadataBytes);
466
+ }
467
+ }
378
468
  /**
379
469
  * Build a context node for a completed RLM child from its persisted session
380
470
  * dir (sub-xxxx/). Children that already attributed grandchild usage carry the
@@ -383,9 +473,9 @@ function listChildSessionDirs(rlmSessionDir, request) {
383
473
  * when the dir holds no readable session.
384
474
  */
385
475
  async function readContextTreeChildNodeFromDisk(childSessionDir, sessionFile, resolveContextWindow, request, identity) {
386
- const allEntries = (await readSessionHistoryFile(sessionFile, request.limits)).filter((entry) => entry.type !== "session");
387
- const branch = branchEntries(allEntries);
388
- if (branch.length === 0) {
476
+ const { entries: allEntries, leafId, hasSourceLeaf } = await readContextTreeProjectionFromDisk(sessionFile, request);
477
+ const branch = branchEntries(allEntries, leafId);
478
+ if (branch.length === 0 && !hasSourceLeaf) {
389
479
  return undefined;
390
480
  }
391
481
  const { ownUsage, totalUsage } = computeOwnAndTotalUsage(branch, allEntries);
@@ -1 +1 @@
1
- {"version":3,"file":"context-tree.js","sourceRoot":"","sources":["../../src/core/context-tree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAKvF,OAAO,EACN,2BAA2B,EAC3B,mBAAmB,GAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AA4B/F,MAAM,qBAAsB,SAAQ,KAAK;CAAG;AAE5C,wEAAwE;AACxE,MAAM,OAAO,kBAAkB;IACrB,MAAM,CAAqC;IAC5C,KAAK,GAAG,CAAC,CAAC;IACV,aAAa,GAAG,CAAC,CAAC;IAClB,gBAAgB,GAAG,C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ACjD,MAAM,IAAI,GAAG,MAAM,4BAA4B,CAAC,QAAQ,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAC;YACzF,IAAI,IAAI;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACV,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;AAAA,CACD","sourcesContent":["import { existsSync, opendirSync, statSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { AssistantMessage, Usage } from \"@ponythewhite/base-context-ai\";\nimport type { RlmChildAgentStatus } from \"./agent-session.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { calculateContextTokens, estimateContextTokens } from \"./compaction/index.js\";\nimport { exportHistoryLimits, readSessionHistoryFile } from \"./export-html/history.js\";\nimport type { ContextUsage } from \"./extensions/index.js\";\nimport type { ParentPathCursor } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport {\n\tapplyChildUsageAttributions,\n\tbuildSessionContext,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"./session-manager.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, subtractAssistantUsage } from \"./usage.js\";\n\n/** Resolves a model's context window so disk-only nodes can report utilization. */\nexport type ContextWindowResolver = (provider: string, modelId: string) => number | undefined;\n\n/**\n * One agent in the context overview: the main session or an RLM (sub-)agent.\n * `ownUsage` excludes descendants; `totalUsage` includes completed descendants, matching /usage.\n */\nexport interface ContextTreeNode {\n\t/** \"root\" for the session itself; sub-xxxx for an RLM child. */\n\tid: string;\n\tlabel: string;\n\tstatus: \"active\" | RlmChildAgentStatus;\n\tmodel?: { provider: string; id: string };\n\townUsage: Usage;\n\ttotalUsage: Usage;\n\tcontextUsage?: ContextUsage;\n\tchildren: ContextTreeNode[];\n}\n\n/** Shared by one overview request, not by concurrent requests or the process. */\nexport interface ContextTreeRequestLimits extends SessionHistoryReadLimits {\n\tmaxNodes: number;\n\tmaxMetadataBytes: number;\n\tmaxDirectoryEntries: number;\n}\n\nclass ContextTreeLimitError extends Error {}\n\n/** Small request-local counters and one full-history reduction tail. */\nexport class ContextTreeRequest {\n\treadonly limits: Readonly<ContextTreeRequestLimits>;\n\tprivate nodes = 0;\n\tprivate metadataBytes = 0;\n\tprivate directoryEntries = 0;\n\tprivate readTail: Promise<void> = Promise.resolve();\n\n\tconstructor(limits: Partial<ContextTreeRequestLimits> = {}) {\n\t\tthis.limits = Object.freeze({\n\t\t\t...exportHistoryLimits(limits),\n\t\t\tmaxNodes: limits.maxNodes ?? 256,\n\t\t\tmaxMetadataBytes: limits.maxMetadataBytes ?? 4 * 1024 * 1024,\n\t\t\tmaxDirectoryEntries: limits.maxDirectoryEntries ?? 16_384,\n\t\t});\n\t\tif (!Object.values(this.limits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\t\tthrow new Error(\"Invalid context tree request limits\");\n\t}\n\n\tadmitNode(): void {\n\t\tif (this.nodes >= this.limits.maxNodes) throw new ContextTreeLimitError(\"Context tree node budget exceeded\");\n\t\tthis.nodes++;\n\t}\n\n\tretainMetadata(value: unknown): number {\n\t\tlet json: string;\n\t\ttry {\n\t\t\tjson = stringifyBoundedJson(value, this.limits.maxMetadataBytes - this.metadataBytes);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"JSON byte limit exceeded\")\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree metadata byte budget exceeded\", { cause: error });\n\t\t\tthrow error;\n\t\t}\n\t\tconst bytes = Buffer.byteLength(json);\n\t\tthis.metadataBytes += bytes;\n\t\treturn bytes;\n\t}\n\n\treleaseMetadata(bytes: number): void {\n\t\tthis.metadataBytes -= bytes;\n\t}\n\n\tdirectoryEntry(): void {\n\t\tif (this.directoryEntries >= this.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tthis.directoryEntries++;\n\t}\n\n\tread<T>(read: () => Promise<T>): Promise<T> {\n\t\tconst result = this.readTail.then(read);\n\t\tthis.readTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n}\n\nfunction treeRequest(limits: Partial<ContextTreeRequestLimits> | ContextTreeRequest): ContextTreeRequest {\n\treturn limits instanceof ContextTreeRequest ? limits : new ContextTreeRequest(limits);\n}\n\nfunction isAssistantEntry(entry: SessionEntry): entry is SessionEntry & {\n\ttype: \"message\";\n\tmessage: AssistantMessage;\n} {\n\treturn entry.type === \"message\" && entry.message.role === \"assistant\";\n}\n\nfunction readUserMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t(block as { type?: unknown }).type === \"text\" &&\n\t\t\t\ttypeof (block as { text?: unknown }).text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction compactLabel(text: string, maxLength = 80): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\tif (compact.length <= maxLength) {\n\t\treturn compact;\n\t}\n\treturn `${compact.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\n/**\n * Usage totals for one agent: `totalUsage` sums the branch's assistant usage\n * (attributed aggregates, so descendants are included), `ownUsage` removes the\n * attributions targeting those assistants. Attribution entries are matched by\n * target across ALL entries, not just the branch: attributions rewrite the\n * target assistant's usage no matter which branch they were appended on, so a\n * fork that keeps the assistant but drops the attribution entry must still\n * subtract it.\n *\n * Totals are deliberately cumulative across compactions: compaction shrinks\n * the model-facing context, not what the session has spent, so assistants\n * dropped from the resolved context still count here.\n */\nexport function computeOwnAndTotalUsage(\n\tbranch: SessionEntry[],\n\tallEntries: SessionEntry[],\n): { ownUsage: Usage; totalUsage: Usage } {\n\tconst totalUsage = emptyUsage();\n\tconst branchAssistantIds = new Set<string>();\n\tfor (const entry of branch) {\n\t\tif (isAssistantEntry(entry)) {\n\t\t\tbranchAssistantIds.add(entry.id);\n\t\t\taddAssistantUsage(totalUsage, entry.message.usage);\n\t\t} else if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) {\n\t\t\taddAssistantUsage(totalUsage, entry.usage);\n\t\t}\n\t}\n\tconst ownUsage = cloneUsage(totalUsage);\n\tfor (const entry of allEntries) {\n\t\tif (entry.type === \"child_usage_attributed\" && branchAssistantIds.has(entry.targetId)) {\n\t\t\tsubtractAssistantUsage(ownUsage, entry.childUsage);\n\t\t}\n\t}\n\treturn { ownUsage, totalUsage };\n}\n\n/** Complete bounded snapshot of an explicitly resident Manager, never an index-error fallback.\n * This synchronous reduction runs in the pre-await live-tree capture walk. It never\n * retains a decoded resident snapshot while native/disk work waits for a slot.\n */\nexport function readResidentContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\tavailabilityMaxSourceBytes?: number,\n): { ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } {\n\tconst snapshot = manager.materializeResidentHistory(limits);\n\tconst branch = branchEntries(snapshot.entries, snapshot.leafId, availabilityMaxSourceBytes !== undefined);\n\tif (availabilityMaxSourceBytes !== undefined) {\n\t\tif (!Number.isSafeInteger(availabilityMaxSourceBytes) || availabilityMaxSourceBytes <= 0)\n\t\t\tthrow new Error(\"Invalid parent-path materialization limits\");\n\t\tif (branch.length > 16_384) throw new Error(\"Parent-path entry budget exceeded\");\n\t\tlet bytes = 0;\n\t\tfor (const entry of branch) {\n\t\t\tbytes += Buffer.byteLength(stringifyBoundedJson(entry, availabilityMaxSourceBytes - bytes));\n\t\t}\n\t}\n\treturn {\n\t\t...computeOwnAndTotalUsage(branch, snapshot.entries),\n\t\t...(availabilityMaxSourceBytes === undefined ? {} : { hasPostCompactionUsage: hasPostCompactionUsage(branch) }),\n\t};\n}\n\n/** Detached, complete source usage and its exact captured parent branch. */\nexport async function readContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\trequest?: ContextTreeRequest,\n\tavailabilityMaxSourceBytes?: number,\n): Promise<\n\t{ source: SourceSnapshotRef; ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } | undefined\n> {\n\tif (!manager.supportsCapturedHistoryReads()) return undefined;\n\tconst sourceLimits = request?.limits ?? limits;\n\tconst capturedLimits = { maxEntries: sourceLimits.maxEntries, maxSourceBytes: sourceLimits.maxSourceBytes };\n\t// The actual source frontier binds NOW, never after waiting for the reduction slot.\n\treturn manager.readSourceHistory((history) => {\n\t\trequest?.retainMetadata(history.source);\n\t\tconst reduce = async () => {\n\t\t\tconst materialized = await history.materialize(capturedLimits);\n\t\t\tconst allEntries = materialized.entries.map(({ entry }) => entry);\n\t\t\tapplyChildUsageAttributions(allEntries);\n\t\t\tconst byId = new Map(allEntries.map((entry) => [entry.id, entry]));\n\t\t\tconst branch: SessionEntry[] = [];\n\t\t\tlet cursor: ParentPathCursor | undefined;\n\t\t\tdo {\n\t\t\t\tconst page = await history.parentPath({ cursor });\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tconst entry = byId.get(reference.id);\n\t\t\t\t\tif (!entry) throw new Error(\"Context-tree parent-path entry source is unavailable\");\n\t\t\t\t\tbranch.push(entry);\n\t\t\t\t}\n\t\t\t\tcursor = page.nextCursor ?? undefined;\n\t\t\t} while (cursor);\n\t\t\tlet available: boolean | undefined;\n\t\t\tif (availabilityMaxSourceBytes !== undefined) {\n\t\t\t\tconst bootstrap = await history.branchBootstrap();\n\t\t\t\tavailable = !bootstrap.latestCompaction;\n\t\t\t\tconst reference = bootstrap.contextUsageAssistant;\n\t\t\t\tif (bootstrap.latestCompaction && reference) {\n\t\t\t\t\tconst updates = await history.branchContext.contextUpdates({\n\t\t\t\t\t\tkind: \"assistant-usage\",\n\t\t\t\t\t\ttargetId: reference.id,\n\t\t\t\t\t});\n\t\t\t\t\tconst bytes =\n\t\t\t\t\t\treference.locator.length + updates.refs.reduce((sum, update) => sum + update.locator.length, 0);\n\t\t\t\t\tif (bytes > availabilityMaxSourceBytes) throw new Error(\"Context usage source byte budget exceeded\");\n\t\t\t\t\tconst assistant = byId.get(reference.id);\n\t\t\t\t\tif (!assistant || !isAssistantEntry(assistant))\n\t\t\t\t\t\tthrow new Error(\"Context usage assistant source is unavailable\");\n\t\t\t\t\t// Full-source ordered projection above includes off-branch attributions.\n\t\t\t\t\tavailable = calculateContextTokens(assistant.message.usage) > 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst usage = {\n\t\t\t\t...computeOwnAndTotalUsage(branch, allEntries),\n\t\t\t\t...(available === undefined ? {} : { hasPostCompactionUsage: available }),\n\t\t\t};\n\t\t\trequest?.retainMetadata(usage);\n\t\t\treturn { source: history.source, ...usage };\n\t\t};\n\t\treturn request ? request.read(reduce) : reduce();\n\t});\n}\n\nfunction hasPostCompactionUsage(branch: SessionEntry[]): boolean {\n\tlet boundary = -1;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tif (branch[index].type === \"compaction\") {\n\t\t\tboundary = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (boundary < 0) return true;\n\tfor (let index = branch.length - 1; index > boundary; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isAssistantEntry(entry)) continue;\n\t\tif (entry.message.stopReason !== \"aborted\" && entry.message.stopReason !== \"error\")\n\t\t\treturn calculateContextTokens(entry.message.usage) > 0;\n\t}\n\treturn false;\n}\n\n/**\n * Current context utilization from persisted entries, mirroring\n * AgentSession.getContextUsage(): unknown right after a compaction until the\n * next assistant response, otherwise the last assistant usage plus an\n * estimate for trailing messages (tool results, queued user input) that have\n * not hit the model yet.\n */\nfunction computeContextUsageFromEntries(\n\tallEntries: SessionEntry[],\n\tbranch: SessionEntry[],\n\tcontextWindow: number | undefined,\n): ContextUsage | undefined {\n\tif (!contextWindow || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tif (!hasPostCompactionUsage(branch)) {\n\t\treturn { tokens: null, contextWindow, percent: null };\n\t}\n\n\tconst estimate = estimateContextTokens(buildSessionContext(allEntries).messages);\n\tif (estimate.tokens <= 0) {\n\t\treturn undefined;\n\t}\n\treturn { tokens: estimate.tokens, contextWindow, percent: (estimate.tokens / contextWindow) * 100 };\n}\n\n/**\n * Entries on the current branch, root to leaf, mirroring\n * SessionManager.getBranch(): the leaf is the last appended entry and the\n * branch is its parentId chain. Keeps forked/abandoned paths out of usage\n * sums so disk nodes match what a live session would report.\n */\nfunction branchEntries(entries: SessionEntry[], leafId?: string | null, strict = false): SessionEntry[] {\n\tif (entries.length === 0) {\n\t\tif (strict && leafId !== undefined && leafId !== null) throw new Error(\"Parent path lineage is unresolved\");\n\t\treturn [];\n\t}\n\tconst byId = new Map(entries.map((entry) => [entry.id, entry]));\n\tconst branch: SessionEntry[] = [];\n\tconst seen = new Set<string>();\n\tlet current: SessionEntry | undefined =\n\t\tleafId === undefined ? entries[entries.length - 1] : leafId === null ? undefined : byId.get(leafId);\n\tif (strict && leafId !== undefined && leafId !== null && !current)\n\t\tthrow new Error(\"Parent path lineage is unresolved\");\n\twhile (current && !seen.has(current.id)) {\n\t\tseen.add(current.id);\n\t\tbranch.push(current);\n\t\tconst parentId = current.parentId;\n\t\tconst hasParent = strict ? parentId !== null : !!parentId;\n\t\tcurrent = hasParent ? byId.get(parentId!) : undefined;\n\t\tif (strict && hasParent && !current) throw new Error(\"Parent path lineage is unresolved\");\n\t}\n\tif (strict && current) throw new Error(\"Parent path lineage is unresolved\");\n\treturn branch.reverse();\n}\n\n/**\n * Terminal status for a persisted child, inferred from how its last assistant\n * turn ended: errored and aborted runs should not render as successful.\n */\nfunction statusFromBranch(entries: SessionEntry[]): \"done\" | \"error\" | \"cancelled\" {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (!isAssistantEntry(entry)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.message.stopReason === \"error\") {\n\t\t\treturn \"error\";\n\t\t}\n\t\tif (entry.message.stopReason === \"aborted\") {\n\t\t\treturn \"cancelled\";\n\t\t}\n\t\treturn \"done\";\n\t}\n\treturn \"done\";\n}\n\n/** Stream names; opening/reading errors keep the caller's existing policy. */\nfunction visitDirectory(dirPath: string, request: ContextTreeRequest, visit: (name: string) => void): void {\n\tconst dir = opendirSync(dirPath);\n\ttry {\n\t\tfor (let entry = dir.readSync(); entry !== null; entry = dir.readSync()) {\n\t\t\trequest.directoryEntry();\n\t\t\tvisit(entry.name);\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdir.closeSync();\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Context tree directory read and close failed\");\n\t\t}\n\t\tthrow error;\n\t}\n\tdir.closeSync();\n}\n\n// readdirSync used UTF8 lexical order; retain its stable mtime-tie ordering.\nfunction comparePaths(a: string, b: string): number {\n\treturn Buffer.compare(Buffer.from(a), Buffer.from(b));\n}\n\nfunction findSessionFile(dir: string, request: ContextTreeRequest): { path: string; bytes: number } | undefined {\n\tlet newest: { path: string; mtime: number; bytes: number } | undefined;\n\ttry {\n\t\tvisitDirectory(dir, request, (name) => {\n\t\t\tif (!name.endsWith(\".jsonl\")) return;\n\t\t\tconst path = join(dir, name);\n\t\t\tlet mtime: number;\n\t\t\ttry {\n\t\t\t\tmtime = statSync(path).mtime.getTime();\n\t\t\t} catch {\n\t\t\t\treturn; // Skip unreadable files.\n\t\t\t}\n\t\t\tif (!newest || mtime > newest.mtime || (mtime === newest.mtime && comparePaths(path, newest.path) < 0)) {\n\t\t\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\t\t\tnewest = undefined;\n\t\t\t\tconst bytes = request.retainMetadata(path);\n\t\t\t\tnewest = { path, mtime, bytes };\n\t\t\t}\n\t\t});\n\t\treturn newest;\n\t} catch (error) {\n\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\tthrow error;\n\t}\n}\n\nfunction listChildSessionDirs(rlmSessionDir: string, request: ContextTreeRequest): { paths: string[]; bytes: number } {\n\tconst paths: string[] = [];\n\tlet bytes = 0;\n\ttry {\n\t\tvisitDirectory(rlmSessionDir, request, (name) => {\n\t\t\tif (!name.startsWith(\"sub-\")) return;\n\t\t\tconst path = join(rlmSessionDir, name);\n\t\t\ttry {\n\t\t\t\tif (!statSync(path).isDirectory()) return;\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes += request.retainMetadata(path);\n\t\t\tpaths.push(path);\n\t\t});\n\t} catch (error) {\n\t\trequest.releaseMetadata(bytes);\n\t\tif (error instanceof ContextTreeLimitError || error instanceof AggregateError) throw error;\n\t\treturn { paths: [], bytes: 0 };\n\t}\n\tpaths.sort(comparePaths).sort((a, b) => {\n\t\ttry {\n\t\t\treturn statSync(a).mtime.getTime() - statSync(b).mtime.getTime();\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t});\n\treturn { paths, bytes };\n}\n\n/**\n * Build a context node for a completed RLM child from its persisted session\n * dir (sub-xxxx/). Children that already attributed grandchild usage carry the\n * aggregate on their assistant messages (applyChildUsageAttributions), so own\n * usage is recovered by subtracting the attribution entries. Returns undefined\n * when the dir holds no readable session.\n */\nasync function readContextTreeChildNodeFromDisk(\n\tchildSessionDir: string,\n\tsessionFile: string,\n\tresolveContextWindow: ContextWindowResolver,\n\trequest: ContextTreeRequest,\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst allEntries = (await readSessionHistoryFile(sessionFile, request.limits)).filter(\n\t\t(entry): entry is SessionEntry => entry.type !== \"session\",\n\t);\n\tconst branch = branchEntries(allEntries);\n\tif (branch.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tconst { ownUsage, totalUsage } = computeOwnAndTotalUsage(branch, allEntries);\n\n\tlet model: { provider: string; id: string } | undefined;\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, id: entry.modelId };\n\t\t}\n\t}\n\n\tlet label = \"\";\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"user\") {\n\t\t\tlabel = compactLabel(readUserMessageText(entry.message.content));\n\t\t\tif (label) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst contextWindow = model ? resolveContextWindow(model.provider, model.id) : undefined;\n\n\tconst metadata = {\n\t\t...(identity ?? {\n\t\t\tid: basename(childSessionDir),\n\t\t\tlabel: label || \"child agent\",\n\t\t\tstatus: statusFromBranch(branch),\n\t\t}),\n\t\tmodel,\n\t\townUsage,\n\t\ttotalUsage,\n\t\tcontextUsage: computeContextUsageFromEntries(allEntries, branch, contextWindow),\n\t};\n\t// A registered run's identity was already admitted by its live parent.\n\trequest.retainMetadata(identity ? { model, ownUsage, totalUsage, contextUsage: metadata.contextUsage } : metadata);\n\treturn { ...metadata, children: [] };\n}\n\n/** Complete or refuse, sharing the request's slot and counters with descendants.\n * Internal identity is an already-admitted registered run, including its empty placeholder.\n */\nexport async function loadContextTreeChildFromDisk(\n\tchildSessionDir: string,\n\tresolveContextWindow: ContextWindowResolver,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst request = treeRequest(limits);\n\tconst directoryBytes = request.retainMetadata(childSessionDir);\n\tlet sessionFile: { path: string; bytes: number } | undefined;\n\tlet node: ContextTreeNode | undefined;\n\ttry {\n\t\tsessionFile = findSessionFile(childSessionDir, request);\n\t\tif (sessionFile && existsSync(sessionFile.path)) {\n\t\t\t// A header-only history still consumes one bounded source admission.\n\t\t\tif (!identity) request.admitNode();\n\t\t\tnode = await request.read(() =>\n\t\t\t\treadContextTreeChildNodeFromDisk(\n\t\t\t\t\tchildSessionDir,\n\t\t\t\t\tsessionFile!.path,\n\t\t\t\t\tresolveContextWindow,\n\t\t\t\t\trequest,\n\t\t\t\t\tidentity,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tif (sessionFile) request.releaseMetadata(sessionFile.bytes);\n\t\trequest.releaseMetadata(directoryBytes);\n\t}\n\tif (node) {\n\t\t// The full source has been reduced and the serial slot released before recursion.\n\t\tnode.children = await loadContextTreeChildrenFromDisk(childSessionDir, resolveContextWindow, undefined, request);\n\t} else if (identity) {\n\t\tconst usage = { ownUsage: emptyUsage(), totalUsage: emptyUsage() };\n\t\trequest.retainMetadata(usage);\n\t\tnode = { ...identity, ...usage, children: [] };\n\t}\n\treturn node;\n}\n\n/** Persisted children, in existing directory order, excluding already represented live IDs. */\nexport async function loadContextTreeChildrenFromDisk(\n\trlmSessionDir: string | undefined,\n\tresolveContextWindow: ContextWindowResolver,\n\tskipIds?: ReadonlySet<string>,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n): Promise<ContextTreeNode[]> {\n\tconst request = treeRequest(limits);\n\tconst skippedIds = new Set<string>();\n\tlet metadataBytes = 0;\n\ttry {\n\t\t// A caller-provided skip set is bounded before copying, too.\n\t\tif (skipIds && skipIds.size > request.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tfor (const id of skipIds ?? []) {\n\t\t\tmetadataBytes += request.retainMetadata(id);\n\t\t\tskippedIds.add(id);\n\t\t}\n\t\tif (!rlmSessionDir || !existsSync(rlmSessionDir)) return [];\n\t\tmetadataBytes += request.retainMetadata(rlmSessionDir);\n\t\tconst directories = listChildSessionDirs(rlmSessionDir, request);\n\t\tmetadataBytes += directories.bytes;\n\t\tconst nodes: ContextTreeNode[] = [];\n\t\tfor (const childDir of directories.paths) {\n\t\t\tif (skippedIds.has(basename(childDir))) continue;\n\t\t\tconst node = await loadContextTreeChildFromDisk(childDir, resolveContextWindow, request);\n\t\t\tif (node) nodes.push(node);\n\t\t}\n\t\treturn nodes;\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n"]}
1
+ {"version":3,"file":"context-tree.js","sourceRoot":"","sources":["../../src/core/context-tree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAK/D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EACN,2BAA2B,EAC3B,mBAAmB,GAInB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AA4B/F,MAAM,qBAAsB,SAAQ,KAAK;CAAG;AAE5C,8EAA8E;AAC9E,MAAM,OAAO,kBAAkB;IACrB,MAAM,CAAqC;IAC5C,KAAK,GAAG,CAAC,CAAC;IACV,aAAa,GAAG,CAAC,CAAC;IAClB,gBAAgB,GAAG,CAAC,CAAC;IACrB,QAAQ,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEpD,YAAY,MAAM,GAAsC,EAAE,EAAE;QAC3D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;YAC3B,GAAG,mBAAmB,CA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AM,WAAW,GAAG,oBAAoB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QACjE,aAAa,IAAI,WAAW,CAAC,KAAK,CAAC;QACnC,MAAM,KAAK,GAAsB,EAAE,CAAC;QACpC,KAAK,MAAM,QAAQ,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;YAC1C,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;gBAAE,SAAS;YACjD,MAAM,IAAI,GAAG,MAAM,4BAA4B,CAAC,QAAQ,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAC;YACzF,IAAI,IAAI;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACV,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;AAAA,CACD","sourcesContent":["import { existsSync, opendirSync, statSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { AssistantMessage, Usage } from \"@ponythewhite/base-context-ai\";\nimport type { RlmChildAgentStatus } from \"./agent-session.js\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { calculateContextTokens, estimateContextTokens } from \"./compaction/index.js\";\nimport { exportHistoryLimits } from \"./export-html/history.js\";\nimport type { ContextUsage } from \"./extensions/index.js\";\nimport type { IndexedSourceEvent, ParentPathCursor } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport { readCapturedSessionJournal } from \"./session-journal-reader.js\";\nimport {\n\tapplyChildUsageAttributions,\n\tbuildSessionContext,\n\ttype FileEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"./session-manager.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, subtractAssistantUsage } from \"./usage.js\";\n\n/** Resolves a model's context window so disk-only nodes can report utilization. */\nexport type ContextWindowResolver = (provider: string, modelId: string) => number | undefined;\n\n/**\n * One agent in the context overview: the main session or an RLM (sub-)agent.\n * `ownUsage` excludes descendants; `totalUsage` includes completed descendants, matching /usage.\n */\nexport interface ContextTreeNode {\n\t/** \"root\" for the session itself; sub-xxxx for an RLM child. */\n\tid: string;\n\tlabel: string;\n\tstatus: \"active\" | RlmChildAgentStatus;\n\tmodel?: { provider: string; id: string };\n\townUsage: Usage;\n\ttotalUsage: Usage;\n\tcontextUsage?: ContextUsage;\n\tchildren: ContextTreeNode[];\n}\n\n/** Shared by one overview request, not by concurrent requests or the process. */\nexport interface ContextTreeRequestLimits extends SessionHistoryReadLimits {\n\tmaxNodes: number;\n\tmaxMetadataBytes: number;\n\tmaxDirectoryEntries: number;\n}\n\nclass ContextTreeLimitError extends Error {}\n\n/** Small request-local counters and one history-projection reduction tail. */\nexport class ContextTreeRequest {\n\treadonly limits: Readonly<ContextTreeRequestLimits>;\n\tprivate nodes = 0;\n\tprivate metadataBytes = 0;\n\tprivate directoryEntries = 0;\n\tprivate readTail: Promise<void> = Promise.resolve();\n\n\tconstructor(limits: Partial<ContextTreeRequestLimits> = {}) {\n\t\tthis.limits = Object.freeze({\n\t\t\t...exportHistoryLimits(limits),\n\t\t\tmaxNodes: limits.maxNodes ?? 256,\n\t\t\tmaxMetadataBytes: limits.maxMetadataBytes ?? 4 * 1024 * 1024,\n\t\t\tmaxDirectoryEntries: limits.maxDirectoryEntries ?? 16_384,\n\t\t});\n\t\tif (!Object.values(this.limits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\t\tthrow new Error(\"Invalid context tree request limits\");\n\t}\n\n\tadmitNode(): void {\n\t\tif (this.nodes >= this.limits.maxNodes) throw new ContextTreeLimitError(\"Context tree node budget exceeded\");\n\t\tthis.nodes++;\n\t}\n\n\tretainMetadata(value: unknown): number {\n\t\tlet json: string;\n\t\ttry {\n\t\t\tjson = stringifyBoundedJson(value, this.limits.maxMetadataBytes - this.metadataBytes);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"JSON byte limit exceeded\")\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree metadata byte budget exceeded\", { cause: error });\n\t\t\tthrow error;\n\t\t}\n\t\tconst bytes = Buffer.byteLength(json);\n\t\tthis.metadataBytes += bytes;\n\t\treturn bytes;\n\t}\n\n\treleaseMetadata(bytes: number): void {\n\t\tthis.metadataBytes -= bytes;\n\t}\n\n\tdirectoryEntry(): void {\n\t\tif (this.directoryEntries >= this.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tthis.directoryEntries++;\n\t}\n\n\tread<T>(read: () => Promise<T>): Promise<T> {\n\t\tconst result = this.readTail.then(read);\n\t\tthis.readTail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n}\n\nfunction treeRequest(limits: Partial<ContextTreeRequestLimits> | ContextTreeRequest): ContextTreeRequest {\n\treturn limits instanceof ContextTreeRequest ? limits : new ContextTreeRequest(limits);\n}\n\nfunction isAssistantEntry(entry: SessionEntry): entry is SessionEntry & {\n\ttype: \"message\";\n\tmessage: AssistantMessage;\n} {\n\treturn entry.type === \"message\" && entry.message.role === \"assistant\";\n}\n\nfunction readUserMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t(block as { type?: unknown }).type === \"text\" &&\n\t\t\t\ttypeof (block as { text?: unknown }).text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\");\n}\n\nfunction compactLabel(text: string, maxLength = 80): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\tif (compact.length <= maxLength) {\n\t\treturn compact;\n\t}\n\treturn `${compact.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\n/**\n * Usage totals for one agent: `totalUsage` sums the branch's assistant usage\n * (attributed aggregates, so descendants are included), `ownUsage` removes the\n * attributions targeting those assistants. Attribution entries are matched by\n * target across ALL entries, not just the branch: attributions rewrite the\n * target assistant's usage no matter which branch they were appended on, so a\n * fork that keeps the assistant but drops the attribution entry must still\n * subtract it.\n *\n * Totals are deliberately cumulative across compactions: compaction shrinks\n * the model-facing context, not what the session has spent, so assistants\n * dropped from the resolved context still count here.\n */\nexport function computeOwnAndTotalUsage(\n\tbranch: SessionEntry[],\n\tallEntries: SessionEntry[],\n): { ownUsage: Usage; totalUsage: Usage } {\n\tconst totalUsage = emptyUsage();\n\tconst branchAssistantIds = new Set<string>();\n\tfor (const entry of branch) {\n\t\tif (isAssistantEntry(entry)) {\n\t\t\tbranchAssistantIds.add(entry.id);\n\t\t\taddAssistantUsage(totalUsage, entry.message.usage);\n\t\t} else if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) {\n\t\t\taddAssistantUsage(totalUsage, entry.usage);\n\t\t}\n\t}\n\tconst ownUsage = cloneUsage(totalUsage);\n\tfor (const entry of allEntries) {\n\t\tif (entry.type === \"child_usage_attributed\" && branchAssistantIds.has(entry.targetId)) {\n\t\t\tsubtractAssistantUsage(ownUsage, entry.childUsage);\n\t\t}\n\t}\n\treturn { ownUsage, totalUsage };\n}\n\n/** Complete bounded snapshot of an explicitly resident Manager, never an index-error fallback.\n * This synchronous reduction runs in the pre-await live-tree capture walk. It never\n * retains a decoded resident snapshot while native/disk work waits for a slot.\n */\nexport function readResidentContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\tavailabilityMaxSourceBytes?: number,\n): { ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } {\n\tconst snapshot = manager.materializeResidentHistory(limits);\n\tconst branch = branchEntries(snapshot.entries, snapshot.leafId, availabilityMaxSourceBytes !== undefined);\n\tif (availabilityMaxSourceBytes !== undefined) {\n\t\tif (!Number.isSafeInteger(availabilityMaxSourceBytes) || availabilityMaxSourceBytes <= 0)\n\t\t\tthrow new Error(\"Invalid parent-path materialization limits\");\n\t\tif (branch.length > 16_384) throw new Error(\"Parent-path entry budget exceeded\");\n\t\tlet bytes = 0;\n\t\tfor (const entry of branch) {\n\t\t\tbytes += Buffer.byteLength(stringifyBoundedJson(entry, availabilityMaxSourceBytes - bytes));\n\t\t}\n\t}\n\treturn {\n\t\t...computeOwnAndTotalUsage(branch, snapshot.entries),\n\t\t...(availabilityMaxSourceBytes === undefined ? {} : { hasPostCompactionUsage: hasPostCompactionUsage(branch) }),\n\t};\n}\n\nfunction isContextTreeUsageReference(reference: IndexedSourceEvent): boolean {\n\treturn (\n\t\t(reference.kind === \"message\" && reference.authority === \"assistant\") ||\n\t\treference.kind === \"compaction\" ||\n\t\treference.kind === \"branch_summary\" ||\n\t\treference.kind === \"child_usage_attributed\"\n\t);\n}\n\n/** Detached, complete source usage and its exact captured parent branch. */\nexport async function readContextTreeUsage(\n\tmanager: SessionManager,\n\tlimits: SessionHistoryReadLimits = { maxEntries: 16_384, maxSourceBytes: 64 * 1024 * 1024 },\n\trequest?: ContextTreeRequest,\n\tavailabilityMaxSourceBytes?: number,\n): Promise<\n\t{ source: SourceSnapshotRef; ownUsage: Usage; totalUsage: Usage; hasPostCompactionUsage?: boolean } | undefined\n> {\n\tif (!manager.supportsCapturedHistoryReads()) return undefined;\n\tconst sourceLimits = request?.limits ?? limits;\n\tconst capturedLimits = { maxEntries: sourceLimits.maxEntries, maxSourceBytes: sourceLimits.maxSourceBytes };\n\tif (!Object.values(capturedLimits).every((value) => Number.isSafeInteger(value) && value > 0))\n\t\tthrow new Error(\"Invalid history materialization limits\");\n\t// The actual source frontier binds NOW, never after waiting for the reduction slot.\n\treturn manager.readSourceHistory((history) => {\n\t\trequest?.retainMetadata(history.source);\n\t\tconst reduce = async () => {\n\t\t\tconst allEntries: SessionEntry[] = [];\n\t\t\tlet sourceBytes = 0;\n\t\t\tlet after = 0;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await history.page(after);\n\t\t\t\tif (page.indexedThrough < history.source.sourceSequence)\n\t\t\t\t\tthrow new Error(\"Captured history has incomplete index coverage\");\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tif (!isContextTreeUsageReference(reference)) continue;\n\t\t\t\t\tif (allEntries.length >= capturedLimits.maxEntries) throw new Error(\"History entry budget exceeded\");\n\t\t\t\t\tif (sourceBytes + reference.locator.length > capturedLimits.maxSourceBytes)\n\t\t\t\t\t\tthrow new Error(\"History source byte budget exceeded\");\n\t\t\t\t\tconst hydrated = await history.hydrateEntry(reference.id, capturedLimits.maxSourceBytes - sourceBytes);\n\t\t\t\t\tif (!hydrated) throw new Error(\"Context-tree usage entry source is unavailable\");\n\t\t\t\t\tallEntries.push(hydrated.entry);\n\t\t\t\t\tsourceBytes += reference.locator.length;\n\t\t\t\t}\n\t\t\t\tif (page.nextAfter === null) break;\n\t\t\t\tafter = page.nextAfter;\n\t\t\t}\n\t\t\tapplyChildUsageAttributions(allEntries);\n\t\t\tconst byId = new Map(allEntries.map((entry) => [entry.id, entry]));\n\t\t\tconst branch: SessionEntry[] = [];\n\t\t\tlet cursor: ParentPathCursor | undefined;\n\t\t\tdo {\n\t\t\t\tconst page = await history.parentPath({ cursor });\n\t\t\t\tfor (const reference of page.events) {\n\t\t\t\t\tif (!isContextTreeUsageReference(reference)) continue;\n\t\t\t\t\tconst entry = byId.get(reference.id);\n\t\t\t\t\tif (!entry) throw new Error(\"Context-tree parent-path entry source is unavailable\");\n\t\t\t\t\tbranch.push(entry);\n\t\t\t\t}\n\t\t\t\tcursor = page.nextCursor ?? undefined;\n\t\t\t} while (cursor);\n\t\t\tlet available: boolean | undefined;\n\t\t\tif (availabilityMaxSourceBytes !== undefined) {\n\t\t\t\tconst bootstrap = await history.branchBootstrap();\n\t\t\t\tavailable = !bootstrap.latestCompaction;\n\t\t\t\tconst reference = bootstrap.contextUsageAssistant;\n\t\t\t\tif (bootstrap.latestCompaction && reference) {\n\t\t\t\t\tconst updates = await history.branchContext.contextUpdates({\n\t\t\t\t\t\tkind: \"assistant-usage\",\n\t\t\t\t\t\ttargetId: reference.id,\n\t\t\t\t\t});\n\t\t\t\t\tconst bytes =\n\t\t\t\t\t\treference.locator.length + updates.refs.reduce((sum, update) => sum + update.locator.length, 0);\n\t\t\t\t\tif (bytes > availabilityMaxSourceBytes) throw new Error(\"Context usage source byte budget exceeded\");\n\t\t\t\t\tconst assistant = byId.get(reference.id);\n\t\t\t\t\tif (!assistant || !isAssistantEntry(assistant))\n\t\t\t\t\t\tthrow new Error(\"Context usage assistant source is unavailable\");\n\t\t\t\t\t// Full-source ordered projection above includes off-branch attributions.\n\t\t\t\t\tavailable = calculateContextTokens(assistant.message.usage) > 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst usage = {\n\t\t\t\t...computeOwnAndTotalUsage(branch, allEntries),\n\t\t\t\t...(available === undefined ? {} : { hasPostCompactionUsage: available }),\n\t\t\t};\n\t\t\trequest?.retainMetadata(usage);\n\t\t\treturn { source: history.source, ...usage };\n\t\t};\n\t\treturn request ? request.read(reduce) : reduce();\n\t});\n}\n\nfunction hasPostCompactionUsage(branch: SessionEntry[]): boolean {\n\tlet boundary = -1;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tif (branch[index].type === \"compaction\") {\n\t\t\tboundary = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (boundary < 0) return true;\n\tfor (let index = branch.length - 1; index > boundary; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isAssistantEntry(entry)) continue;\n\t\tif (entry.message.stopReason !== \"aborted\" && entry.message.stopReason !== \"error\")\n\t\t\treturn calculateContextTokens(entry.message.usage) > 0;\n\t}\n\treturn false;\n}\n\n/**\n * Current context utilization from persisted entries, mirroring\n * AgentSession.getContextUsage(): unknown right after a compaction until the\n * next assistant response, otherwise the last assistant usage plus an\n * estimate for trailing messages (tool results, queued user input) that have\n * not hit the model yet.\n */\nfunction computeContextUsageFromEntries(\n\tallEntries: SessionEntry[],\n\tbranch: SessionEntry[],\n\tcontextWindow: number | undefined,\n): ContextUsage | undefined {\n\tif (!contextWindow || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tif (!hasPostCompactionUsage(branch)) {\n\t\treturn { tokens: null, contextWindow, percent: null };\n\t}\n\n\tconst estimate = estimateContextTokens(buildSessionContext(allEntries, branch.at(-1)?.id ?? null).messages);\n\tif (estimate.tokens <= 0) {\n\t\treturn undefined;\n\t}\n\treturn { tokens: estimate.tokens, contextWindow, percent: (estimate.tokens / contextWindow) * 100 };\n}\n\n/**\n * Entries on the current branch, root to leaf, mirroring\n * SessionManager.getBranch(): the leaf is the last appended entry and the\n * branch is its parentId chain. Keeps forked/abandoned paths out of usage\n * sums so disk nodes match what a live session would report.\n */\nfunction branchEntries(entries: SessionEntry[], leafId?: string | null, strict = false): SessionEntry[] {\n\tif (entries.length === 0) {\n\t\tif (strict && leafId !== undefined && leafId !== null) throw new Error(\"Parent path lineage is unresolved\");\n\t\treturn [];\n\t}\n\tconst byId = new Map(entries.map((entry) => [entry.id, entry]));\n\tconst branch: SessionEntry[] = [];\n\tconst seen = new Set<string>();\n\tlet current: SessionEntry | undefined =\n\t\tleafId === undefined ? entries[entries.length - 1] : leafId === null ? undefined : byId.get(leafId);\n\tif (strict && leafId !== undefined && leafId !== null && !current)\n\t\tthrow new Error(\"Parent path lineage is unresolved\");\n\twhile (current && !seen.has(current.id)) {\n\t\tseen.add(current.id);\n\t\tbranch.push(current);\n\t\tconst parentId = current.parentId;\n\t\tconst hasParent = strict ? parentId !== null : !!parentId;\n\t\tcurrent = hasParent ? byId.get(parentId!) : undefined;\n\t\tif (strict && hasParent && !current) throw new Error(\"Parent path lineage is unresolved\");\n\t}\n\tif (strict && current) throw new Error(\"Parent path lineage is unresolved\");\n\treturn branch.reverse();\n}\n\n/**\n * Terminal status for a persisted child, inferred from how its last assistant\n * turn ended: errored and aborted runs should not render as successful.\n */\nfunction statusFromBranch(entries: SessionEntry[]): \"done\" | \"error\" | \"cancelled\" {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (!isAssistantEntry(entry)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.message.stopReason === \"error\") {\n\t\t\treturn \"error\";\n\t\t}\n\t\tif (entry.message.stopReason === \"aborted\") {\n\t\t\treturn \"cancelled\";\n\t\t}\n\t\treturn \"done\";\n\t}\n\treturn \"done\";\n}\n\n/** Stream names; opening/reading errors keep the caller's existing policy. */\nfunction visitDirectory(dirPath: string, request: ContextTreeRequest, visit: (name: string) => void): void {\n\tconst dir = opendirSync(dirPath);\n\ttry {\n\t\tfor (let entry = dir.readSync(); entry !== null; entry = dir.readSync()) {\n\t\t\trequest.directoryEntry();\n\t\t\tvisit(entry.name);\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tdir.closeSync();\n\t\t} catch (closeError) {\n\t\t\tthrow new AggregateError([error, closeError], \"Context tree directory read and close failed\");\n\t\t}\n\t\tthrow error;\n\t}\n\tdir.closeSync();\n}\n\n// readdirSync used UTF8 lexical order; retain its stable mtime-tie ordering.\nfunction comparePaths(a: string, b: string): number {\n\treturn Buffer.compare(Buffer.from(a), Buffer.from(b));\n}\n\nfunction findSessionFile(dir: string, request: ContextTreeRequest): { path: string; bytes: number } | undefined {\n\tlet newest: { path: string; mtime: number; bytes: number } | undefined;\n\ttry {\n\t\tvisitDirectory(dir, request, (name) => {\n\t\t\tif (!name.endsWith(\".jsonl\")) return;\n\t\t\tconst path = join(dir, name);\n\t\t\tlet mtime: number;\n\t\t\ttry {\n\t\t\t\tmtime = statSync(path).mtime.getTime();\n\t\t\t} catch {\n\t\t\t\treturn; // Skip unreadable files.\n\t\t\t}\n\t\t\tif (!newest || mtime > newest.mtime || (mtime === newest.mtime && comparePaths(path, newest.path) < 0)) {\n\t\t\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\t\t\tnewest = undefined;\n\t\t\t\tconst bytes = request.retainMetadata(path);\n\t\t\t\tnewest = { path, mtime, bytes };\n\t\t\t}\n\t\t});\n\t\treturn newest;\n\t} catch (error) {\n\t\tif (newest) request.releaseMetadata(newest.bytes);\n\t\tthrow error;\n\t}\n}\n\nfunction listChildSessionDirs(rlmSessionDir: string, request: ContextTreeRequest): { paths: string[]; bytes: number } {\n\tconst paths: string[] = [];\n\tlet bytes = 0;\n\ttry {\n\t\tvisitDirectory(rlmSessionDir, request, (name) => {\n\t\t\tif (!name.startsWith(\"sub-\")) return;\n\t\t\tconst path = join(rlmSessionDir, name);\n\t\t\ttry {\n\t\t\t\tif (!statSync(path).isDirectory()) return;\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes += request.retainMetadata(path);\n\t\t\tpaths.push(path);\n\t\t});\n\t} catch (error) {\n\t\trequest.releaseMetadata(bytes);\n\t\tif (error instanceof ContextTreeLimitError || error instanceof AggregateError) throw error;\n\t\treturn { paths: [], bytes: 0 };\n\t}\n\tpaths.sort(comparePaths).sort((a, b) => {\n\t\ttry {\n\t\t\treturn statSync(a).mtime.getTime() - statSync(b).mtime.getTime();\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t});\n\treturn { paths, bytes };\n}\n\n/** Read a fixed disk prefix without retaining private request or tool-intent bodies. */\nasync function readContextTreeProjectionFromDisk(\n\tsessionFile: string,\n\trequest: ContextTreeRequest,\n): Promise<{ entries: SessionEntry[]; leafId: string | null; hasSourceLeaf: boolean }> {\n\tconst entries: SessionEntry[] = [];\n\tconst hiddenParents = new Map<string, string | null>();\n\tlet leafId: string | null = null;\n\tlet hasHeader = false;\n\tlet sourceBytes = 0;\n\tlet metadataBytes = 0;\n\ttry {\n\t\tawait readCapturedSessionJournal(sessionFile, (record) => {\n\t\t\tconst value = record.entry;\n\t\t\tif (!value || typeof value !== \"object\" || !(\"type\" in value) || typeof value.type !== \"string\")\n\t\t\t\tthrow new Error(\"Invalid session journal entry\");\n\t\t\tconst entry = value as FileEntry;\n\t\t\tif (!hasHeader) {\n\t\t\t\tif (entry.type !== \"session\" || typeof entry.id !== \"string\")\n\t\t\t\t\tthrow new Error(\"Session source has no valid header\");\n\t\t\t\thasHeader = true;\n\t\t\t}\n\t\t\tif (entry.type !== \"session\") leafId = entry.id;\n\t\t\tif (entry.type === \"request\" || entry.type === \"tool_intent\") {\n\t\t\t\tmetadataBytes += request.retainMetadata([entry.id, entry.parentId]);\n\t\t\t\thiddenParents.set(entry.id, entry.parentId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst bytes = record.source?.locator.length ?? Buffer.byteLength(record.json) + 1;\n\t\t\tif (sourceBytes + bytes > request.limits.maxSourceBytes)\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree source byte budget exceeded\");\n\t\t\tsourceBytes += bytes;\n\t\t\tif (entry.type === \"session\") return;\n\t\t\tif (entries.length >= request.limits.maxEntries)\n\t\t\t\tthrow new ContextTreeLimitError(\"Context tree entry budget exceeded\");\n\t\t\tentries.push(entry);\n\t\t});\n\t\tconst visibleParent = (id: string | null): string | null => {\n\t\t\tlet remaining = hiddenParents.size;\n\t\t\twhile (id !== null && hiddenParents.has(id)) {\n\t\t\t\tif (remaining-- === 0) throw new Error(\"Parent path lineage is unresolved\");\n\t\t\t\tid = hiddenParents.get(id)!;\n\t\t\t}\n\t\t\treturn id;\n\t\t};\n\t\tfor (const entry of entries) entry.parentId = visibleParent(entry.parentId);\n\t\t// A trailing private record can select an older branch, not the last visible entry.\n\t\tconst hasSourceLeaf = leafId !== null;\n\t\tleafId = visibleParent(leafId);\n\t\tapplyChildUsageAttributions(entries);\n\t\treturn { entries, leafId, hasSourceLeaf };\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n\n/**\n * Build a context node for a completed RLM child from its persisted session\n * dir (sub-xxxx/). Children that already attributed grandchild usage carry the\n * aggregate on their assistant messages (applyChildUsageAttributions), so own\n * usage is recovered by subtracting the attribution entries. Returns undefined\n * when the dir holds no readable session.\n */\nasync function readContextTreeChildNodeFromDisk(\n\tchildSessionDir: string,\n\tsessionFile: string,\n\tresolveContextWindow: ContextWindowResolver,\n\trequest: ContextTreeRequest,\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst { entries: allEntries, leafId, hasSourceLeaf } = await readContextTreeProjectionFromDisk(sessionFile, request);\n\tconst branch = branchEntries(allEntries, leafId);\n\tif (branch.length === 0 && !hasSourceLeaf) {\n\t\treturn undefined;\n\t}\n\n\tconst { ownUsage, totalUsage } = computeOwnAndTotalUsage(branch, allEntries);\n\n\tlet model: { provider: string; id: string } | undefined;\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, id: entry.modelId };\n\t\t}\n\t}\n\n\tlet label = \"\";\n\tfor (const entry of branch) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"user\") {\n\t\t\tlabel = compactLabel(readUserMessageText(entry.message.content));\n\t\t\tif (label) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst contextWindow = model ? resolveContextWindow(model.provider, model.id) : undefined;\n\n\tconst metadata = {\n\t\t...(identity ?? {\n\t\t\tid: basename(childSessionDir),\n\t\t\tlabel: label || \"child agent\",\n\t\t\tstatus: statusFromBranch(branch),\n\t\t}),\n\t\tmodel,\n\t\townUsage,\n\t\ttotalUsage,\n\t\tcontextUsage: computeContextUsageFromEntries(allEntries, branch, contextWindow),\n\t};\n\t// A registered run's identity was already admitted by its live parent.\n\trequest.retainMetadata(identity ? { model, ownUsage, totalUsage, contextUsage: metadata.contextUsage } : metadata);\n\treturn { ...metadata, children: [] };\n}\n\n/** Complete or refuse, sharing the request's slot and counters with descendants.\n * Internal identity is an already-admitted registered run, including its empty placeholder.\n */\nexport async function loadContextTreeChildFromDisk(\n\tchildSessionDir: string,\n\tresolveContextWindow: ContextWindowResolver,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n\tidentity?: Pick<ContextTreeNode, \"id\" | \"label\" | \"status\">,\n): Promise<ContextTreeNode | undefined> {\n\tconst request = treeRequest(limits);\n\tconst directoryBytes = request.retainMetadata(childSessionDir);\n\tlet sessionFile: { path: string; bytes: number } | undefined;\n\tlet node: ContextTreeNode | undefined;\n\ttry {\n\t\tsessionFile = findSessionFile(childSessionDir, request);\n\t\tif (sessionFile && existsSync(sessionFile.path)) {\n\t\t\t// A header-only history still consumes one bounded source admission.\n\t\t\tif (!identity) request.admitNode();\n\t\t\tnode = await request.read(() =>\n\t\t\t\treadContextTreeChildNodeFromDisk(\n\t\t\t\t\tchildSessionDir,\n\t\t\t\t\tsessionFile!.path,\n\t\t\t\t\tresolveContextWindow,\n\t\t\t\t\trequest,\n\t\t\t\t\tidentity,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tif (sessionFile) request.releaseMetadata(sessionFile.bytes);\n\t\trequest.releaseMetadata(directoryBytes);\n\t}\n\tif (node) {\n\t\t// The full source has been reduced and the serial slot released before recursion.\n\t\tnode.children = await loadContextTreeChildrenFromDisk(childSessionDir, resolveContextWindow, undefined, request);\n\t} else if (identity) {\n\t\tconst usage = { ownUsage: emptyUsage(), totalUsage: emptyUsage() };\n\t\trequest.retainMetadata(usage);\n\t\tnode = { ...identity, ...usage, children: [] };\n\t}\n\treturn node;\n}\n\n/** Persisted children, in existing directory order, excluding already represented live IDs. */\nexport async function loadContextTreeChildrenFromDisk(\n\trlmSessionDir: string | undefined,\n\tresolveContextWindow: ContextWindowResolver,\n\tskipIds?: ReadonlySet<string>,\n\tlimits: Partial<ContextTreeRequestLimits> | ContextTreeRequest = {},\n): Promise<ContextTreeNode[]> {\n\tconst request = treeRequest(limits);\n\tconst skippedIds = new Set<string>();\n\tlet metadataBytes = 0;\n\ttry {\n\t\t// A caller-provided skip set is bounded before copying, too.\n\t\tif (skipIds && skipIds.size > request.limits.maxDirectoryEntries)\n\t\t\tthrow new ContextTreeLimitError(\"Context tree directory entry budget exceeded\");\n\t\tfor (const id of skipIds ?? []) {\n\t\t\tmetadataBytes += request.retainMetadata(id);\n\t\t\tskippedIds.add(id);\n\t\t}\n\t\tif (!rlmSessionDir || !existsSync(rlmSessionDir)) return [];\n\t\tmetadataBytes += request.retainMetadata(rlmSessionDir);\n\t\tconst directories = listChildSessionDirs(rlmSessionDir, request);\n\t\tmetadataBytes += directories.bytes;\n\t\tconst nodes: ContextTreeNode[] = [];\n\t\tfor (const childDir of directories.paths) {\n\t\t\tif (skippedIds.has(basename(childDir))) continue;\n\t\t\tconst node = await loadContextTreeChildFromDisk(childDir, resolveContextWindow, request);\n\t\t\tif (node) nodes.push(node);\n\t\t}\n\t\treturn nodes;\n\t} finally {\n\t\trequest.releaseMetadata(metadataBytes);\n\t}\n}\n"]}