@bastani/atomic 0.9.5-alpha.8 → 0.9.5

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 (530) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +2 -2
  3. package/dist/builtin/cursor/CHANGELOG.md +12 -0
  4. package/dist/builtin/cursor/package.json +3 -3
  5. package/dist/builtin/cursor/src/model-mapper.ts +6 -3
  6. package/dist/builtin/intercom/CHANGELOG.md +37 -0
  7. package/dist/builtin/intercom/README.md +4 -2
  8. package/dist/builtin/intercom/broker/broker.ts +6 -114
  9. package/dist/builtin/intercom/broker/client.ts +29 -54
  10. package/dist/builtin/intercom/broker/delivered-message-cache.ts +44 -0
  11. package/dist/builtin/intercom/broker/pending-send-registry.ts +142 -0
  12. package/dist/builtin/intercom/broker/send-handler.ts +106 -0
  13. package/dist/builtin/intercom/broker/send-signature.ts +37 -0
  14. package/dist/builtin/intercom/foreground-detach-handoff.ts +136 -0
  15. package/dist/builtin/intercom/index-heavy.ts +49 -53
  16. package/dist/builtin/intercom/index.ts +278 -262
  17. package/dist/builtin/intercom/lazy-heavy-proxy.ts +114 -0
  18. package/dist/builtin/intercom/lazy-subagent-ack.ts +20 -0
  19. package/dist/builtin/intercom/lazy-tool-execution.ts +39 -0
  20. package/dist/builtin/intercom/lifecycle-lease.ts +51 -0
  21. package/dist/builtin/intercom/lifecycle.ts +37 -20
  22. package/dist/builtin/intercom/package.json +3 -6
  23. package/dist/builtin/intercom/reply-routing.ts +17 -0
  24. package/dist/builtin/intercom/subagent-relay.ts +58 -12
  25. package/dist/builtin/intercom/types.ts +3 -3
  26. package/dist/builtin/mcp/CHANGELOG.md +38 -0
  27. package/dist/builtin/mcp/OAUTH.md +1 -0
  28. package/dist/builtin/mcp/README.md +10 -6
  29. package/dist/builtin/mcp/apps-cancellation.ts +32 -0
  30. package/dist/builtin/mcp/call-tool-result.ts +9 -0
  31. package/dist/builtin/mcp/caller-wait.ts +50 -0
  32. package/dist/builtin/mcp/command-registration.ts +82 -0
  33. package/dist/builtin/mcp/direct-tool-executor.ts +279 -0
  34. package/dist/builtin/mcp/direct-tools.ts +40 -255
  35. package/dist/builtin/mcp/host-html-template.ts +4 -2
  36. package/dist/builtin/mcp/index.ts +274 -239
  37. package/dist/builtin/mcp/init.ts +96 -126
  38. package/dist/builtin/mcp/mcp-auth-flow.ts +247 -237
  39. package/dist/builtin/mcp/mcp-callback-server.ts +89 -68
  40. package/dist/builtin/mcp/mcp-oauth-provider.ts +23 -1
  41. package/dist/builtin/mcp/metadata-hydration.ts +52 -0
  42. package/dist/builtin/mcp/package.json +3 -3
  43. package/dist/builtin/mcp/proxy-auth.ts +4 -4
  44. package/dist/builtin/mcp/proxy-call.ts +111 -40
  45. package/dist/builtin/mcp/proxy-connect.ts +35 -15
  46. package/dist/builtin/mcp/proxy-info-modes.ts +106 -23
  47. package/dist/builtin/mcp/proxy-modes.ts +3 -3
  48. package/dist/builtin/mcp/session-cleanup-barrier.ts +43 -0
  49. package/dist/builtin/mcp/startup-warmup.ts +98 -0
  50. package/dist/builtin/mcp/state-lease.ts +12 -0
  51. package/dist/builtin/mcp/tool-result-renderer.ts +3 -3
  52. package/dist/builtin/mcp/ui-server.ts +8 -8
  53. package/dist/builtin/mcp/ui-session.ts +9 -18
  54. package/dist/builtin/subagents/CHANGELOG.md +78 -0
  55. package/dist/builtin/subagents/README.md +30 -29
  56. package/dist/builtin/subagents/agents/code-simplifier.md +2 -2
  57. package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -2
  58. package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
  59. package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -2
  60. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
  61. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -2
  62. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
  63. package/dist/builtin/subagents/agents/debugger.md +2 -2
  64. package/dist/builtin/subagents/agents/worker.md +2 -2
  65. package/dist/builtin/subagents/package.json +5 -5
  66. package/dist/builtin/subagents/prompts/review-loop.md +1 -1
  67. package/dist/builtin/subagents/skills/subagent/SKILL.md +37 -36
  68. package/dist/builtin/subagents/src/extension/api-lifecycle.ts +64 -0
  69. package/dist/builtin/subagents/src/extension/fanout-child.ts +44 -51
  70. package/dist/builtin/subagents/src/extension/index.ts +289 -320
  71. package/dist/builtin/subagents/src/extension/prompt-guidance.ts +7 -10
  72. package/dist/builtin/subagents/src/extension/schemas.ts +22 -5
  73. package/dist/builtin/subagents/src/extension/startup-maintenance.ts +89 -0
  74. package/dist/builtin/subagents/src/extension/tool-description.ts +29 -0
  75. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +13 -2
  76. package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
  77. package/dist/builtin/subagents/src/runs/background/async-event-journal.ts +106 -0
  78. package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +26 -20
  79. package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +13 -2
  80. package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +3 -0
  81. package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +1 -1
  82. package/dist/builtin/subagents/src/runs/background/completion-claims.ts +189 -0
  83. package/dist/builtin/subagents/src/runs/background/completion-dedupe.ts +44 -7
  84. package/dist/builtin/subagents/src/runs/background/completion-notification.ts +34 -0
  85. package/dist/builtin/subagents/src/runs/background/notify.ts +72 -22
  86. package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +232 -0
  87. package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +151 -0
  88. package/dist/builtin/subagents/src/runs/background/result-quarantine.ts +72 -0
  89. package/dist/builtin/subagents/src/runs/background/result-retry-scheduler.ts +48 -0
  90. package/dist/builtin/subagents/src/runs/background/result-status.ts +81 -0
  91. package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +59 -0
  92. package/dist/builtin/subagents/src/runs/background/result-watcher.ts +177 -233
  93. package/dist/builtin/subagents/src/runs/background/run-id-resolver.ts +3 -2
  94. package/dist/builtin/subagents/src/runs/background/stale-run-reconciler.ts +73 -14
  95. package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +29 -15
  96. package/dist/builtin/subagents/src/runs/background/top-level-async.ts +1 -2
  97. package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +1 -0
  98. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +1 -0
  99. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +1 -0
  100. package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +7 -9
  101. package/dist/builtin/subagents/src/runs/foreground/chain-execution-types.ts +3 -13
  102. package/dist/builtin/subagents/src/runs/foreground/chain-execution.ts +2 -15
  103. package/dist/builtin/subagents/src/runs/foreground/execution-attempt-finalize.ts +2 -2
  104. package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +63 -46
  105. package/dist/builtin/subagents/src/runs/foreground/execution-detach-reservations.ts +48 -0
  106. package/dist/builtin/subagents/src/runs/foreground/execution-detach-route.ts +17 -0
  107. package/dist/builtin/subagents/src/runs/foreground/execution-run-sync.ts +39 -26
  108. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +3 -1
  109. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-chain.ts +3 -51
  110. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +6 -11
  111. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +11 -2
  112. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +2 -0
  113. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +5 -112
  114. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +2 -0
  115. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +68 -118
  116. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +79 -7
  117. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +2 -2
  118. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +3 -0
  119. package/dist/builtin/subagents/src/runs/shared/pi-args.ts +2 -2
  120. package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +55 -12
  121. package/dist/builtin/subagents/src/shared/artifacts.ts +22 -11
  122. package/dist/builtin/subagents/src/shared/event-jsonl-writer.ts +294 -0
  123. package/dist/builtin/subagents/src/shared/exclusive-file-publication.ts +44 -0
  124. package/dist/builtin/subagents/src/shared/jsonl-writer.ts +1 -0
  125. package/dist/builtin/subagents/src/shared/model-info.ts +2 -2
  126. package/dist/builtin/subagents/src/shared/settings.ts +20 -10
  127. package/dist/builtin/subagents/src/shared/types-async.ts +3 -1
  128. package/dist/builtin/subagents/src/shared/types-config.ts +2 -0
  129. package/dist/builtin/subagents/src/shared/types-runtime.ts +3 -2
  130. package/dist/builtin/subagents/src/slash/slash-commands.ts +9 -12
  131. package/dist/builtin/subagents/src/slash/slash-live-state.ts +63 -32
  132. package/dist/builtin/subagents/src/tui/render-result.ts +7 -0
  133. package/dist/builtin/subagents/src/tui/render-stable-output.ts +1 -0
  134. package/dist/builtin/subagents/src/tui/render-widget.ts +157 -89
  135. package/dist/builtin/web-access/CHANGELOG.md +28 -0
  136. package/dist/builtin/web-access/README.md +4 -0
  137. package/dist/builtin/web-access/content-tools.ts +8 -3
  138. package/dist/builtin/web-access/index-heavy.ts +1 -1
  139. package/dist/builtin/web-access/index.ts +190 -46
  140. package/dist/builtin/web-access/lifecycle-lease.ts +38 -0
  141. package/dist/builtin/web-access/package.json +2 -2
  142. package/dist/builtin/web-access/result-renderers.ts +1 -1
  143. package/dist/builtin/web-access/summary-review.ts +1 -1
  144. package/dist/builtin/web-access/web-search-activity.ts +1 -1
  145. package/dist/builtin/web-access/web-search-return.ts +7 -0
  146. package/dist/builtin/web-access/web-search-summary.ts +1 -1
  147. package/dist/builtin/web-access/web-search-tool.ts +4 -2
  148. package/dist/builtin/workflows/CHANGELOG.md +86 -0
  149. package/dist/builtin/workflows/README.md +5 -5
  150. package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +27 -4
  151. package/dist/builtin/workflows/builtin/goal-runner.ts +86 -27
  152. package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +10 -0
  153. package/dist/builtin/workflows/builtin/ralph-core.ts +9 -9
  154. package/dist/builtin/workflows/builtin/ralph-models.ts +71 -36
  155. package/dist/builtin/workflows/builtin/ralph-runner.ts +20 -31
  156. package/dist/builtin/workflows/package.json +2 -2
  157. package/dist/builtin/workflows/skills/impeccable/SKILL.md +16 -13
  158. package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -0
  159. package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +58 -0
  160. package/dist/builtin/workflows/skills/impeccable/reference/android.md +40 -0
  161. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +2 -0
  162. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +2 -0
  163. package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +139 -0
  164. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +69 -62
  165. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +21 -7
  166. package/dist/builtin/workflows/skills/impeccable/reference/document.md +1 -1
  167. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +92 -0
  168. package/dist/builtin/workflows/skills/impeccable/reference/init.md +29 -7
  169. package/dist/builtin/workflows/skills/impeccable/reference/ios.md +45 -0
  170. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +25 -1
  171. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +23 -1
  172. package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +2 -1
  173. package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +75 -14
  174. package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +1 -1
  175. package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +31 -0
  176. package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +64 -0
  177. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +118 -11
  178. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +16 -11
  179. package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +66 -0
  180. package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +42 -10
  181. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +30 -0
  182. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +4 -6
  183. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +660 -0
  184. package/dist/builtin/workflows/skills/impeccable/scripts/hook-before-edit.mjs +516 -0
  185. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +1764 -0
  186. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +61 -0
  187. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +4 -2
  188. package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +2 -2
  189. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +13 -16
  190. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +17 -11
  191. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +104 -37
  192. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +9 -0
  193. package/dist/builtin/workflows/src/durable/backend.ts +12 -0
  194. package/dist/builtin/workflows/src/durable/dbos-backend.ts +17 -1
  195. package/dist/builtin/workflows/src/durable/resume-catalog.ts +12 -0
  196. package/dist/builtin/workflows/src/durable/resume-runtime.ts +5 -2
  197. package/dist/builtin/workflows/src/durable/stage-primitive.ts +2 -1
  198. package/dist/builtin/workflows/src/durable/types.ts +16 -0
  199. package/dist/builtin/workflows/src/engine/primitives/task.ts +3 -1
  200. package/dist/builtin/workflows/src/engine/run-durable-finalize.ts +1 -2
  201. package/dist/builtin/workflows/src/engine/run-returned-status.ts +50 -16
  202. package/dist/builtin/workflows/src/engine/run.ts +20 -19
  203. package/dist/builtin/workflows/src/engine/runtime.ts +5 -0
  204. package/dist/builtin/workflows/src/extension/extension-factory.ts +3 -0
  205. package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +9 -2
  206. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +137 -27
  207. package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +22 -6
  208. package/dist/builtin/workflows/src/extension/public-types.ts +1 -1
  209. package/dist/builtin/workflows/src/extension/workflow-command-completions.ts +13 -1
  210. package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +19 -4
  211. package/dist/builtin/workflows/src/extension/workflow-command-surfaces.ts +9 -0
  212. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +17 -22
  213. package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +48 -23
  214. package/dist/builtin/workflows/src/extension/workflow-schema.ts +15 -2
  215. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +20 -8
  216. package/dist/builtin/workflows/src/extension/workflow-tool.ts +24 -8
  217. package/dist/builtin/workflows/src/runs/background/status.ts +4 -3
  218. package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +29 -8
  219. package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +1 -1
  220. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +3 -2
  221. package/dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts +1 -1
  222. package/dist/builtin/workflows/src/runs/shared/worktree-git.ts +155 -20
  223. package/dist/builtin/workflows/src/runs/shared/worktree-types.ts +6 -0
  224. package/dist/builtin/workflows/src/runs/shared/worktree.ts +2 -1
  225. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -2
  226. package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +2 -2
  227. package/dist/builtin/workflows/src/shared/resume-continuation.ts +2 -0
  228. package/dist/builtin/workflows/src/shared/returned-run-status.ts +116 -0
  229. package/dist/builtin/workflows/src/shared/workflow-failures-decisions.ts +2 -0
  230. package/dist/builtin/workflows/src/tui/graph-view-render-helpers.ts +21 -3
  231. package/dist/builtin/workflows/src/tui/graph-view-state.ts +3 -0
  232. package/dist/builtin/workflows/src/tui/graph-view-types.ts +3 -0
  233. package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +1 -23
  234. package/dist/builtin/workflows/src/tui/stage-chat-view-footer-status.ts +54 -9
  235. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +5 -2
  236. package/dist/builtin/workflows/src/tui/status-list.ts +22 -15
  237. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +4 -4
  238. package/dist/cli/args.d.ts.map +1 -1
  239. package/dist/cli/args.js +2 -2
  240. package/dist/cli/args.js.map +1 -1
  241. package/dist/core/agent-session-auto-compaction.d.ts +23 -3
  242. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  243. package/dist/core/agent-session-auto-compaction.js +129 -17
  244. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  245. package/dist/core/agent-session-events.d.ts.map +1 -1
  246. package/dist/core/agent-session-events.js +9 -1
  247. package/dist/core/agent-session-events.js.map +1 -1
  248. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  249. package/dist/core/agent-session-message-queue.js +1 -1
  250. package/dist/core/agent-session-message-queue.js.map +1 -1
  251. package/dist/core/agent-session-methods.d.ts +6 -3
  252. package/dist/core/agent-session-methods.d.ts.map +1 -1
  253. package/dist/core/agent-session-methods.js.map +1 -1
  254. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  255. package/dist/core/agent-session-prompt.js +2 -2
  256. package/dist/core/agent-session-prompt.js.map +1 -1
  257. package/dist/core/agent-session-retry.d.ts.map +1 -1
  258. package/dist/core/agent-session-retry.js +1 -1
  259. package/dist/core/agent-session-retry.js.map +1 -1
  260. package/dist/core/agent-session-services.d.ts.map +1 -1
  261. package/dist/core/agent-session-services.js +3 -2
  262. package/dist/core/agent-session-services.js.map +1 -1
  263. package/dist/core/agent-session-types.d.ts.map +1 -1
  264. package/dist/core/agent-session-types.js +1 -1
  265. package/dist/core/agent-session-types.js.map +1 -1
  266. package/dist/core/agent-session.d.ts +4 -2
  267. package/dist/core/agent-session.d.ts.map +1 -1
  268. package/dist/core/agent-session.js +4 -2
  269. package/dist/core/agent-session.js.map +1 -1
  270. package/dist/core/anthropic-thinking-guard.d.ts +5 -5
  271. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  272. package/dist/core/anthropic-thinking-guard.js +42 -32
  273. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  274. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  275. package/dist/core/atomic-guide-command.js +15 -15
  276. package/dist/core/atomic-guide-command.js.map +1 -1
  277. package/dist/core/auth-storage.d.ts.map +1 -1
  278. package/dist/core/auth-storage.js +14 -9
  279. package/dist/core/auth-storage.js.map +1 -1
  280. package/dist/core/compaction/compaction.d.ts +2 -0
  281. package/dist/core/compaction/compaction.d.ts.map +1 -1
  282. package/dist/core/compaction/compaction.js +79 -46
  283. package/dist/core/compaction/compaction.js.map +1 -1
  284. package/dist/core/compaction/context-assistant-turns.d.ts +42 -0
  285. package/dist/core/compaction/context-assistant-turns.d.ts.map +1 -0
  286. package/dist/core/compaction/context-assistant-turns.js +87 -0
  287. package/dist/core/compaction/context-assistant-turns.js.map +1 -0
  288. package/dist/core/compaction/context-compaction-critical.d.ts +1 -1
  289. package/dist/core/compaction/context-compaction-critical.d.ts.map +1 -1
  290. package/dist/core/compaction/context-compaction-critical.js +2 -2
  291. package/dist/core/compaction/context-compaction-critical.js.map +1 -1
  292. package/dist/core/compaction/context-compaction-eviction-alternates.d.ts +18 -0
  293. package/dist/core/compaction/context-compaction-eviction-alternates.d.ts.map +1 -0
  294. package/dist/core/compaction/context-compaction-eviction-alternates.js +186 -0
  295. package/dist/core/compaction/context-compaction-eviction-alternates.js.map +1 -0
  296. package/dist/core/compaction/context-compaction-eviction.d.ts +10 -2
  297. package/dist/core/compaction/context-compaction-eviction.d.ts.map +1 -1
  298. package/dist/core/compaction/context-compaction-eviction.js +196 -146
  299. package/dist/core/compaction/context-compaction-eviction.js.map +1 -1
  300. package/dist/core/compaction/context-compaction-prompt.d.ts.map +1 -1
  301. package/dist/core/compaction/context-compaction-prompt.js +1 -1
  302. package/dist/core/compaction/context-compaction-prompt.js.map +1 -1
  303. package/dist/core/compaction/context-compaction-types.d.ts +2 -0
  304. package/dist/core/compaction/context-compaction-types.d.ts.map +1 -1
  305. package/dist/core/compaction/context-compaction-types.js.map +1 -1
  306. package/dist/core/compaction/context-deletion-application.d.ts +5 -4
  307. package/dist/core/compaction/context-deletion-application.d.ts.map +1 -1
  308. package/dist/core/compaction/context-deletion-application.js +17 -15
  309. package/dist/core/compaction/context-deletion-application.js.map +1 -1
  310. package/dist/core/compaction/context-deletion-store.d.ts.map +1 -1
  311. package/dist/core/compaction/context-deletion-store.js +1 -1
  312. package/dist/core/compaction/context-deletion-store.js.map +1 -1
  313. package/dist/core/compaction/context-deletion-targets.d.ts +2 -1
  314. package/dist/core/compaction/context-deletion-targets.d.ts.map +1 -1
  315. package/dist/core/compaction/context-deletion-targets.js +36 -31
  316. package/dist/core/compaction/context-deletion-targets.js.map +1 -1
  317. package/dist/core/compaction/context-deletion-tool-helpers.d.ts.map +1 -1
  318. package/dist/core/compaction/context-deletion-tool-helpers.js +116 -43
  319. package/dist/core/compaction/context-deletion-tool-helpers.js.map +1 -1
  320. package/dist/core/compaction/context-transcript-analysis.d.ts +1 -2
  321. package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
  322. package/dist/core/compaction/context-transcript-analysis.js +33 -37
  323. package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
  324. package/dist/core/copilot-model-synthesis.d.ts.map +1 -1
  325. package/dist/core/copilot-model-synthesis.js +3 -1
  326. package/dist/core/copilot-model-synthesis.js.map +1 -1
  327. package/dist/core/extensions/loader-virtual-modules.d.ts +8 -1
  328. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  329. package/dist/core/extensions/loader-virtual-modules.js +2 -1
  330. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  331. package/dist/core/extensions/provider-types.d.ts +2 -7
  332. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  333. package/dist/core/extensions/provider-types.js.map +1 -1
  334. package/dist/core/footer-data-provider.d.ts +6 -0
  335. package/dist/core/footer-data-provider.d.ts.map +1 -1
  336. package/dist/core/footer-data-provider.js +72 -29
  337. package/dist/core/footer-data-provider.js.map +1 -1
  338. package/dist/core/messages.d.ts +9 -0
  339. package/dist/core/messages.d.ts.map +1 -1
  340. package/dist/core/messages.js +100 -18
  341. package/dist/core/messages.js.map +1 -1
  342. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  343. package/dist/core/model-registry-builtins.js +5 -0
  344. package/dist/core/model-registry-builtins.js.map +1 -1
  345. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  346. package/dist/core/model-registry-custom-loader.js +49 -8
  347. package/dist/core/model-registry-custom-loader.js.map +1 -1
  348. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  349. package/dist/core/model-registry-dynamic.js +11 -5
  350. package/dist/core/model-registry-dynamic.js.map +1 -1
  351. package/dist/core/model-registry-loader.d.ts.map +1 -1
  352. package/dist/core/model-registry-loader.js +8 -0
  353. package/dist/core/model-registry-loader.js.map +1 -1
  354. package/dist/core/model-registry-schemas.d.ts +93 -8
  355. package/dist/core/model-registry-schemas.d.ts.map +1 -1
  356. package/dist/core/model-registry-schemas.js +24 -12
  357. package/dist/core/model-registry-schemas.js.map +1 -1
  358. package/dist/core/model-registry-types.d.ts +7 -6
  359. package/dist/core/model-registry-types.d.ts.map +1 -1
  360. package/dist/core/model-registry-types.js.map +1 -1
  361. package/dist/core/model-registry.d.ts +5 -0
  362. package/dist/core/model-registry.d.ts.map +1 -1
  363. package/dist/core/model-registry.js +23 -0
  364. package/dist/core/model-registry.js.map +1 -1
  365. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  366. package/dist/core/model-resolver-cli.js +33 -5
  367. package/dist/core/model-resolver-cli.js.map +1 -1
  368. package/dist/core/model-resolver-initial.d.ts +6 -1
  369. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  370. package/dist/core/model-resolver-initial.js +12 -7
  371. package/dist/core/model-resolver-initial.js.map +1 -1
  372. package/dist/core/model-resolver.d.ts +1 -1
  373. package/dist/core/model-resolver.d.ts.map +1 -1
  374. package/dist/core/model-resolver.js +1 -1
  375. package/dist/core/model-resolver.js.map +1 -1
  376. package/dist/core/openai-responses-payload-sanitizer.d.ts +1 -0
  377. package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
  378. package/dist/core/openai-responses-payload-sanitizer.js +24 -9
  379. package/dist/core/openai-responses-payload-sanitizer.js.map +1 -1
  380. package/dist/core/resource-loader-context-files.d.ts +1 -0
  381. package/dist/core/resource-loader-context-files.d.ts.map +1 -1
  382. package/dist/core/resource-loader-context-files.js +13 -10
  383. package/dist/core/resource-loader-context-files.js.map +1 -1
  384. package/dist/core/sdk.d.ts.map +1 -1
  385. package/dist/core/sdk.js +2 -2
  386. package/dist/core/sdk.js.map +1 -1
  387. package/dist/core/session-entry-normalization.d.ts +7 -0
  388. package/dist/core/session-entry-normalization.d.ts.map +1 -0
  389. package/dist/core/session-entry-normalization.js +14 -0
  390. package/dist/core/session-entry-normalization.js.map +1 -0
  391. package/dist/core/session-manager-core.d.ts.map +1 -1
  392. package/dist/core/session-manager-core.js +1 -0
  393. package/dist/core/session-manager-core.js.map +1 -1
  394. package/dist/core/session-manager-history.d.ts +2 -2
  395. package/dist/core/session-manager-history.d.ts.map +1 -1
  396. package/dist/core/session-manager-history.js +127 -108
  397. package/dist/core/session-manager-history.js.map +1 -1
  398. package/dist/core/settings-manager-basic-accessors.d.ts +2 -2
  399. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  400. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  401. package/dist/core/settings-types.d.ts +1 -1
  402. package/dist/core/settings-types.d.ts.map +1 -1
  403. package/dist/core/settings-types.js.map +1 -1
  404. package/dist/core/slash-commands.d.ts +2 -0
  405. package/dist/core/slash-commands.d.ts.map +1 -1
  406. package/dist/core/slash-commands.js +141 -0
  407. package/dist/core/slash-commands.js.map +1 -1
  408. package/dist/core/tools/bash.d.ts.map +1 -1
  409. package/dist/core/tools/bash.js +11 -8
  410. package/dist/core/tools/bash.js.map +1 -1
  411. package/dist/index.d.ts +1 -0
  412. package/dist/index.d.ts.map +1 -1
  413. package/dist/index.js +1 -0
  414. package/dist/index.js.map +1 -1
  415. package/dist/main-deferred-startup.d.ts.map +1 -1
  416. package/dist/main-deferred-startup.js +2 -2
  417. package/dist/main-deferred-startup.js.map +1 -1
  418. package/dist/main-early-input.d.ts.map +1 -1
  419. package/dist/main-early-input.js +7 -0
  420. package/dist/main-early-input.js.map +1 -1
  421. package/dist/main-session.d.ts.map +1 -1
  422. package/dist/main-session.js +1 -0
  423. package/dist/main-session.js.map +1 -1
  424. package/dist/main.d.ts.map +1 -1
  425. package/dist/main.js +1 -1
  426. package/dist/main.js.map +1 -1
  427. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  428. package/dist/modes/interactive/components/chat-session-host-actions.js +0 -1
  429. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  430. package/dist/modes/interactive/components/settings-selector-options.d.ts.map +1 -1
  431. package/dist/modes/interactive/components/settings-selector-options.js +3 -1
  432. package/dist/modes/interactive/components/settings-selector-options.js.map +1 -1
  433. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  434. package/dist/modes/interactive/components/thinking-selector.js +2 -1
  435. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  436. package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
  437. package/dist/modes/interactive/interactive-agent-events.js +3 -1
  438. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  439. package/dist/modes/interactive/interactive-autocomplete.d.ts.map +1 -1
  440. package/dist/modes/interactive/interactive-autocomplete.js +21 -9
  441. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  442. package/dist/modes/interactive/interactive-child-ordering.d.ts +7 -0
  443. package/dist/modes/interactive/interactive-child-ordering.d.ts.map +1 -0
  444. package/dist/modes/interactive/interactive-child-ordering.js +26 -0
  445. package/dist/modes/interactive/interactive-child-ordering.js.map +1 -0
  446. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  447. package/dist/modes/interactive/interactive-deferred-startup.js +43 -30
  448. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  449. package/dist/modes/interactive/interactive-hotkeys-debug.d.ts.map +1 -1
  450. package/dist/modes/interactive/interactive-hotkeys-debug.js +1 -0
  451. package/dist/modes/interactive/interactive-hotkeys-debug.js.map +1 -1
  452. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  453. package/dist/modes/interactive/interactive-input-handling.js +41 -6
  454. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  455. package/dist/modes/interactive/interactive-mode-base.d.ts +3 -0
  456. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  457. package/dist/modes/interactive/interactive-mode-base.js +3 -0
  458. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  459. package/dist/modes/interactive/interactive-mode-deps.d.ts +2 -2
  460. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  461. package/dist/modes/interactive/interactive-mode-deps.js +2 -2
  462. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  463. package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -2
  464. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  465. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  466. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  467. package/dist/modes/interactive/interactive-model-routing.js +11 -4
  468. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  469. package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
  470. package/dist/modes/interactive/interactive-process-lifecycle.js +0 -3
  471. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  472. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  473. package/dist/modes/interactive/interactive-render-chat.js +15 -1
  474. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  475. package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
  476. package/dist/modes/interactive/interactive-session-routing.js +5 -1
  477. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  478. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  479. package/dist/modes/interactive/interactive-startup.js +20 -21
  480. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  481. package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
  482. package/dist/modes/interactive/theme/global-theme.js +26 -2
  483. package/dist/modes/interactive/theme/global-theme.js.map +1 -1
  484. package/dist/modes/interactive/theme/theme-class.d.ts +1 -1
  485. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  486. package/dist/modes/interactive/theme/theme-class.js +2 -0
  487. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  488. package/dist/utils/clipboard-image.d.ts.map +1 -1
  489. package/dist/utils/clipboard-image.js +3 -0
  490. package/dist/utils/clipboard-image.js.map +1 -1
  491. package/dist/utils/fs-watch.d.ts +24 -1
  492. package/dist/utils/fs-watch.d.ts.map +1 -1
  493. package/dist/utils/fs-watch.js +60 -5
  494. package/dist/utils/fs-watch.js.map +1 -1
  495. package/docs/changelog.mdx +19 -0
  496. package/docs/compaction.md +60 -49
  497. package/docs/custom-provider.md +18 -5
  498. package/docs/development.md +4 -0
  499. package/docs/extensions.md +11 -2
  500. package/docs/json.md +1 -1
  501. package/docs/models.md +69 -10
  502. package/docs/providers.md +1 -1
  503. package/docs/quickstart.md +12 -8
  504. package/docs/rpc.md +2 -2
  505. package/docs/sdk.md +1 -1
  506. package/docs/settings.md +4 -4
  507. package/docs/subagents.md +40 -5
  508. package/docs/tools.md +1 -1
  509. package/docs/usage.md +4 -2
  510. package/docs/windows.md +4 -0
  511. package/docs/workflows.md +33 -48
  512. package/examples/extensions/preset.ts +2 -2
  513. package/examples/extensions/subagent/README.md +2 -2
  514. package/examples/extensions/subagent/index.ts +1 -2
  515. package/examples/extensions/subagent/schemas.ts +4 -1
  516. package/examples/sdk/12-full-control.ts +1 -1
  517. package/npm-shrinkwrap.json +48 -51
  518. package/package.json +7 -7
  519. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-behavior.ts +0 -75
  520. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-component.ts +0 -202
  521. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-edit.ts +0 -97
  522. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-editor.ts +0 -160
  523. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-frame.ts +0 -72
  524. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-modes.ts +0 -161
  525. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-selectors.ts +0 -203
  526. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-selectors.ts +0 -234
  527. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-state.ts +0 -103
  528. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-types.ts +0 -29
  529. package/dist/builtin/subagents/src/runs/foreground/chain-clarify.ts +0 -9
  530. package/dist/builtin/subagents/src/runs/foreground/chain-execution-clarify.ts +0 -117
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,KAAK,GAGN,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kB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BAAoB;KACnD,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACL,OAAO;QACP,gBAAgB;QAChB,oBAAoB;QACpB,oBAAoB;QACpB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveSavedModelReference } from \"./model-resolver.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { time } from \"./timings.ts\";\nimport { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\ntype ContextWindowRequestSource = \"explicit\" | \"incoming-model\" | \"session\" | \"model-settings\" | \"global-settings\";\n\nconst COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = { allowCopilotLongContextFallback: true } as const;\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveSavedModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const sessionContextWindow = hasExistingSession ? existingSession.contextWindow : undefined;\n const modelSettingsContextWindow = model ? settingsManager.getDefaultContextWindowForModel(model.provider, model.id) : undefined;\n const globalSettingsContextWindow = settingsManager.getDefaultContextWindow();\n const contextWindowRequest:\n | { contextWindow: number; source: ContextWindowRequestSource }\n | undefined =\n options.contextWindow !== undefined\n ? { contextWindow: options.contextWindow, source: \"explicit\" }\n : incomingModelContextWindow !== undefined\n ? { contextWindow: incomingModelContextWindow, source: \"incoming-model\" }\n : sessionContextWindow !== undefined\n ? { contextWindow: sessionContextWindow, source: \"session\" }\n : modelSettingsContextWindow !== undefined\n ? { contextWindow: modelSettingsContextWindow, source: \"model-settings\" }\n : globalSettingsContextWindow !== undefined\n ? { contextWindow: globalSettingsContextWindow, source: \"global-settings\" }\n : undefined;\n if (model && contextWindowRequest !== undefined) {\n const selected = selectContextWindow(\n model,\n contextWindowRequest.contextWindow,\n COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS,\n );\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else if (contextWindowRequest.source !== \"global-settings\") {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n const reasoningRestored = restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\n return sanitizeOpenAIResponsesPayload(reasoningRestored, model);\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n const transformed = runner ? await runner.emitContext(messages) : messages;\n return scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n fallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n resourceLoader,\n customTools: options.customTools,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowWarning,\n contextWindowError,\n };\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,KAAK,GAGN,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kBAAkB,EAIlB,YAAY,GACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AACpF,OAAO,EAAE,yCAAyC,EAAE,MAAM,oCAAoC,CAAC;AAC/F,OAAO,EAAE,4BAA4B,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACpH,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE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,CAAC;QAC/B,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;QAC7E,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB,EAAE,OAAO,CAAC,aAAa;QACxC,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;KACnD,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACL,OAAO;QACP,gBAAgB;QAChB,oBAAoB;QACpB,oBAAoB;QACpB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n shouldApplyCodexFastMode,\n streamWithCodexFastMode,\n withCodexFastModePayload,\n withCodexFastModeStreamOptions,\n} from \"./codex-fast-mode.ts\";\nimport { restoreAnthropicReplayThinkingBlocks } from \"./anthropic-thinking-guard.ts\";\nimport { sanitizeCopilotGeminiPayload } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { restoreCopilotGeminiReasoningOpaque } from \"./copilot-gemini-reasoning.ts\";\nimport { normalizeCopilotGeminiReplayToolArguments } from \"./copilot-gemini-tool-arguments.ts\";\nimport { getModelDefaultContextWindow, getSupportedContextWindows, selectContextWindow } from \"./context-window.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveRestoredModelReference } from \"./model-resolver.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { sanitizeOpenAIResponsesPayload } from \"./openai-responses-payload-sanitizer.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\nimport { time } from \"./timings.ts\";\nimport { defaultToolNames } from \"./tools/index.ts\";\n\nimport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\nexport type { CreateAgentSessionOptions, CreateAgentSessionResult } from \"./sdk-types.ts\";\n\nexport * from \"./sdk-exports.ts\";\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\ntype ContextWindowRequestSource = \"explicit\" | \"incoming-model\" | \"session\" | \"model-settings\" | \"global-settings\";\n\nconst COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = { allowCopilotLongContextFallback: true } as const;\n\nfunction getAlreadyAppliedContextWindow(model: Model<Api>): number | undefined {\n const defaultContextWindow = getModelDefaultContextWindow(model);\n if (model.contextWindow === defaultContextWindow) {\n return undefined;\n }\n\n return getSupportedContextWindows(model).includes(model.contextWindow)\n ? model.contextWindow\n : undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai/compat';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry. When a modelRegistry\n // is supplied (e.g. a workflow stage reusing one registry across model\n // fallback candidates), do NOT also build a fresh AuthStorage: its\n // constructor eagerly calls reload(), which acquires the auth.json file lock\n // and, under contention, can fail and leave an empty credential set. Reusing\n // the supplied registry's already-loaded auth avoids that race (issue #1431).\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const modelRegistry =\n options.modelRegistry ??\n ModelRegistry.create(options.authStorage ?? AuthStorage.create(authPath), modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n // Mark workflow-created sessions as internal so they are excluded from the\n // standard `/resume` history while remaining resumable via `/workflow resume`.\n // Only stamped when the orchestration context identifies a workflow stage;\n // reattaching to an already-marked session preserves its existing marker.\n if (options.orchestrationContext?.kind === \"workflow-stage\") {\n const ctx = options.orchestrationContext;\n sessionManager.markSessionInternal({\n runId: ctx.workflowRunId,\n stageId: ctx.workflowStageId,\n stageName: ctx.workflowStageName,\n });\n }\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = await resolveRestoredModelReference(\n existingSession.model.provider,\n existingSession.model.modelId,\n modelRegistry,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n let selectedContextWindow: number | undefined;\n let contextWindowWarning: string | undefined;\n let contextWindowError: string | undefined;\n const explicitContextWindowSelection = options.contextWindow !== undefined;\n const incomingModelContextWindow =\n model && options.model ? getAlreadyAppliedContextWindow(model) : undefined;\n const sessionContextWindow = hasExistingSession ? existingSession.contextWindow : undefined;\n const modelSettingsContextWindow = model ? settingsManager.getDefaultContextWindowForModel(model.provider, model.id) : undefined;\n const globalSettingsContextWindow = settingsManager.getDefaultContextWindow();\n const contextWindowRequest:\n | { contextWindow: number; source: ContextWindowRequestSource }\n | undefined =\n options.contextWindow !== undefined\n ? { contextWindow: options.contextWindow, source: \"explicit\" }\n : incomingModelContextWindow !== undefined\n ? { contextWindow: incomingModelContextWindow, source: \"incoming-model\" }\n : sessionContextWindow !== undefined\n ? { contextWindow: sessionContextWindow, source: \"session\" }\n : modelSettingsContextWindow !== undefined\n ? { contextWindow: modelSettingsContextWindow, source: \"model-settings\" }\n : globalSettingsContextWindow !== undefined\n ? { contextWindow: globalSettingsContextWindow, source: \"global-settings\" }\n : undefined;\n if (model && contextWindowRequest !== undefined) {\n const selected = selectContextWindow(\n model,\n contextWindowRequest.contextWindow,\n COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS,\n );\n if (\"error\" in selected) {\n if (options.contextWindowStrict) {\n contextWindowError = selected.error;\n } else if (contextWindowRequest.source !== \"global-settings\") {\n contextWindowWarning = selected.error;\n }\n } else {\n model = selected.model;\n selectedContextWindow = selected.contextWindow;\n }\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n let lastConvertedLlmMessages: Message[] | undefined;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n lastConvertedLlmMessages = converted;\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n const filtered = converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n lastConvertedLlmMessages = filtered;\n return filtered;\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const isCodexFastModeEnabled = (requestModel: Model<Api>): boolean =>\n shouldApplyCodexFastMode(\n requestModel,\n settingsManager.getCodexFastModeSettings(),\n options.orchestrationContext,\n );\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, streamOptions) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n // SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n // Use max int32 to effectively disable the timeout.\n const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n const timeoutMs = streamOptions?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n const websocketConnectTimeoutMs =\n streamOptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const attributionHeaders = mergeProviderAttributionHeaders(\n model,\n settingsManager,\n streamOptions?.sessionId,\n auth.headers,\n streamOptions?.headers,\n );\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const codexFastModeStreamOptions = withCodexFastModeStreamOptions(\n {\n ...streamOptions,\n apiKey: auth.apiKey,\n timeoutMs,\n websocketConnectTimeoutMs,\n maxRetries: streamOptions?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n streamOptions?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers: attributionHeaders,\n },\n fastModeEnabled,\n );\n if (modelRegistry.hasRegisteredStreamSimpleForApi(model.api)) {\n return streamSimple(model, context, codexFastModeStreamOptions);\n }\n return streamWithCodexFastMode(model, context, codexFastModeStreamOptions);\n },\n onPayload: async (payload, model) => {\n const fastModeEnabled = isCodexFastModeEnabled(model);\n const guardedPayload = withCodexFastModePayload(payload, fastModeEnabled);\n const sourceMessages = lastConvertedLlmMessages;\n const replayGuardedPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(guardedPayload, sourceMessages, model)\n : guardedPayload;\n const runner = extensionRunnerRef.current;\n let finalPayload: unknown;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n finalPayload = replayGuardedPayload;\n } else {\n const extensionPayload = await runner.emitBeforeProviderRequest(\n replayGuardedPayload,\n );\n finalPayload = sourceMessages\n ? restoreAnthropicReplayThinkingBlocks(extensionPayload, sourceMessages, model)\n : extensionPayload;\n }\n // GitHub Copilot Gemini models are served through CAPI, which translates\n // the OpenAI request into Google GenAI and rejects tool schemas whose\n // `anyOf`/`oneOf` wraps a complex object (HTTP 400 invalid request body).\n // Sanitize tool JSON Schemas into Gemini's supported subset. No-op for\n // every other provider/model, and runs last so it also covers tools\n // injected by `before_provider_request` extensions.\n const schemaSanitized = sanitizeCopilotGeminiPayload(finalPayload, model);\n // Reconstruct flattened tool-call arguments on replayed assistant\n // messages (for example `edits[0].newText` -> `edits: [{ newText }]`).\n // CAPI parses replayed arguments straight into Gemini's FunctionCall,\n // and a flattened/malformed prior call ends the next turn with\n // `finish_reason: \"error\"`. No-op for well-formed args / other models.\n const replayArgsNormalized = normalizeCopilotGeminiReplayToolArguments(schemaSanitized, model);\n // CAPI carries Gemini thought signatures in a `reasoning_opaque` field it\n // reads back off the assistant message on replay. Convert the\n // `reasoning_details` the client re-emits (captured inbound by the SSE\n // interceptor) into that field so multi-turn tool use keeps its thought\n // signature instead of dying on an empty completion. No-op otherwise.\n const reasoningRestored = restoreCopilotGeminiReasoningOpaque(replayArgsNormalized, model);\n return sanitizeOpenAIResponsesPayload(reasoningRestored, model);\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n const transformed = runner ? await runner.emitContext(messages) : messages;\n return scrubPreCompactionAssistantUsage(transformed, sessionManager.getBranch());\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n const transcriptContextWindow = model\n ? (existingSession.contextWindow ?? getModelDefaultContextWindow(model))\n : undefined;\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== transcriptContextWindow)\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n if (\n selectedContextWindow !== undefined &&\n (explicitContextWindowSelection || selectedContextWindow !== getModelDefaultContextWindow(model))\n ) {\n sessionManager.appendContextWindowChange(selectedContextWindow);\n }\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n fallbackModels: options.fallbackModels ?? settingsManager.getFallbackModels(),\n resourceLoader,\n customTools: options.customTools,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludedTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n orchestrationContext: options.orchestrationContext,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n contextWindowWarning,\n contextWindowError,\n };\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { SessionEntry } from "./session-manager-types.ts";
2
+ /**
3
+ * Build a safe derived path for replay/analysis without rewriting durable
4
+ * session entries. Only lax message entries whose content is null are cloned.
5
+ */
6
+ export declare function normalizeDerivedSessionEntries(entries: readonly SessionEntry[]): SessionEntry[];
7
+ //# sourceMappingURL=session-entry-normalization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-entry-normalization.d.ts","sourceRoot":"","sources":["../../src/core/session-entry-normalization.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D;;;GAGG;AACH,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,YAAY,EAAE,CAM/F","sourcesContent":["import { normalizeMessageContent } from \"./messages.ts\";\nimport type { SessionEntry } from \"./session-manager-types.ts\";\n\n/**\n * Build a safe derived path for replay/analysis without rewriting durable\n * session entries. Only lax message entries whose content is null are cloned.\n */\nexport function normalizeDerivedSessionEntries(entries: readonly SessionEntry[]): SessionEntry[] {\n\treturn entries.map((entry) => {\n\t\tif (entry.type !== \"message\") return entry;\n\t\tconst message = normalizeMessageContent(entry.message);\n\t\treturn message === entry.message ? entry : { ...entry, message };\n\t});\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { normalizeMessageContent } from "./messages.js";
2
+ /**
3
+ * Build a safe derived path for replay/analysis without rewriting durable
4
+ * session entries. Only lax message entries whose content is null are cloned.
5
+ */
6
+ export function normalizeDerivedSessionEntries(entries) {
7
+ return entries.map((entry) => {
8
+ if (entry.type !== "message")
9
+ return entry;
10
+ const message = normalizeMessageContent(entry.message);
11
+ return message === entry.message ? entry : { ...entry, message };
12
+ });
13
+ }
14
+ //# sourceMappingURL=session-entry-normalization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-entry-normalization.js","sourceRoot":"","sources":["../../src/core/session-entry-normalization.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAGxD;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAAC,OAAgC;IAC9E,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAC5B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QAC3C,MAAM,OAAO,GAAG,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACvD,OAAO,OAAO,KAAK,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,CAAC;IAClE,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { normalizeMessageContent } from \"./messages.ts\";\nimport type { SessionEntry } from \"./session-manager-types.ts\";\n\n/**\n * Build a safe derived path for replay/analysis without rewriting durable\n * session entries. Only lax message entries whose content is null are cloned.\n */\nexport function normalizeDerivedSessionEntries(entries: readonly SessionEntry[]): SessionEntry[] {\n\treturn entries.map((entry) => {\n\t\tif (entry.type !== \"message\") return entry;\n\t\tconst message = normalizeMessageContent(entry.message);\n\t\treturn message === entry.message ? entry : { ...entry, message };\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-core.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIvF,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAmCzE,OAAO,KAAK,EAEX,sBAAsB,EACtB,qBAAqB,EAErB,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,MAAM,4BAA4B,CAAC;AAGpC,qfAAqf;AACrf,qBAAa,cAAc;IAC1B,OAAO,CAAC,SAAS,CAAc;IAC/B,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,OAAO,CAAU;IACzB,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,IAAI,CAAwC;IACpD,OAAO,CAAC,UAAU,CAAkC;IACpD,OAAO,CAAC,mBAAmB,CAAkC;IAC7D,OAAO,CAAC,MAAM,CAAuB;IAErC,OAAO,eAmBN;IAED,yEAAyE;IACzE,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAgCxC;IAED,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAwB1D;IAED,gHAAgH;IAChH,mBAAmB,CAAC,QAAQ,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAM5D;IAED,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,YAAY;IAKpB,WAAW,IAAI,OAAO,CAErB;IA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pi-ai/compat\";\nimport { existsSync, statSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport {\n\tcreateBackupSnapshot,\n\tcreateBranchedSessionState,\n\tforkSessionFromFile,\n} from \"./session-manager-archive.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateContextCompactionEntry,\n\tcreateContextWindowChangeEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tgetEntriesWithoutHeader,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateThinkingLevelChangeEntry,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { buildSessionContext, buildSessionIndex, buildSessionTree, getBranchPath } from \"./session-manager-history.ts\";\nimport { listAllSessions, listProjectSessions } from \"./session-manager-list.ts\";\nimport { migrateToCurrentVersion } from \"./session-manager-migrations.ts\";\nimport { getDefaultSessionDir, getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport {\n\tappendSessionEntries,\n\tappendSessionEntry,\n\tensureDirectory,\n\tfindMostRecentSession,\n\thasAssistantMessage,\n\tloadEntriesFromFile,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextCompactionStats,\n\tContextDeletionTarget,\n\tFileEntry,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId } from \"./session-manager-validation.ts\";\n\n/** Manages conversation sessions as append-only trees stored in JSONL files. Each session entry has an id and parentId forming a tree structure. The \"leaf\" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history. Use buildSessionContext() to get the resolved message list for the LLM, which applies context-deletion filtering and follows the path from root to current leaf. */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir) {\n\t\t\tensureDirectory(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis.setSessionFile(sessionFile);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header = createSessionHeader(\n\t\t\tthis.sessionId,\n\t\t\tthis.cwd,\n\t\t\ttimestamp,\n\t\t\toptions?.parentSession,\n\t\t\toptions?.internal,\n\t\t\toptions?.workflow,\n\t\t);\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tthis.sessionFile = createSessionFilePath(this.getSessionDir(), timestamp, this.sessionId);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\t/** Mark the session header as internal (e.g. workflow stage). Preserves an existing full marker on reattach. */\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): void {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tif (!header || (header.internal && header.workflow)) return;\n\t\theader.internal = true;\n\t\tif (workflow) header.workflow = workflow;\n\t\tif (this.flushed) this._rewriteFile();\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\twriteSessionEntries(this.sessionFile, this.fileEntries);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tif (!hasAssistantMessage(this.fileEntries)) {\n\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\tthis.flushed = false;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tappendSessionEntries(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendSessionEntry(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a context window change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendContextWindowChange(contextWindow: number): string {\n\t\tconst entry = createContextWindowChangeEntry(contextWindow, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append logical deletion metadata for deletion-only context compaction. */\n\tappendContextCompaction(\n\t\tdeletedTargets: ContextDeletionTarget[],\n\t\tprotectedEntryIds: string[],\n\t\tstats: ContextCompactionStats,\n\t\tbackupPath?: string,\n\t): string {\n\t\tconst entry = createContextCompactionEntry(deletedTargets, protectedEntryIds, stats, backupPath, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Write a recoverable snapshot of the current session entries without mutating the active JSONL. */\n\twriteBackupSnapshot(label = \"compact\"): string | undefined {\n\t\tif (!this.persist) return undefined;\n\t\treturn createBackupSnapshot(this.sessionFile, this.fileEntries, label);\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn getLatestSessionName(this.getEntries());\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t): string {\n\t\tconst entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(branchFromId, summary, details, fromHook, this.byId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Create a new session file containing only the path from root to the specified leaf. */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst result = createBranchedSessionState({\n\t\t\tleafId,\n\t\t\tpersist: this.persist,\n\t\t\tsessionDir: this.getSessionDir(),\n\t\t\tcwd: this.cwd,\n\t\t\tpreviousSessionFile: this.sessionFile,\n\t\t\tpath: this.getBranch(leafId),\n\t\t\tlabelsById: this.labelsById,\n\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t});\n\t\tthis.fileEntries = result.fileEntries;\n\t\tthis.sessionId = result.sessionId;\n\t\tif (result.sessionFile) this.sessionFile = result.sessionFile;\n\t\tthis._buildIndex();\n\n\t\tif (this.persist) {\n\t\t\tif (result.shouldRewriteFile) this._rewriteFile();\n\t\t\tthis.flushed = result.flushed ?? false;\n\t\t\treturn result.sessionFile;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Create a new session. */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/** Open a specific session file. */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tconst entries = loadEntriesFromFile(resolvedPath);\n\t\tconst header = entries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tconst cwd = cwdOverride ?? header?.cwd ?? process.cwd();\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true);\n\t}\n\n\t/** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(\n\t\t\tdir,\n\t\t\tfilterCwd ? cwd : undefined,\n\t\t\toptions?.includeInternal === true,\n\t\t);\n\t\treturn new SessionManager(cwd, dir, mostRecent ?? undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/** Fork a session from another project directory into the current project. */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);\n\t\treturn new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);\n\t}\n\n\t/** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listProjectSessions(cwd, sessionDir, onProgress, options?.includeInternal === true);\n\t}\n\n\t/** List sessions across all directories. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listAllSessions(sessionDirOrOnProgress, onProgress, options?.includeInternal === true);\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-manager-core.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIvF,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAmCzE,OAAO,KAAK,EAEX,sBAAsB,EACtB,qBAAqB,EAErB,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,MAAM,4BAA4B,CAAC;AAGpC,qf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d,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,iBAAiB,GACzB,cAAc,CAGhB;IAED,+GAA+G;IAC/G,OAAa,IAAI,CAChB,GAAG,EAAE,MAAM,EACX,UAAU,CAAC,EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,mBAAmB,EAChC,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GACrC,OAAO,CAAC,WAAW,EAAE,CAAC,CAExB;IAED,sHAAsH;IACtH,OAAa,OAAO,CAAC,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAC/E,OAAa,OAAO,CACnB,UAAU,CAAC,EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,mBAAmB,EAChC,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GACrC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAQ1B","sourcesContent":["import type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { existsSync, statSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport {\n\tcreateBackupSnapshot,\n\tcreateBranchedSessionState,\n\tforkSessionFromFile,\n} from \"./session-manager-archive.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateContextCompactionEntry,\n\tcreateContextWindowChangeEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tgetEntriesWithoutHeader,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateThinkingLevelChangeEntry,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { buildSessionContext, buildSessionIndex, buildSessionTree, getBranchPath } from \"./session-manager-history.ts\";\nimport { listAllSessions, listProjectSessions } from \"./session-manager-list.ts\";\nimport { migrateToCurrentVersion } from \"./session-manager-migrations.ts\";\nimport { getDefaultSessionDir, getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport {\n\tappendSessionEntries,\n\tappendSessionEntry,\n\tensureDirectory,\n\tfindMostRecentSession,\n\thasAssistantMessage,\n\tloadEntriesFromFile,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextCompactionStats,\n\tContextDeletionTarget,\n\tFileEntry,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId } from \"./session-manager-validation.ts\";\n\n/** Manages conversation sessions as append-only trees stored in JSONL files. Each session entry has an id and parentId forming a tree structure. The \"leaf\" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history. Use buildSessionContext() to get the resolved message list for the LLM, which applies context-deletion filtering and follows the path from root to current leaf. */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir) {\n\t\t\tensureDirectory(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis.setSessionFile(sessionFile);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header = createSessionHeader(\n\t\t\tthis.sessionId,\n\t\t\tthis.cwd,\n\t\t\ttimestamp,\n\t\t\toptions?.parentSession,\n\t\t\toptions?.internal,\n\t\t\toptions?.workflow,\n\t\t);\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tthis.sessionFile = createSessionFilePath(this.getSessionDir(), timestamp, this.sessionId);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\t/** Mark the session header as internal (e.g. workflow stage). Preserves an existing full marker on reattach. */\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): void {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tif (!header || (header.internal && header.workflow)) return;\n\t\theader.internal = true;\n\t\tif (workflow) header.workflow = workflow;\n\t\tif (this.flushed) this._rewriteFile();\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\twriteSessionEntries(this.sessionFile, this.fileEntries);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tif (!hasAssistantMessage(this.fileEntries)) {\n\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\tthis.flushed = false;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tappendSessionEntries(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendSessionEntry(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a context window change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendContextWindowChange(contextWindow: number): string {\n\t\tconst entry = createContextWindowChangeEntry(contextWindow, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append logical deletion metadata for deletion-only context compaction. */\n\tappendContextCompaction(\n\t\tdeletedTargets: ContextDeletionTarget[],\n\t\tprotectedEntryIds: string[],\n\t\tstats: ContextCompactionStats,\n\t\tbackupPath?: string,\n\t): string {\n\t\tconst entry = createContextCompactionEntry(deletedTargets, protectedEntryIds, stats, backupPath, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Write a recoverable snapshot of the current session entries without mutating the active JSONL. */\n\twriteBackupSnapshot(label = \"compact\"): string | undefined {\n\t\tif (!this.persist) return undefined;\n\t\treturn createBackupSnapshot(this.sessionFile, this.fileEntries, label);\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn getLatestSessionName(this.getEntries());\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t): string {\n\t\tconst entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(branchFromId, summary, details, fromHook, this.byId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Create a new session file containing only the path from root to the specified leaf. */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst result = createBranchedSessionState({\n\t\t\tleafId,\n\t\t\tpersist: this.persist,\n\t\t\tsessionDir: this.getSessionDir(),\n\t\t\tcwd: this.cwd,\n\t\t\tpreviousSessionFile: this.sessionFile,\n\t\t\tpath: this.getBranch(leafId),\n\t\t\tlabelsById: this.labelsById,\n\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t});\n\t\tthis.fileEntries = result.fileEntries;\n\t\tthis.sessionId = result.sessionId;\n\t\tif (result.sessionFile) this.sessionFile = result.sessionFile;\n\t\tthis._buildIndex();\n\n\t\tif (this.persist) {\n\t\t\tif (result.shouldRewriteFile) this._rewriteFile();\n\t\t\tthis.flushed = result.flushed ?? false;\n\t\t\treturn result.sessionFile;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Create a new session. */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/** Open a specific session file. */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tconst entries = loadEntriesFromFile(resolvedPath);\n\t\tconst header = entries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tconst cwd = cwdOverride ?? header?.cwd ?? process.cwd();\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true);\n\t}\n\n\t/** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(\n\t\t\tdir,\n\t\t\tfilterCwd ? cwd : undefined,\n\t\t\toptions?.includeInternal === true,\n\t\t);\n\t\treturn new SessionManager(cwd, dir, mostRecent ?? undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/** Fork a session from another project directory into the current project. */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);\n\t\treturn new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);\n\t}\n\n\t/** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listProjectSessions(cwd, sessionDir, onProgress, options?.includeInternal === true);\n\t}\n\n\t/** List sessions across all directories. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listAllSessions(sessionDirOrOnProgress, onProgress, options?.includeInternal === true);\n\t}\n}\n"]}
@@ -73,6 +73,7 @@ export class SessionManager {
73
73
  this.fileEntries = [header];
74
74
  this.byId.clear();
75
75
  this.labelsById.clear();
76
+ this.labelTimestampsById.clear();
76
77
  this.leafId = null;
77
78
  this.flushed = false;
78
79
  if (this.persist) {
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-core.js","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE/D,OAAO,EACN,oBAAoB,EACpB,0BAA0B,EAC1B,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,wBAAwB,EACxB,4BAA4B,EAC5B,8BAA8B,EAC9B,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,EACtB,8BAA8B,EAC9B,oBAAoB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACjF,OAAO,EA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AC,QAAQ,CAAC,GAAG,GAAW,OAAO,CAAC,GAAG,EAAE,EAAE,OAA2B;QACvE,OAAO,IAAI,cAAc,CAAC,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/D,CAAC;IAED,8EAA8E;IAC9E,MAAM,CAAC,QAAQ,CACd,UAAkB,EAClB,SAAiB,EACjB,UAAmB,EACnB,OAA2B;QAE3B,MAAM,MAAM,GAAG,mBAAmB,CAAC,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QAC/E,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;IACpF,CAAC;IAED,+GAA+G;IAC/G,MAAM,CAAC,KAAK,CAAC,IAAI,CAChB,GAAW,EACX,UAAmB,EACnB,UAAgC,EAChC,OAAuC;QAEvC,OAAO,mBAAmB,CAAC,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC,CAAC;IAC5F,CAAC;IASD,MAAM,CAAC,KAAK,CAAC,OAAO,CACnB,sBAAqD,EACrD,UAAgC,EAChC,OAAuC;QAEvC,OAAO,eAAe,CAAC,sBAAsB,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC,CAAC;IAC/F,CAAC;CACD","sourcesContent":["import type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { existsSync, statSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport {\n\tcreateBackupSnapshot,\n\tcreateBranchedSessionState,\n\tforkSessionFromFile,\n} from \"./session-manager-archive.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateContextCompactionEntry,\n\tcreateContextWindowChangeEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tgetEntriesWithoutHeader,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateThinkingLevelChangeEntry,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { buildSessionContext, buildSessionIndex, buildSessionTree, getBranchPath } from \"./session-manager-history.ts\";\nimport { listAllSessions, listProjectSessions } from \"./session-manager-list.ts\";\nimport { migrateToCurrentVersion } from \"./session-manager-migrations.ts\";\nimport { getDefaultSessionDir, getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport {\n\tappendSessionEntries,\n\tappendSessionEntry,\n\tensureDirectory,\n\tfindMostRecentSession,\n\thasAssistantMessage,\n\tloadEntriesFromFile,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextCompactionStats,\n\tContextDeletionTarget,\n\tFileEntry,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId } from \"./session-manager-validation.ts\";\n\n/** Manages conversation sessions as append-only trees stored in JSONL files. Each session entry has an id and parentId forming a tree structure. The \"leaf\" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history. Use buildSessionContext() to get the resolved message list for the LLM, which applies context-deletion filtering and follows the path from root to current leaf. */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir) {\n\t\t\tensureDirectory(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis.setSessionFile(sessionFile);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header = createSessionHeader(\n\t\t\tthis.sessionId,\n\t\t\tthis.cwd,\n\t\t\ttimestamp,\n\t\t\toptions?.parentSession,\n\t\t\toptions?.internal,\n\t\t\toptions?.workflow,\n\t\t);\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tthis.sessionFile = createSessionFilePath(this.getSessionDir(), timestamp, this.sessionId);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\t/** Mark the session header as internal (e.g. workflow stage). Preserves an existing full marker on reattach. */\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): void {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tif (!header || (header.internal && header.workflow)) return;\n\t\theader.internal = true;\n\t\tif (workflow) header.workflow = workflow;\n\t\tif (this.flushed) this._rewriteFile();\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\twriteSessionEntries(this.sessionFile, this.fileEntries);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tif (!hasAssistantMessage(this.fileEntries)) {\n\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\tthis.flushed = false;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tappendSessionEntries(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendSessionEntry(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a context window change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendContextWindowChange(contextWindow: number): string {\n\t\tconst entry = createContextWindowChangeEntry(contextWindow, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append logical deletion metadata for deletion-only context compaction. */\n\tappendContextCompaction(\n\t\tdeletedTargets: ContextDeletionTarget[],\n\t\tprotectedEntryIds: string[],\n\t\tstats: ContextCompactionStats,\n\t\tbackupPath?: string,\n\t): string {\n\t\tconst entry = createContextCompactionEntry(deletedTargets, protectedEntryIds, stats, backupPath, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Write a recoverable snapshot of the current session entries without mutating the active JSONL. */\n\twriteBackupSnapshot(label = \"compact\"): string | undefined {\n\t\tif (!this.persist) return undefined;\n\t\treturn createBackupSnapshot(this.sessionFile, this.fileEntries, label);\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn getLatestSessionName(this.getEntries());\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t): string {\n\t\tconst entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(branchFromId, summary, details, fromHook, this.byId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Create a new session file containing only the path from root to the specified leaf. */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst result = createBranchedSessionState({\n\t\t\tleafId,\n\t\t\tpersist: this.persist,\n\t\t\tsessionDir: this.getSessionDir(),\n\t\t\tcwd: this.cwd,\n\t\t\tpreviousSessionFile: this.sessionFile,\n\t\t\tpath: this.getBranch(leafId),\n\t\t\tlabelsById: this.labelsById,\n\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t});\n\t\tthis.fileEntries = result.fileEntries;\n\t\tthis.sessionId = result.sessionId;\n\t\tif (result.sessionFile) this.sessionFile = result.sessionFile;\n\t\tthis._buildIndex();\n\n\t\tif (this.persist) {\n\t\t\tif (result.shouldRewriteFile) this._rewriteFile();\n\t\t\tthis.flushed = result.flushed ?? false;\n\t\t\treturn result.sessionFile;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Create a new session. */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/** Open a specific session file. */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tconst entries = loadEntriesFromFile(resolvedPath);\n\t\tconst header = entries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tconst cwd = cwdOverride ?? header?.cwd ?? process.cwd();\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true);\n\t}\n\n\t/** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(\n\t\t\tdir,\n\t\t\tfilterCwd ? cwd : undefined,\n\t\t\toptions?.includeInternal === true,\n\t\t);\n\t\treturn new SessionManager(cwd, dir, mostRecent ?? undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/** Fork a session from another project directory into the current project. */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);\n\t\treturn new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);\n\t}\n\n\t/** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listProjectSessions(cwd, sessionDir, onProgress, options?.includeInternal === true);\n\t}\n\n\t/** List sessions across all directories. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listAllSessions(sessionDirOrOnProgress, onProgress, options?.includeInternal === true);\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-manager-core.js","sourceRoot":"","sources":["../../src/core/session-manager-core.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE/D,OAAO,EACN,oBAAoB,EACpB,0BAA0B,EAC1B,mBAAmB,GACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,wBAAwB,EACxB,4BAA4B,EAC5B,8BAA8B,EAC9B,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,EACtB,8BAA8B,EAC9B,oBAAoB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,EAAE,eAAe,EAAE,mB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AE,GAAG,EAAE,UAAU,IAAI,SAAS,EAAE,IAAI,CAAC,CAAC;IACpE,CAAC;IAED,wDAAwD;IACxD,MAAM,CAAC,QAAQ,CAAC,GAAG,GAAW,OAAO,CAAC,GAAG,EAAE,EAAE,OAA2B;QACvE,OAAO,IAAI,cAAc,CAAC,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/D,CAAC;IAED,8EAA8E;IAC9E,MAAM,CAAC,QAAQ,CACd,UAAkB,EAClB,SAAiB,EACjB,UAAmB,EACnB,OAA2B;QAE3B,MAAM,MAAM,GAAG,mBAAmB,CAAC,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QAC/E,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;IACpF,CAAC;IAED,+GAA+G;IAC/G,MAAM,CAAC,KAAK,CAAC,IAAI,CAChB,GAAW,EACX,UAAmB,EACnB,UAAgC,EAChC,OAAuC;QAEvC,OAAO,mBAAmB,CAAC,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC,CAAC;IAC5F,CAAC;IASD,MAAM,CAAC,KAAK,CAAC,OAAO,CACnB,sBAAqD,EACrD,UAAgC,EAChC,OAAuC;QAEvC,OAAO,eAAe,CAAC,sBAAsB,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC,CAAC;IAC/F,CAAC;CACD","sourcesContent":["import type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { existsSync, statSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport {\n\tcreateBackupSnapshot,\n\tcreateBranchedSessionState,\n\tforkSessionFromFile,\n} from \"./session-manager-archive.ts\";\nimport {\n\tcreateBranchSummaryEntry,\n\tcreateContextCompactionEntry,\n\tcreateContextWindowChangeEntry,\n\tcreateCustomEntry,\n\tcreateCustomMessageEntry,\n\tcreateLabelEntry,\n\tgetEntriesWithoutHeader,\n\tcreateMessageEntry,\n\tcreateModelChangeEntry,\n\tcreateSessionFilePath,\n\tcreateSessionHeader,\n\tcreateSessionInfoEntry,\n\tcreateThinkingLevelChangeEntry,\n\tgetLatestSessionName,\n} from \"./session-manager-entries.ts\";\nimport { buildSessionContext, buildSessionIndex, buildSessionTree, getBranchPath } from \"./session-manager-history.ts\";\nimport { listAllSessions, listProjectSessions } from \"./session-manager-list.ts\";\nimport { migrateToCurrentVersion } from \"./session-manager-migrations.ts\";\nimport { getDefaultSessionDir, getDefaultSessionDirPath } from \"./session-manager-paths.ts\";\nimport {\n\tappendSessionEntries,\n\tappendSessionEntry,\n\tensureDirectory,\n\tfindMostRecentSession,\n\thasAssistantMessage,\n\tloadEntriesFromFile,\n\twriteSessionEntries,\n} from \"./session-manager-storage.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tContextCompactionStats,\n\tContextDeletionTarget,\n\tFileEntry,\n\tNewSessionOptions,\n\tSessionContext,\n\tSessionEntry,\n\tSessionHeader,\n\tSessionInfo,\n\tSessionListProgress,\n\tSessionTreeNode,\n\tSessionWorkflowMetadata,\n} from \"./session-manager-types.ts\";\nimport { assertValidSessionId, createSessionId } from \"./session-manager-validation.ts\";\n\n/** Manages conversation sessions as append-only trees stored in JSONL files. Each session entry has an id and parentId forming a tree structure. The \"leaf\" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history. Use buildSessionContext() to get the resolved message list for the LLM, which applies context-deletion filtering and follows the path from root to current leaf. */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map<string, SessionEntry> = new Map();\n\tprivate labelsById: Map<string, string> = new Map();\n\tprivate labelTimestampsById: Map<string, string> = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir) {\n\t\t\tensureDirectory(this.sessionDir);\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis.setSessionFile(sessionFile);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header = createSessionHeader(\n\t\t\tthis.sessionId,\n\t\t\tthis.cwd,\n\t\t\ttimestamp,\n\t\t\toptions?.parentSession,\n\t\t\toptions?.internal,\n\t\t\toptions?.workflow,\n\t\t);\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tthis.sessionFile = createSessionFilePath(this.getSessionDir(), timestamp, this.sessionId);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\t/** Mark the session header as internal (e.g. workflow stage). Preserves an existing full marker on reattach. */\n\tmarkSessionInternal(workflow?: SessionWorkflowMetadata): void {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tif (!header || (header.internal && header.workflow)) return;\n\t\theader.internal = true;\n\t\tif (workflow) header.workflow = workflow;\n\t\tif (this.flushed) this._rewriteFile();\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tconst index = buildSessionIndex(this.fileEntries);\n\t\tthis.byId = index.byId;\n\t\tthis.labelsById = index.labelsById;\n\t\tthis.labelTimestampsById = index.labelTimestampsById;\n\t\tthis.leafId = index.leafId;\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\twriteSessionEntries(this.sessionFile, this.fileEntries);\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tif (!hasAssistantMessage(this.fileEntries)) {\n\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\tthis.flushed = false;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tappendSessionEntries(this.sessionFile, this.fileEntries);\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendSessionEntry(this.sessionFile, entry);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id. */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry = createMessageEntry(message, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a context window change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendContextWindowChange(contextWindow: number): string {\n\t\tconst entry = createContextWindowChangeEntry(contextWindow, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append logical deletion metadata for deletion-only context compaction. */\n\tappendContextCompaction(\n\t\tdeletedTargets: ContextDeletionTarget[],\n\t\tprotectedEntryIds: string[],\n\t\tstats: ContextCompactionStats,\n\t\tbackupPath?: string,\n\t): string {\n\t\tconst entry = createContextCompactionEntry(deletedTargets, protectedEntryIds, stats, backupPath, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Write a recoverable snapshot of the current session entries without mutating the active JSONL. */\n\twriteBackupSnapshot(label = \"compact\"): string | undefined {\n\t\tif (!this.persist) return undefined;\n\t\treturn createBackupSnapshot(this.sessionFile, this.fileEntries, label);\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry = createCustomEntry(customType, data, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst entry = createSessionInfoEntry(name, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\treturn getLatestSessionName(this.getEntries());\n\t}\n\n\t/** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */\n\tappendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t\texcludeFromContext?: boolean,\n\t): string {\n\t\tconst entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/** Get all direct children of an entry. */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/** Get the label for an entry, if any. */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/** Set or clear a label on an entry. */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry = createLabelEntry(targetId, label, this.byId, this.leafId);\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/** Walk from entry to root, returning all entries in path order. */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\treturn getBranchPath(fromId ?? this.leafId, this.byId);\n\t}\n\n\t/** Build the session context (what gets sent to the LLM). */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/** Get session header. */\n\tgetHeader(): SessionHeader | null {\n\t\tconst header = this.fileEntries.find((entry) => entry.type === \"session\");\n\t\treturn header ? (header as SessionHeader) : null;\n\t}\n\n\t/** Get all session entries (excludes header). Returns a shallow copy. */\n\tgetEntries(): SessionEntry[] {\n\t\treturn getEntriesWithoutHeader(this.fileEntries);\n\t}\n\n\t/** Get the session as a tree structure. Returns a shallow defensive copy of all entries. */\n\tgetTree(): SessionTreeNode[] {\n\t\treturn buildSessionTree(this.getEntries(), this.labelsById, this.labelTimestampsById);\n\t}\n\n\t/** Start a new branch from an earlier entry. */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/** Reset the leaf pointer to null (before any entries). */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/** Start a new branch with a summary of the abandoned path. */\n\tbranchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = createBranchSummaryEntry(branchFromId, summary, details, fromHook, this.byId);\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Create a new session file containing only the path from root to the specified leaf. */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst result = createBranchedSessionState({\n\t\t\tleafId,\n\t\t\tpersist: this.persist,\n\t\t\tsessionDir: this.getSessionDir(),\n\t\t\tcwd: this.cwd,\n\t\t\tpreviousSessionFile: this.sessionFile,\n\t\t\tpath: this.getBranch(leafId),\n\t\t\tlabelsById: this.labelsById,\n\t\t\tlabelTimestampsById: this.labelTimestampsById,\n\t\t});\n\t\tthis.fileEntries = result.fileEntries;\n\t\tthis.sessionId = result.sessionId;\n\t\tif (result.sessionFile) this.sessionFile = result.sessionFile;\n\t\tthis._buildIndex();\n\n\t\tif (this.persist) {\n\t\t\tif (result.shouldRewriteFile) this._rewriteFile();\n\t\t\tthis.flushed = result.flushed ?? false;\n\t\t\treturn result.sessionFile;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Create a new session. */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/** Open a specific session file. */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tconst entries = loadEntriesFromFile(resolvedPath);\n\t\tconst header = entries.find((entry) => entry.type === \"session\") as SessionHeader | undefined;\n\t\tconst cwd = cwdOverride ?? header?.cwd ?? process.cwd();\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true);\n\t}\n\n\t/** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */\n\tstatic continueRecent(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: { includeInternal?: boolean },\n\t): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(\n\t\t\tdir,\n\t\t\tfilterCwd ? cwd : undefined,\n\t\t\toptions?.includeInternal === true,\n\t\t);\n\t\treturn new SessionManager(cwd, dir, mostRecent ?? undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/** Fork a session from another project directory into the current project. */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);\n\t\treturn new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);\n\t}\n\n\t/** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async list(\n\t\tcwd: string,\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listProjectSessions(cwd, sessionDir, onProgress, options?.includeInternal === true);\n\t}\n\n\t/** List sessions across all directories. Internal (workflow) sessions are excluded unless `includeInternal: true`. */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDir?: string,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]>;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t\toptions?: { includeInternal?: boolean },\n\t): Promise<SessionInfo[]> {\n\t\treturn listAllSessions(sessionDirOrOnProgress, onProgress, options?.includeInternal === true);\n\t}\n}\n"]}
@@ -3,8 +3,8 @@ export declare function getLatestCompactionBoundaryEntry(entries: SessionEntry[]
3
3
  /**
4
4
  * Build raw deletion filters from persisted context_compaction entries.
5
5
  *
6
- * These raw filters do not apply replay-safety repair for latest assistant
7
- * thinking/redacted_thinking blocks or their paired tool results. Production
6
+ * These raw filters do not apply replay-safety repair for assistant
7
+ * thinking/redacted_thinking turns or their paired tool results. Production
8
8
  * context rebuild paths should prefer `buildEffectiveContextDeletionFilters`
9
9
  * or `buildContextDeletionFilteredPath(path)` unless they intentionally need
10
10
  * the un-repaired historical deletion plan for diagnostics.
@@ -1 +1 @@
1
- {"version":3,"file":"session-manager-history.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-history.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,sBAAsB,EACtB,sBAAsB,EACtB,SAAS,EACT,cAAc,EACd,YAAY,EAEZ,eAAe,EACf,MAAM,4BAA4B,CAAC;AAEpC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nB","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"./messages.ts\";\nimport { contentArrayHasAssistantThinkingBlock } from \"./thinking-blocks.ts\";\nimport { reconcilePersistedToolDependencyFilters } from \"./session-manager-tool-dependencies.ts\";\nimport type {\n\tContextCompactionEntry,\n\tContextDeletionFilters,\n\tFileEntry,\n\tSessionContext,\n\tSessionEntry,\n\tSessionMessageEntry,\n\tSessionTreeNode,\n} from \"./session-manager-types.ts\";\n\nexport function getLatestCompactionBoundaryEntry(entries: SessionEntry[]): ContextCompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"context_compaction\") {\n\t\t\treturn entry;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Build raw deletion filters from persisted context_compaction entries.\n *\n * These raw filters do not apply replay-safety repair for latest assistant\n * thinking/redacted_thinking blocks or their paired tool results. Production\n * context rebuild paths should prefer `buildEffectiveContextDeletionFilters`\n * or `buildContextDeletionFilteredPath(path)` unless they intentionally need\n * the un-repaired historical deletion plan for diagnostics.\n */\nexport function buildContextDeletionFilters(path: SessionEntry[]): ContextDeletionFilters {\n\tconst deletedEntryIds = new Set<string>();\n\tconst deletedContentBlocks = new Map<string, Set<number>>();\n\n\tfor (const entry of path) {\n\t\tif (entry.type !== \"context_compaction\") continue;\n\t\tfor (const target of entry.deletedTargets) {\n\t\t\tif (target.kind === \"entry\") {\n\t\t\t\tdeletedEntryIds.add(target.entryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst existing = deletedContentBlocks.get(target.entryId) ?? new Set<number>();\n\t\t\texisting.add(target.blockIndex);\n\t\t\tdeletedContentBlocks.set(target.entryId, existing);\n\t\t}\n\t}\n\n\treturn { deletedEntryIds, deletedContentBlocks };\n}\n\nfunction getToolCallContentBlockId(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst candidate = block as { type?: unknown; id?: unknown };\n\treturn candidate.type === \"toolCall\" && typeof candidate.id === \"string\" ? candidate.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\nfunction collectToolCallContentBlockIds(content: readonly unknown[]): Set<string> {\n\tconst toolCallIds = new Set<string>();\n\tfor (const block of content) {\n\t\tconst toolCallId = getToolCallContentBlockId(block);\n\t\tif (toolCallId) toolCallIds.add(toolCallId);\n\t}\n\treturn toolCallIds;\n}\n\nfunction addDeletionTarget(filters: ContextDeletionFilters, target: ContextCompactionEntry[\"deletedTargets\"][number]): void {\n\tif (target.kind === \"entry\") {\n\t\tfilters.deletedEntryIds.add(target.entryId);\n\t\treturn;\n\t}\n\tconst existing = filters.deletedContentBlocks.get(target.entryId) ?? new Set<number>();\n\texisting.add(target.blockIndex);\n\tfilters.deletedContentBlocks.set(target.entryId, existing);\n}\n\nfunction buildToolResultEntryIdsByCallId(path: SessionEntry[]): Map<string, Set<string>> {\n\tconst toolResultEntryIdsByCallId = new Map<string, Set<string>>();\n\tfor (const entry of path) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tconst toolCallId = getToolResultCallId(entry.message);\n\t\tif (!toolCallId) continue;\n\t\tconst existing = toolResultEntryIdsByCallId.get(toolCallId) ?? new Set<string>();\n\t\texisting.add(entry.id);\n\t\ttoolResultEntryIdsByCallId.set(toolCallId, existing);\n\t}\n\treturn toolResultEntryIdsByCallId;\n}\n\nfunction findRetainedThinkingAssistants(\n\tpath: SessionEntry[],\n\tdeletedEntryIds: ReadonlySet<string>,\n): SessionMessageEntry[] {\n\treturn path.filter((entry): entry is SessionMessageEntry => {\n\t\tif (entry.type !== \"message\") return false;\n\t\tif (deletedEntryIds.has(entry.id)) return false;\n\t\tif (entry.message.role !== \"assistant\") return false;\n\t\treturn contentArrayHasAssistantThinkingBlock(entry.message.content);\n\t});\n}\n\nexport function buildEffectiveContextDeletionFilters(path: SessionEntry[]): ContextDeletionFilters {\n\tconst filters = buildContextDeletionFilters(path);\n\tif (!path.some((entry) => entry.type === \"context_compaction\")) return filters;\n\n\tconst rawDeletedEntryIds = new Set<string>();\n\tfor (const compaction of path) {\n\t\tif (compaction.type !== \"context_compaction\") continue;\n\t\tfor (const target of compaction.deletedTargets) {\n\t\t\tif (target.kind === \"entry\") rawDeletedEntryIds.add(target.entryId);\n\t\t}\n\t}\n\tconst retainedThinkingAssistants = findRetainedThinkingAssistants(path, rawDeletedEntryIds);\n\tconst retainedThinkingAssistantIds = new Set(retainedThinkingAssistants.map((entry) => entry.id));\n\tconst retainedThinkingAssistantById = new Map(retainedThinkingAssistants.map((entry) => [entry.id, entry]));\n\tconst toolResultEntryIdsByCallId = buildToolResultEntryIdsByCallId(path);\n\tconst effectiveFilters: ContextDeletionFilters = {\n\t\tdeletedEntryIds: new Set<string>(),\n\t\tdeletedContentBlocks: new Map<string, Set<number>>(),\n\t};\n\tconst allRestoredToolResultEntryIds = new Set<string>();\n\n\tfor (const compaction of path) {\n\t\tif (compaction.type !== \"context_compaction\") continue;\n\t\tfor (const target of compaction.deletedTargets) {\n\t\t\tif (target.kind !== \"content_block\") continue;\n\t\t\tconst retainedThinkingAssistant = retainedThinkingAssistantById.get(target.entryId);\n\t\t\tif (!retainedThinkingAssistant) continue;\n\t\t\tconst content = (retainedThinkingAssistant.message as { content: readonly unknown[] }).content;\n\t\t\tfor (const toolCallId of collectToolCallContentBlockIds(content)) {\n\t\t\t\tfor (const entryId of toolResultEntryIdsByCallId.get(toolCallId) ?? []) {\n\t\t\t\t\tallRestoredToolResultEntryIds.add(entryId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const compaction of path) {\n\t\tif (compaction.type !== \"context_compaction\") continue;\n\t\tlet restoresRetainedThinkingAssistant = false;\n\t\tfor (const target of compaction.deletedTargets) {\n\t\t\tif (target.kind === \"content_block\" && retainedThinkingAssistantIds.has(target.entryId)) {\n\t\t\t\trestoresRetainedThinkingAssistant = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor (const target of compaction.deletedTargets) {\n\t\t\tif (target.kind === \"content_block\" && retainedThinkingAssistantIds.has(target.entryId)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// When a stale persisted plan tried to partially filter a retained\n\t\t\t// thinking-bearing assistant, treat the same compaction entry as one\n\t\t\t// unsafe unit and restore its paired tool results. Later compaction\n\t\t\t// entries may still trim those restored multi-block results normally,\n\t\t\t// but whole-entry deletion of those paired results remains unsafe in any\n\t\t\t// later compaction because the assistant tool call is retained.\n\t\t\tif (restoresRetainedThinkingAssistant && allRestoredToolResultEntryIds.has(target.entryId)) continue;\n\t\t\tif (target.kind === \"entry\" && allRestoredToolResultEntryIds.has(target.entryId)) continue;\n\t\t\taddDeletionTarget(effectiveFilters, target);\n\t\t}\n\t}\n\n\treturn reconcilePersistedToolDependencyFilters(path, effectiveFilters);\n}\n\nfunction filterContentArray<T>(content: T[], deletedBlocks: ReadonlySet<number>): T[] {\n\treturn content.filter((_, index) => !deletedBlocks.has(index));\n}\n\nfunction filterMessageContentBlocks(\n\tmessage: AgentMessage,\n\tdeletedBlocks: ReadonlySet<number> | undefined,\n): AgentMessage | undefined {\n\tif (!deletedBlocks || deletedBlocks.size === 0) return message;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"toolResult\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"custom\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"bashExecution\":\n\t\tcase \"branchSummary\":\n\t\t\treturn message;\n\t}\n}\n\n/**\n * Return the active branch path after applying logical context-deletion entries.\n * Whole-entry deletions remove the entry from the path. Content-block deletions\n * clone only affected message/custom-message entries so retained blocks stay verbatim.\n * The optional filters parameter is for callers that already computed effective\n * filters with `buildEffectiveContextDeletionFilters(path)` and want to avoid\n * repeating the repair pass.\n */\nexport function buildContextDeletionFilteredPath(\n\tpath: SessionEntry[],\n\teffectiveFilters: ContextDeletionFilters = buildEffectiveContextDeletionFilters(path),\n): SessionEntry[] {\n\tconst filteredPath: SessionEntry[] = [];\n\n\tfor (const entry of path) {\n\t\tif (effectiveFilters.deletedEntryIds.has(entry.id)) continue;\n\n\t\tconst deletedBlocks = effectiveFilters.deletedContentBlocks.get(entry.id);\n\t\tif (!deletedBlocks || deletedBlocks.size === 0) {\n\t\t\tfilteredPath.push(entry);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type === \"message\") {\n\t\t\tconst message = filterMessageContentBlocks(entry.message, deletedBlocks);\n\t\t\tif (message) filteredPath.push({ ...entry, message });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type === \"custom_message\" && Array.isArray(entry.content)) {\n\t\t\tconst content = filterContentArray(entry.content, deletedBlocks);\n\t\t\tif (content.length > 0) filteredPath.push({ ...entry, content });\n\t\t\tcontinue;\n\t\t}\n\n\t\tfilteredPath.push(entry);\n\t}\n\n\treturn filteredPath;\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Applies context-deletion filtering and includes branch summaries along the path.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionContext {\n\t// Build uuid index if not available\n\tif (!byId) {\n\t\tbyId = new Map<string, SessionEntry>();\n\t\tfor (const entry of entries) {\n\t\t\tbyId.set(entry.id, entry);\n\t\t}\n\t}\n\n\t// Find leaf\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\t// Explicitly null - return no messages (navigated to before first entry)\n\t\treturn { messages: [], thinkingLevel: \"off\", contextWindow: undefined, model: null };\n\t}\n\tif (leafId) {\n\t\tleaf = byId.get(leafId);\n\t}\n\tif (!leaf) {\n\t\t// Fallback to last entry (when leafId is undefined)\n\t\tleaf = entries[entries.length - 1];\n\t}\n\n\tif (!leaf) {\n\t\treturn { messages: [], thinkingLevel: \"off\", contextWindow: undefined, model: null };\n\t}\n\n\t// Walk from leaf to root, collecting path\n\tconst path = getBranchPath(leaf.id, byId);\n\n\t// Extract settings\n\tlet thinkingLevel = \"off\";\n\tlet contextWindow: number | undefined;\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"context_window_change\") {\n\t\t\tcontextWindow = entry.contextWindow;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\tconst filteredPath = buildContextDeletionFilteredPath(path);\n\n\t// Build active context messages from the filtered path. Legacy \"compaction\"\n\t// entries are archival metadata and intentionally inert here.\n\tconst messages: AgentMessage[] = [];\n\n\tconst appendMessage = (entry: SessionEntry) => {\n\t\tlet message: AgentMessage | undefined;\n\t\tif (entry.type === \"message\") {\n\t\t\tmessage = entry.message;\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessage = createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && entry.summary) {\n\t\t\tmessage = createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t\t}\n\n\t\tif (message) messages.push(message);\n\t};\n\n\tfor (const entry of filteredPath) {\n\t\tappendMessage(entry);\n\t}\n\n\treturn { messages, thinkingLevel, contextWindow, model };\n}\n\nexport interface SessionIndex {\n\tbyId: Map<string, SessionEntry>;\n\tlabelsById: Map<string, string>;\n\tlabelTimestampsById: Map<string, string>;\n\tleafId: string | null;\n}\n\nexport function buildSessionIndex(fileEntries: FileEntry[]): SessionIndex {\n\tconst byId = new Map<string, SessionEntry>();\n\tconst labelsById = new Map<string, string>();\n\tconst labelTimestampsById = new Map<string, string>();\n\tlet leafId: string | null = null;\n\n\tfor (const entry of fileEntries) {\n\t\tif (entry.type === \"session\") continue;\n\t\tbyId.set(entry.id, entry);\n\t\tleafId = entry.id;\n\t\tif (entry.type === \"label\") {\n\t\t\tif (entry.label) {\n\t\t\t\tlabelsById.set(entry.targetId, entry.label);\n\t\t\t\tlabelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tlabelsById.delete(entry.targetId);\n\t\t\t\tlabelTimestampsById.delete(entry.targetId);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { byId, labelsById, labelTimestampsById, leafId };\n}\n\nexport function getBranchPath(fromId: string | null | undefined, byId: Map<string, SessionEntry>): SessionEntry[] {\n\tconst path: SessionEntry[] = [];\n\tlet current = fromId ? byId.get(fromId) : undefined;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? byId.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nexport function buildSessionTree(\n\tentries: SessionEntry[],\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): SessionTreeNode[] {\n\tconst nodeMap = new Map<string, SessionTreeNode>();\n\tconst roots: SessionTreeNode[] = [];\n\n\t// Create nodes with resolved labels\n\tfor (const entry of entries) {\n\t\tconst label = labelsById.get(entry.id);\n\t\tconst labelTimestamp = labelTimestampsById.get(entry.id);\n\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t}\n\n\t// Build tree\n\tfor (const entry of entries) {\n\t\tconst node = nodeMap.get(entry.id)!;\n\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\troots.push(node);\n\t\t} else {\n\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\tif (parent) {\n\t\t\t\tparent.children.push(node);\n\t\t\t} else {\n\t\t\t\t// Orphan - treat as root\n\t\t\t\troots.push(node);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort children by timestamp (oldest first, newest at bottom)\n\t// Use iterative approach to avoid stack overflow on deep trees\n\tconst stack: SessionTreeNode[] = [...roots];\n\twhile (stack.length > 0) {\n\t\tconst node = stack.pop()!;\n\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\tstack.push(...node.children);\n\t}\n\n\treturn roots;\n}\n"]}
1
+ {"version":3,"file":"session-manager-history.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-history.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACX,sBAAsB,EACtB,sBAAsB,EACtB,SAAS,EACT,cAAc,EACd,YAAY,EACZ,eAAe,EACf,MAAM,4BAA4B,CAAC;AAEpC,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,sBAAsB,GAAG,IAAI,CAQvG;AAED;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,YAAY,EAAE,GAAG,sBAAsB,CAkBxF;AAoHD,wBAAgB,oCAAoC,CAAC,IAAI,EAAE,YAAY,EAAE,GAAG,sBAAsB,CA6BjG;AA0CD;;;;;;;GAOG;AACH,wBAAgB,gCAAgC,CAC/C,IAAI,EAAE,YAAY,EAAE,EACpB,gBAAgB,CAAC,EAAE,sBAAsB,GACvC,YAAY,EAAE,CA8BhB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,GAC9B,cAAc,CA8EhB;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,SAAS,EAAE,GAAG,YAAY,CAsBxE;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,GAAG,YAAY,EAAE,CAShH;AAED,wBAAgB,gBAAgB,CAC/B,OAAO,EAAE,YAAY,EAAE,EACvB,UAAU,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACvC,mBAAmB,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAC9C,eAAe,EAAE,CAqCnB","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageStartsLlmUserTurn,\n\tnormalizeMessageContent,\n\tuserLikeContentIsLlmVisible,\n} from \"./messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"./session-entry-normalization.ts\";\nimport { contentArrayHasAssistantThinkingBlock } from \"./thinking-blocks.ts\";\nimport { reconcilePersistedToolDependencyFilters } from \"./session-manager-tool-dependencies.ts\";\nimport { analyzeAssistantToolUseTurns, type AssistantTurnEntry } from \"./compaction/context-assistant-turns.js\";\nimport type {\n\tContextCompactionEntry,\n\tContextDeletionFilters,\n\tFileEntry,\n\tSessionContext,\n\tSessionEntry,\n\tSessionTreeNode,\n} from \"./session-manager-types.ts\";\n\nexport function getLatestCompactionBoundaryEntry(entries: SessionEntry[]): ContextCompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"context_compaction\") {\n\t\t\treturn entry;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Build raw deletion filters from persisted context_compaction entries.\n *\n * These raw filters do not apply replay-safety repair for assistant\n * thinking/redacted_thinking turns or their paired tool results. Production\n * context rebuild paths should prefer `buildEffectiveContextDeletionFilters`\n * or `buildContextDeletionFilteredPath(path)` unless they intentionally need\n * the un-repaired historical deletion plan for diagnostics.\n */\nexport function buildContextDeletionFilters(path: SessionEntry[]): ContextDeletionFilters {\n\tconst deletedEntryIds = new Set<string>();\n\tconst deletedContentBlocks = new Map<string, Set<number>>();\n\n\tfor (const entry of path) {\n\t\tif (entry.type !== \"context_compaction\") continue;\n\t\tfor (const target of entry.deletedTargets) {\n\t\t\tif (target.kind === \"entry\") {\n\t\t\t\tdeletedEntryIds.add(target.entryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst existing = deletedContentBlocks.get(target.entryId) ?? new Set<number>();\n\t\t\texisting.add(target.blockIndex);\n\t\t\tdeletedContentBlocks.set(target.entryId, existing);\n\t\t}\n\t}\n\n\treturn { deletedEntryIds, deletedContentBlocks };\n}\n\nfunction restoreEntry(filters: ContextDeletionFilters, entryId: string): void {\n\tfilters.deletedEntryIds.delete(entryId);\n\tfilters.deletedContentBlocks.delete(entryId);\n}\n\nfunction addDeletionTarget(\n\tfilters: ContextDeletionFilters,\n\ttarget: ContextCompactionEntry[\"deletedTargets\"][number],\n): void {\n\tif (target.kind === \"entry\") {\n\t\tfilters.deletedEntryIds.add(target.entryId);\n\t\tfilters.deletedContentBlocks.delete(target.entryId);\n\t\treturn;\n\t}\n\tif (filters.deletedEntryIds.has(target.entryId)) return;\n\tconst existing = filters.deletedContentBlocks.get(target.entryId) ?? new Set<number>();\n\texisting.add(target.blockIndex);\n\tfilters.deletedContentBlocks.set(target.entryId, existing);\n}\n\nfunction sessionBoundaryIsVisible(entry: SessionEntry, filters: ContextDeletionFilters): boolean {\n\tif (filters.deletedEntryIds.has(entry.id)) return false;\n\tconst deletedBlocks = filters.deletedContentBlocks.get(entry.id);\n\tif (entry.type === \"custom_message\") {\n\t\treturn entry.excludeFromContext !== true && userLikeContentIsLlmVisible(entry.content, deletedBlocks);\n\t}\n\tif (entry.type === \"branch_summary\") return typeof entry.summary === \"string\" && entry.summary.length > 0;\n\tif (entry.type !== \"message\") return false;\n\treturn messageStartsLlmUserTurn(entry.message, deletedBlocks);\n}\n\nfunction sessionEntryAsTurnEntry(\n\tentry: SessionEntry,\n\tfilters: ContextDeletionFilters,\n): AssistantTurnEntry | undefined {\n\tif (entry.type === \"custom_message\") {\n\t\tif (entry.excludeFromContext === true) return undefined;\n\t\treturn {\n\t\t\tentryId: entry.id,\n\t\t\trole: \"custom\",\n\t\t\thasSignedThinking: false,\n\t\t\tstartsNewTurn: sessionBoundaryIsVisible(entry, filters),\n\t\t};\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn {\n\t\t\tentryId: entry.id,\n\t\t\trole: \"branchSummary\",\n\t\t\thasSignedThinking: false,\n\t\t\tstartsNewTurn: sessionBoundaryIsVisible(entry, filters),\n\t\t};\n\t}\n\tif (entry.type !== \"message\") return undefined;\n\tconst message = entry.message;\n\tif (message.role === \"compactionSummary\") return undefined;\n\tif (\n\t\t(message.role === \"bashExecution\" && message.excludeFromContext === true) ||\n\t\t(message.role === \"custom\" && (message as { excludeFromContext?: boolean }).excludeFromContext === true)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tentryId: entry.id,\n\t\trole: message.role,\n\t\thasSignedThinking: message.role === \"assistant\" && contentArrayHasAssistantThinkingBlock(message.content),\n\t\tstartsNewTurn: sessionBoundaryIsVisible(entry, filters),\n\t};\n}\n\nfunction analyzeSessionAssistantTurns(path: SessionEntry[], filters: ContextDeletionFilters) {\n\treturn analyzeAssistantToolUseTurns(path.flatMap((entry) => sessionEntryAsTurnEntry(entry, filters) ?? []));\n}\n\nfunction repairSignedThinkingTurnFilters(path: SessionEntry[], filters: ContextDeletionFilters): ContextDeletionFilters {\n\tconst turns = analyzeSessionAssistantTurns(path, filters);\n\n\t// A retained signed assistant is byte-exact/all-or-nothing at message level.\n\t// Whole-entry deletion alone counts toward a safe historical omission.\n\tfor (const turn of turns) {\n\t\tfor (const entryId of turn.signedThinkingEntryIds) {\n\t\t\tif (!filters.deletedEntryIds.has(entryId)) filters.deletedContentBlocks.delete(entryId);\n\t\t}\n\t}\n\n\tfor (const turn of turns) {\n\t\tconst deletedSignedIds = turn.signedThinkingEntryIds.filter((entryId) => filters.deletedEntryIds.has(entryId));\n\t\tconst unsafe = turn.active\n\t\t\t? deletedSignedIds.length > 0\n\t\t\t: deletedSignedIds.length > 0 && deletedSignedIds.length < turn.signedThinkingEntryIds.length;\n\t\tif (!unsafe) continue;\n\t\tfor (const entryId of turn.signedThinkingEntryIds) restoreEntry(filters, entryId);\n\t}\n\treturn filters;\n}\n\nfunction signedTurnReplayPolicy(\n\tpath: SessionEntry[],\n\tfinalIntent: ContextDeletionFilters,\n): { restoredEntryIds: Set<string>; retainedEntryIds: Set<string> } {\n\tconst restoredEntryIds = new Set<string>();\n\tconst retainedEntryIds = new Set<string>();\n\tfor (const turn of analyzeSessionAssistantTurns(path, finalIntent)) {\n\t\tconst deleted = turn.signedThinkingEntryIds.filter((entryId) => finalIntent.deletedEntryIds.has(entryId));\n\t\tconst restoreTurn = turn.active\n\t\t\t? deleted.length > 0\n\t\t\t: deleted.length > 0 && deleted.length < turn.signedThinkingEntryIds.length;\n\t\tfor (const entryId of turn.signedThinkingEntryIds) {\n\t\t\tif (restoreTurn) restoredEntryIds.add(entryId);\n\t\t\tif (restoreTurn || !finalIntent.deletedEntryIds.has(entryId)) retainedEntryIds.add(entryId);\n\t\t}\n\t}\n\treturn { restoredEntryIds, retainedEntryIds };\n}\n\nexport function buildEffectiveContextDeletionFilters(path: SessionEntry[]): ContextDeletionFilters {\n\tconst derivedPath = normalizeDerivedSessionEntries(path);\n\tconst finalIntent = buildContextDeletionFilters(derivedPath);\n\tif (!derivedPath.some((entry) => entry.type === \"context_compaction\")) return finalIntent;\n\n\t// Decide turn-level restoration from the cumulative durable intent so safe\n\t// complete historical omissions may span multiple compaction entries. Then\n\t// replay each entry chronologically: reconciliation at each boundary restores\n\t// an unsafe paired whole-result deletion without erasing a later independent\n\t// content-block deletion on that result.\n\tconst { restoredEntryIds, retainedEntryIds } = signedTurnReplayPolicy(derivedPath, finalIntent);\n\tconst effective: ContextDeletionFilters = {\n\t\tdeletedEntryIds: new Set<string>(),\n\t\tdeletedContentBlocks: new Map<string, Set<number>>(),\n\t};\n\tfor (const entry of derivedPath) {\n\t\tif (entry.type !== \"context_compaction\") continue;\n\t\tfor (const target of entry.deletedTargets) {\n\t\t\tif (target.kind === \"entry\" && restoredEntryIds.has(target.entryId)) continue;\n\t\t\tif (target.kind === \"content_block\" && retainedEntryIds.has(target.entryId)) continue;\n\t\t\taddDeletionTarget(effective, target);\n\t\t}\n\t\treconcilePersistedToolDependencyFilters(derivedPath, effective);\n\t}\n\n\t// Defensive final repair handles malformed dependency graphs and keeps this\n\t// reconstruction path authoritative even if reconciliation behavior evolves.\n\trepairSignedThinkingTurnFilters(derivedPath, effective);\n\treturn reconcilePersistedToolDependencyFilters(derivedPath, effective);\n}\n\nfunction filterContentArray<T>(content: T[], deletedBlocks: ReadonlySet<number>): T[] {\n\treturn content.filter((_, index) => !deletedBlocks.has(index));\n}\n\nfunction filterMessageContentBlocks(\n\tmessage: AgentMessage,\n\tdeletedBlocks: ReadonlySet<number> | undefined,\n): AgentMessage | undefined {\n\tif (!deletedBlocks || deletedBlocks.size === 0) return message;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"toolResult\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"custom\": {\n\t\t\tif (!Array.isArray(message.content)) return message;\n\t\t\tconst content = filterContentArray(message.content, deletedBlocks);\n\t\t\tif (content.length === 0) return undefined;\n\t\t\treturn { ...message, content };\n\t\t}\n\t\tcase \"bashExecution\":\n\t\tcase \"branchSummary\":\n\t\t\treturn message;\n\t}\n}\n\n/**\n * Return the active branch path after applying logical context-deletion entries.\n * Whole-entry deletions remove the entry from the path. Content-block deletions\n * clone only affected message/custom-message entries so retained blocks stay verbatim.\n * The optional filters parameter is for callers that already computed effective\n * filters with `buildEffectiveContextDeletionFilters(path)` and want to avoid\n * repeating the repair pass.\n */\nexport function buildContextDeletionFilteredPath(\n\tpath: SessionEntry[],\n\teffectiveFilters?: ContextDeletionFilters,\n): SessionEntry[] {\n\tconst derivedPath = normalizeDerivedSessionEntries(path);\n\tconst filters = effectiveFilters ?? buildEffectiveContextDeletionFilters(derivedPath);\n\tconst filteredPath: SessionEntry[] = [];\n\n\tfor (const entry of derivedPath) {\n\t\tif (filters.deletedEntryIds.has(entry.id)) continue;\n\n\t\tconst deletedBlocks = filters.deletedContentBlocks.get(entry.id);\n\t\tif (!deletedBlocks || deletedBlocks.size === 0) {\n\t\t\tfilteredPath.push(entry);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type === \"message\") {\n\t\t\tconst message = filterMessageContentBlocks(entry.message, deletedBlocks);\n\t\t\tif (message) filteredPath.push({ ...entry, message });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type === \"custom_message\" && Array.isArray(entry.content)) {\n\t\t\tconst content = filterContentArray(entry.content, deletedBlocks);\n\t\t\tif (content.length > 0) filteredPath.push({ ...entry, content });\n\t\t\tcontinue;\n\t\t}\n\n\t\tfilteredPath.push(entry);\n\t}\n\n\treturn filteredPath;\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Applies context-deletion filtering and includes branch summaries along the path.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionContext {\n\t// Build uuid index if not available\n\tif (!byId) {\n\t\tbyId = new Map<string, SessionEntry>();\n\t\tfor (const entry of entries) {\n\t\t\tbyId.set(entry.id, entry);\n\t\t}\n\t}\n\n\t// Find leaf\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\t// Explicitly null - return no messages (navigated to before first entry)\n\t\treturn { messages: [], thinkingLevel: \"off\", contextWindow: undefined, model: null };\n\t}\n\tif (leafId) {\n\t\tleaf = byId.get(leafId);\n\t}\n\tif (!leaf) {\n\t\t// Fallback to last entry (when leafId is undefined)\n\t\tleaf = entries[entries.length - 1];\n\t}\n\n\tif (!leaf) {\n\t\treturn { messages: [], thinkingLevel: \"off\", contextWindow: undefined, model: null };\n\t}\n\n\t// Walk from leaf to root, collecting path\n\tconst path = normalizeDerivedSessionEntries(getBranchPath(leaf.id, byId));\n\n\t// Extract settings\n\tlet thinkingLevel = \"off\";\n\tlet contextWindow: number | undefined;\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"context_window_change\") {\n\t\t\tcontextWindow = entry.contextWindow;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\tconst filteredPath = buildContextDeletionFilteredPath(path);\n\n\t// Build active context messages from the filtered path. Legacy \"compaction\"\n\t// entries are archival metadata and intentionally inert here.\n\tconst messages: AgentMessage[] = [];\n\n\tconst appendMessage = (entry: SessionEntry) => {\n\t\tlet message: AgentMessage | undefined;\n\t\tif (entry.type === \"message\") {\n\t\t\tmessage = normalizeMessageContent(entry.message);\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessage = createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && typeof entry.summary === \"string\" && entry.summary.length > 0) {\n\t\t\tmessage = createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t\t}\n\n\t\tif (message) messages.push(message);\n\t};\n\n\tfor (const entry of filteredPath) {\n\t\tappendMessage(entry);\n\t}\n\n\treturn { messages, thinkingLevel, contextWindow, model };\n}\n\nexport interface SessionIndex {\n\tbyId: Map<string, SessionEntry>;\n\tlabelsById: Map<string, string>;\n\tlabelTimestampsById: Map<string, string>;\n\tleafId: string | null;\n}\n\nexport function buildSessionIndex(fileEntries: FileEntry[]): SessionIndex {\n\tconst byId = new Map<string, SessionEntry>();\n\tconst labelsById = new Map<string, string>();\n\tconst labelTimestampsById = new Map<string, string>();\n\tlet leafId: string | null = null;\n\n\tfor (const entry of fileEntries) {\n\t\tif (entry.type === \"session\") continue;\n\t\tbyId.set(entry.id, entry);\n\t\tleafId = entry.id;\n\t\tif (entry.type === \"label\") {\n\t\t\tif (entry.label) {\n\t\t\t\tlabelsById.set(entry.targetId, entry.label);\n\t\t\t\tlabelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tlabelsById.delete(entry.targetId);\n\t\t\t\tlabelTimestampsById.delete(entry.targetId);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { byId, labelsById, labelTimestampsById, leafId };\n}\n\nexport function getBranchPath(fromId: string | null | undefined, byId: Map<string, SessionEntry>): SessionEntry[] {\n\tconst path: SessionEntry[] = [];\n\tlet current = fromId ? byId.get(fromId) : undefined;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? byId.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nexport function buildSessionTree(\n\tentries: SessionEntry[],\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): SessionTreeNode[] {\n\tconst nodeMap = new Map<string, SessionTreeNode>();\n\tconst roots: SessionTreeNode[] = [];\n\n\t// Create nodes with resolved labels\n\tfor (const entry of entries) {\n\t\tconst label = labelsById.get(entry.id);\n\t\tconst labelTimestamp = labelTimestampsById.get(entry.id);\n\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t}\n\n\t// Build tree\n\tfor (const entry of entries) {\n\t\tconst node = nodeMap.get(entry.id)!;\n\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\troots.push(node);\n\t\t} else {\n\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\tif (parent) {\n\t\t\t\tparent.children.push(node);\n\t\t\t} else {\n\t\t\t\t// Orphan - treat as root\n\t\t\t\troots.push(node);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort children by timestamp (oldest first, newest at bottom)\n\t// Use iterative approach to avoid stack overflow on deep trees\n\tconst stack: SessionTreeNode[] = [...roots];\n\twhile (stack.length > 0) {\n\t\tconst node = stack.pop()!;\n\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\tstack.push(...node.children);\n\t}\n\n\treturn roots;\n}\n"]}