@bastani/atomic 0.9.11-alpha.9 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/README.md +1 -1
  3. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  4. package/dist/builtin/intercom/package.json +1 -1
  5. package/dist/builtin/intercom/subagent-relay.ts +8 -5
  6. package/dist/builtin/mcp/CHANGELOG.md +10 -0
  7. package/dist/builtin/mcp/package.json +1 -1
  8. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  9. package/dist/builtin/subagents/agents/code-simplifier.md +2 -2
  10. package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -2
  11. package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
  12. package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -2
  13. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
  14. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -2
  15. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
  16. package/dist/builtin/subagents/agents/worker.md +2 -2
  17. package/dist/builtin/subagents/package.json +1 -1
  18. package/dist/builtin/subagents/src/extension/notification-content.ts +14 -9
  19. package/dist/builtin/subagents/src/runs/background/notify.ts +20 -4
  20. package/dist/builtin/web-access/CHANGELOG.md +20 -0
  21. package/dist/builtin/web-access/content-tools.ts +1 -0
  22. package/dist/builtin/web-access/flat-string.ts +37 -0
  23. package/dist/builtin/web-access/github-api.ts +2 -1
  24. package/dist/builtin/web-access/github-extract.ts +3 -2
  25. package/dist/builtin/web-access/package.json +2 -2
  26. package/dist/builtin/workflows/CHANGELOG.md +57 -0
  27. package/dist/builtin/workflows/builtin/goal-ledger.ts +6 -4
  28. package/dist/builtin/workflows/builtin/goal-runner.ts +2 -1
  29. package/dist/builtin/workflows/builtin/goal.ts +1 -1
  30. package/dist/builtin/workflows/builtin/ralph-core.ts +8 -9
  31. package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +2 -4
  32. package/dist/builtin/workflows/builtin/ralph-models.ts +4 -4
  33. package/dist/builtin/workflows/builtin/ralph-runner.ts +5 -8
  34. package/dist/builtin/workflows/builtin/ralph.ts +2 -1
  35. package/dist/builtin/workflows/package.json +1 -1
  36. package/dist/builtin/workflows/src/durable/completed-catalog.ts +14 -8
  37. package/dist/builtin/workflows/src/durable/completed-inspection.ts +10 -11
  38. package/dist/builtin/workflows/src/durable/resume-catalog.ts +1 -1
  39. package/dist/builtin/workflows/src/durable/resume-eligibility.ts +42 -0
  40. package/dist/builtin/workflows/src/durable/resume-runtime.ts +36 -37
  41. package/dist/builtin/workflows/src/durable/tool-primitive.ts +10 -2
  42. package/dist/builtin/workflows/src/engine/run.ts +1 -0
  43. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +12 -8
  44. package/dist/builtin/workflows/src/extension/hil-answer-notifications.ts +5 -2
  45. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1966 -880
  46. package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +6 -3
  47. package/dist/builtin/workflows/src/extension/postmortem-deps.ts +3 -2
  48. package/dist/builtin/workflows/src/extension/render-result.ts +4 -11
  49. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +17 -20
  50. package/dist/builtin/workflows/src/extension/runtime.ts +3 -3
  51. package/dist/builtin/workflows/src/extension/workflow-command-completions.ts +1 -1
  52. package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +3 -7
  53. package/dist/builtin/workflows/src/extension/workflow-durable-resume-command.ts +21 -24
  54. package/dist/builtin/workflows/src/extension/workflow-resume-picker-rows.ts +38 -26
  55. package/dist/builtin/workflows/src/extension/workflow-resume-shadow.ts +2 -1
  56. package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +56 -64
  57. package/dist/builtin/workflows/src/extension/workflow-schema.ts +2 -2
  58. package/dist/builtin/workflows/src/extension/workflow-status-summary.ts +0 -5
  59. package/dist/builtin/workflows/src/extension/workflow-targets.ts +17 -20
  60. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -1
  61. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +24 -51
  62. package/dist/builtin/workflows/src/extension/workflow-tool-inspection.ts +7 -29
  63. package/dist/builtin/workflows/src/extension/workflow-tool-send.ts +5 -13
  64. package/dist/builtin/workflows/src/extension/workflow-tool.ts +4 -13
  65. package/dist/builtin/workflows/src/runs/background/quit.ts +4 -3
  66. package/dist/builtin/workflows/src/runs/background/run-inspect.ts +8 -8
  67. package/dist/builtin/workflows/src/runs/background/status.ts +2 -1
  68. package/dist/builtin/workflows/src/runs/background/workflow-lifecycle-aggregate.ts +2 -1
  69. package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +5 -5
  70. package/dist/builtin/workflows/src/runs/foreground/executor-lifecycle.ts +4 -0
  71. package/dist/builtin/workflows/src/runs/foreground/executor-scheduler.ts +2 -0
  72. package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +23 -8
  73. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +6 -2
  74. package/dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts +5 -0
  75. package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +56 -10
  76. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +6 -0
  77. package/dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts +137 -6
  78. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +2 -0
  79. package/dist/builtin/workflows/src/shared/authoring-contract-ui.ts +2 -0
  80. package/dist/builtin/workflows/src/shared/expanded-workflow-graph.ts +159 -10
  81. package/dist/builtin/workflows/src/shared/flat-string.ts +33 -0
  82. package/dist/builtin/workflows/src/shared/graph-store-snapshot.ts +144 -0
  83. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +2 -3
  84. package/dist/builtin/workflows/src/shared/run-id.ts +36 -0
  85. package/dist/builtin/workflows/src/shared/store-internal.ts +32 -3
  86. package/dist/builtin/workflows/src/shared/store-observation.ts +10 -0
  87. package/dist/builtin/workflows/src/shared/store-public-types.ts +8 -0
  88. package/dist/builtin/workflows/src/shared/store-run-methods.ts +14 -0
  89. package/dist/builtin/workflows/src/shared/store-types.ts +4 -0
  90. package/dist/builtin/workflows/src/shared/types.ts +2 -0
  91. package/dist/builtin/workflows/src/shared/workflow-artifacts.ts +261 -0
  92. package/dist/builtin/workflows/src/tui/dispatch-confirm.ts +39 -23
  93. package/dist/builtin/workflows/src/tui/graph-canvas.ts +26 -9
  94. package/dist/builtin/workflows/src/tui/graph-view-constants.ts +3 -0
  95. package/dist/builtin/workflows/src/tui/graph-view-graph-render.ts +95 -98
  96. package/dist/builtin/workflows/src/tui/graph-view-render.ts +7 -20
  97. package/dist/builtin/workflows/src/tui/graph-view-state.ts +160 -13
  98. package/dist/builtin/workflows/src/tui/layout.ts +8 -2
  99. package/dist/builtin/workflows/src/tui/node-card.ts +57 -45
  100. package/dist/builtin/workflows/src/tui/overlay-adapter.ts +4 -2
  101. package/dist/builtin/workflows/src/tui/prompt-card-render.ts +291 -21
  102. package/dist/builtin/workflows/src/tui/prompt-card.ts +1 -1
  103. package/dist/builtin/workflows/src/tui/renderers.ts +0 -1
  104. package/dist/builtin/workflows/src/tui/run-detail.ts +52 -35
  105. package/dist/builtin/workflows/src/tui/run-identity-rows.ts +97 -0
  106. package/dist/builtin/workflows/src/tui/session-overlays.ts +24 -3
  107. package/dist/builtin/workflows/src/tui/session-picker.ts +94 -41
  108. package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +190 -26
  109. package/dist/builtin/workflows/src/tui/stage-chat-view-footer-status.ts +52 -18
  110. package/dist/builtin/workflows/src/tui/stage-chat-view-input.ts +9 -5
  111. package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +44 -4
  112. package/dist/builtin/workflows/src/tui/stage-chat-view-types.ts +3 -1
  113. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +3 -2
  114. package/dist/builtin/workflows/src/tui/status-list.ts +67 -45
  115. package/dist/builtin/workflows/src/tui/store-widget-installer.ts +7 -6
  116. package/dist/builtin/workflows/src/tui/widget.ts +49 -40
  117. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +15 -10
  118. package/dist/builtin/workflows/src/tui/workflow-resume-selector.ts +21 -8
  119. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  120. package/dist/core/agent-session-accessors.js +5 -0
  121. package/dist/core/agent-session-accessors.js.map +1 -1
  122. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  123. package/dist/core/agent-session-auto-compaction.js +5 -0
  124. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  125. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  126. package/dist/core/agent-session-compaction.js +3 -0
  127. package/dist/core/agent-session-compaction.js.map +1 -1
  128. package/dist/core/agent-session-events.d.ts.map +1 -1
  129. package/dist/core/agent-session-events.js +2 -1
  130. package/dist/core/agent-session-events.js.map +1 -1
  131. package/dist/core/agent-session-message-queue.d.ts +3 -7
  132. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  133. package/dist/core/agent-session-message-queue.js +27 -13
  134. package/dist/core/agent-session-message-queue.js.map +1 -1
  135. package/dist/core/agent-session-methods.d.ts +5 -3
  136. package/dist/core/agent-session-methods.d.ts.map +1 -1
  137. package/dist/core/agent-session-methods.js.map +1 -1
  138. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  139. package/dist/core/agent-session-persistent-custom-messages.js +6 -3
  140. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  141. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  142. package/dist/core/agent-session-post-tool-compaction.js +11 -2
  143. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  144. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  145. package/dist/core/agent-session-runtime.js +5 -3
  146. package/dist/core/agent-session-runtime.js.map +1 -1
  147. package/dist/core/agent-session-tree.d.ts.map +1 -1
  148. package/dist/core/agent-session-tree.js +4 -0
  149. package/dist/core/agent-session-tree.js.map +1 -1
  150. package/dist/core/agent-session-types.d.ts +4 -0
  151. package/dist/core/agent-session-types.d.ts.map +1 -1
  152. package/dist/core/agent-session-types.js.map +1 -1
  153. package/dist/core/agent-session.d.ts +2 -1
  154. package/dist/core/agent-session.d.ts.map +1 -1
  155. package/dist/core/agent-session.js +1 -0
  156. package/dist/core/agent-session.js.map +1 -1
  157. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  158. package/dist/core/auth-storage-backends.js +12 -1
  159. package/dist/core/auth-storage-backends.js.map +1 -1
  160. package/dist/core/bounded-model-refresh.d.ts +14 -0
  161. package/dist/core/bounded-model-refresh.d.ts.map +1 -0
  162. package/dist/core/bounded-model-refresh.js +38 -0
  163. package/dist/core/bounded-model-refresh.js.map +1 -0
  164. package/dist/core/context-tool-pairing.d.ts +4 -4
  165. package/dist/core/context-tool-pairing.js +4 -4
  166. package/dist/core/context-tool-pairing.js.map +1 -1
  167. package/dist/core/http-dispatcher.d.ts.map +1 -1
  168. package/dist/core/http-dispatcher.js +26 -1
  169. package/dist/core/http-dispatcher.js.map +1 -1
  170. package/dist/core/messages.d.ts +18 -6
  171. package/dist/core/messages.d.ts.map +1 -1
  172. package/dist/core/messages.js +46 -18
  173. package/dist/core/messages.js.map +1 -1
  174. package/dist/core/model-refresh-timeout.d.ts +9 -0
  175. package/dist/core/model-refresh-timeout.d.ts.map +1 -0
  176. package/dist/core/model-refresh-timeout.js +9 -0
  177. package/dist/core/model-refresh-timeout.js.map +1 -0
  178. package/dist/core/model-runtime-snapshot.d.ts +3 -0
  179. package/dist/core/model-runtime-snapshot.d.ts.map +1 -1
  180. package/dist/core/model-runtime-snapshot.js +59 -0
  181. package/dist/core/model-runtime-snapshot.js.map +1 -1
  182. package/dist/core/model-runtime.d.ts +7 -1
  183. package/dist/core/model-runtime.d.ts.map +1 -1
  184. package/dist/core/model-runtime.js +72 -17
  185. package/dist/core/model-runtime.js.map +1 -1
  186. package/dist/core/sdk.d.ts.map +1 -1
  187. package/dist/core/sdk.js +4 -3
  188. package/dist/core/sdk.js.map +1 -1
  189. package/dist/core/session-manager-core.d.ts +1 -1
  190. package/dist/core/session-manager-core.d.ts.map +1 -1
  191. package/dist/core/session-manager-core.js +2 -2
  192. package/dist/core/session-manager-core.js.map +1 -1
  193. package/dist/core/session-manager-entries.d.ts +1 -1
  194. package/dist/core/session-manager-entries.d.ts.map +1 -1
  195. package/dist/core/session-manager-entries.js +2 -1
  196. package/dist/core/session-manager-entries.js.map +1 -1
  197. package/dist/core/session-manager-history.d.ts.map +1 -1
  198. package/dist/core/session-manager-history.js +2 -2
  199. package/dist/core/session-manager-history.js.map +1 -1
  200. package/dist/core/session-manager-types.d.ts +3 -0
  201. package/dist/core/session-manager-types.d.ts.map +1 -1
  202. package/dist/core/session-manager-types.js.map +1 -1
  203. package/dist/index.d.ts +1 -1
  204. package/dist/index.d.ts.map +1 -1
  205. package/dist/index.js.map +1 -1
  206. package/dist/main-app-mode.d.ts +1 -0
  207. package/dist/main-app-mode.d.ts.map +1 -1
  208. package/dist/main-app-mode.js +3 -0
  209. package/dist/main-app-mode.js.map +1 -1
  210. package/dist/main.d.ts.map +1 -1
  211. package/dist/main.js +8 -3
  212. package/dist/main.js.map +1 -1
  213. package/dist/modes/interactive/components/chat-session-host-actions.d.ts +7 -2
  214. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  215. package/dist/modes/interactive/components/chat-session-host-actions.js +13 -4
  216. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  217. package/dist/modes/interactive/components/chat-session-host-editor.d.ts +3 -1
  218. package/dist/modes/interactive/components/chat-session-host-editor.d.ts.map +1 -1
  219. package/dist/modes/interactive/components/chat-session-host-editor.js +2 -2
  220. package/dist/modes/interactive/components/chat-session-host-editor.js.map +1 -1
  221. package/dist/modes/interactive/components/chat-session-host-events.d.ts +3 -0
  222. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  223. package/dist/modes/interactive/components/chat-session-host-events.js +5 -4
  224. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  225. package/dist/modes/interactive/components/chat-session-host.d.ts +16 -2
  226. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  227. package/dist/modes/interactive/components/chat-session-host.js +35 -5
  228. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  229. package/dist/modes/interactive/components/index.d.ts +1 -0
  230. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  231. package/dist/modes/interactive/components/index.js.map +1 -1
  232. package/dist/modes/interactive/components/model-selector.d.ts +0 -1
  233. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  234. package/dist/modes/interactive/components/model-selector.js +25 -35
  235. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  236. package/dist/modes/interactive/interactive-editor-actions.js +2 -1
  237. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  238. package/dist/modes/interactive/interactive-input-handling.js +1 -1
  239. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  240. package/dist/modes/interactive/interactive-mode-surface.d.ts +4 -1
  241. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  242. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  243. package/dist/modes/interactive/interactive-model-routing.js +4 -1
  244. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  245. package/dist/modes/interactive/interactive-pause.d.ts +3 -1
  246. package/dist/modes/interactive/interactive-pause.d.ts.map +1 -1
  247. package/dist/modes/interactive/interactive-pause.js +5 -1
  248. package/dist/modes/interactive/interactive-pause.js.map +1 -1
  249. package/dist/modes/interactive/interactive-queueing.js +3 -3
  250. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  251. package/dist/modes/interactive-engine/engine-health.d.ts +6 -0
  252. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  253. package/dist/modes/interactive-engine/engine-health.js +15 -1
  254. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  255. package/dist/modes/interactive-engine/isolated-auth.js +1 -1
  256. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
  257. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -0
  258. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  259. package/dist/modes/interactive-engine/isolated-runtime.js +7 -1
  260. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  261. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -1
  262. package/dist/modes/interactive-engine/remote-model-catalog.js +5 -1
  263. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  264. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  265. package/dist/modes/rpc/rpc-command-handler.js +23 -7
  266. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  267. package/dist/modes/rpc/rpc-input-scheduler.js +1 -1
  268. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  269. package/dist/modes/rpc/rpc-types.d.ts +2 -1
  270. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  271. package/dist/modes/rpc/rpc-types.js.map +1 -1
  272. package/docs/custom-provider.md +3 -3
  273. package/docs/extensions.md +3 -1
  274. package/docs/index.md +10 -0
  275. package/docs/keybindings.md +1 -1
  276. package/docs/models.md +2 -0
  277. package/docs/providers.md +7 -3
  278. package/docs/quickstart.md +7 -1
  279. package/docs/session-format.md +2 -0
  280. package/docs/termux.md +3 -1
  281. package/docs/usage.md +3 -2
  282. package/docs/workflows.md +82 -46
  283. package/npm-shrinkwrap.json +59 -27
  284. package/package.json +3 -3
  285. package/dist/builtin/workflows/src/tui/toast.ts +0 -107
@@ -1,8 +1,10 @@
1
1
  import type { SessionInfo } from "@bastani/atomic";
2
+ import { isWorkflowRunResumable } from "../durable/resume-eligibility.js";
2
3
  import type { DurableWorkflowDeleteOutcome } from "../durable/retention-policy.js";
3
4
  import type { ResumableWorkflowEntry } from "../durable/types.js";
4
5
  import type { PiHostSessionPickerFunction, PiHostSessionPickerRow } from "../extension/wiring.js";
5
6
  import type { RunSnapshot, StageSnapshot } from "../shared/store-types.js";
7
+ import { workflowRunResumeCandidate } from "../shared/workflow-artifacts.js";
6
8
 
7
9
  export type WorkflowResumeSelectorResult =
8
10
  | { kind: "live"; runId: string }
@@ -55,6 +57,9 @@ function completedStageCount(run: RunSnapshot): number {
55
57
  return run.stages.filter((stage) => stage.status === "completed" || stage.status === "failed").length;
56
58
  }
57
59
 
60
+ function isResumePickerLiveRun(run: RunSnapshot): boolean {
61
+ return isWorkflowRunResumable(workflowRunResumeCandidate(run));
62
+ }
58
63
  interface WorkflowStatusPresentation {
59
64
  readonly label: string;
60
65
  readonly color?: "success" | "warning" | "error";
@@ -132,19 +137,27 @@ export function workflowResumeSelectorItems(
132
137
  durableEntries: readonly ResumableWorkflowEntry[],
133
138
  completedEntries: readonly ResumableWorkflowEntry[] = [],
134
139
  ): WorkflowResumeSelectorItem[] {
135
- const liveIds = new Set(liveRuns.map((run) => run.id));
136
- const durableIds = new Set(durableEntries.map((entry) => entry.workflowId));
140
+ const classifiedLiveRuns = liveRuns.map((run) => ({ run, resumable: isResumePickerLiveRun(run) }));
141
+ const eligibleLiveRuns = classifiedLiveRuns.filter(({ resumable }) => resumable).map(({ run }) => run);
142
+ const visibleLiveIds = new Set(eligibleLiveRuns.map((run) => run.id));
143
+ // An actively executing live snapshot is intentionally not resumable here, but its durable
144
+ // row remains the existing fallback. Other predicate-rejected snapshots must disappear from
145
+ // the resumable row kinds, or a missing-artifact live run would reappear as a durable duplicate.
146
+ const suppressedLiveIds = new Set(
147
+ classifiedLiveRuns
148
+ .filter(({ run, resumable }) => resumable || !(run.status === "running" && run.endedAt === undefined))
149
+ .map(({ run }) => run.id),
150
+ );
151
+ const visibleDurableEntries = durableEntries.filter((entry) => !suppressedLiveIds.has(entry.workflowId));
152
+ const durableIds = new Set(visibleDurableEntries.map((entry) => entry.workflowId));
137
153
  return [
138
- ...liveRuns.map(liveRunSession),
139
- ...durableEntries
140
- .filter((entry) => !liveIds.has(entry.workflowId))
141
- .map((entry) => durableWorkflowSession(entry, "durable")),
154
+ ...eligibleLiveRuns.map(liveRunSession),
155
+ ...visibleDurableEntries.map((entry) => durableWorkflowSession(entry, "durable")),
142
156
  ...completedEntries
143
- .filter((entry) => !liveIds.has(entry.workflowId) && !durableIds.has(entry.workflowId))
157
+ .filter((entry) => !visibleLiveIds.has(entry.workflowId) && !durableIds.has(entry.workflowId))
144
158
  .map((entry) => durableWorkflowSession(entry, "completed")),
145
159
  ].sort(compareResumeItemsByRecency);
146
160
  }
147
-
148
161
  export interface WorkflowResumeCatalogRows {
149
162
  readonly durable: readonly ResumableWorkflowEntry[];
150
163
  readonly completed: readonly ResumableWorkflowEntry[];
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-accessors.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-accessors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,YAAY,GAAG,IAAI,CAyI1E"}
1
+ {"version":3,"file":"agent-session-accessors.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-accessors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,YAAY,GAAG,IAAI,CA8I1E"}
@@ -47,6 +47,11 @@ export function installAgentSessionAccessors(prototype) {
47
47
  this._branchSummaryAbortController !== undefined);
48
48
  },
49
49
  },
50
+ compactionReason: {
51
+ get() {
52
+ return this._compactionReason;
53
+ },
54
+ },
50
55
  messages: {
51
56
  get() {
52
57
  return this.agent.state.messages;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-accessors.js","source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C,CAAC;SACD;QACD,aAAa,EAAE;YACd,GAAG;gBACF,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,GAAG,CAAC,CAAC;YAC5C,CAAC;SACD;QACD,sBAAsB,EAAE;YACvB,GAAG;gBACF,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC;YAC7C,CAAC;SACD;QACD,eAAe,EAAE;YAChB,GAAG;gBACF,OAAO,IAAI,CAAC,gBAAgB,CAAC;YAC9B,CAAC;SACD;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport function installAgentSessionAccessors(prototype: AgentSession): void {\n\tObject.defineProperties(prototype, {\n\t\torchestrationContext: {\n\t\t\tget() {\n\t\t\t\treturn this._orchestrationContext;\n\t\t\t},\n\t\t},\n\t\tmodelRuntime: {\n\t\t\tget() {\n\t\t\t\treturn this._modelRuntime;\n\t\t\t},\n\t\t},\n\t\tstate: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state;\n\t\t\t},\n\t\t},\n\t\tmodel: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.model;\n\t\t\t},\n\t\t},\n\t\tthinkingLevel: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.thinkingLevel;\n\t\t\t},\n\t\t},\n\t\tisStreaming: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.isStreaming;\n\t\t\t},\n\t\t},\n\t\tsystemPrompt: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.systemPrompt;\n\t\t\t},\n\t\t},\n\t\tretryAttempt: {\n\t\t\tget() {\n\t\t\t\treturn this._retryAttempt;\n\t\t\t},\n\t\t},\n\t\tisCompacting: {\n\t\t\tget() {\n\t\t\t\treturn (\n\t\t\t\t\tthis._autoCompactionAbortController !== undefined ||\n\t\t\t\t\tthis._compactionAbortController !== undefined ||\n\t\t\t\t\tthis._branchSummaryAbortController !== undefined\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tmessages: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.messages;\n\t\t\t},\n\t\t},\n\t\tsteeringMode: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.steeringMode;\n\t\t\t},\n\t\t},\n\t\tfollowUpMode: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.followUpMode;\n\t\t\t},\n\t\t},\n\t\tsessionFile: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionFile();\n\t\t\t},\n\t\t},\n\t\tsessionId: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionId();\n\t\t\t},\n\t\t},\n\t\tsessionName: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionName();\n\t\t\t},\n\t\t},\n\t\tscopedModels: {\n\t\t\tget() {\n\t\t\t\treturn this._scopedModels;\n\t\t\t},\n\t\t},\n\t\tpromptTemplates: {\n\t\t\tget() {\n\t\t\t\treturn this._resourceLoader.getPrompts().prompts;\n\t\t\t},\n\t\t},\n\t\tpendingMessageCount: {\n\t\t\tget() {\n\t\t\t\treturn this._steeringMessages.length + this._followUpMessages.length;\n\t\t\t},\n\t\t},\n\t\tqueuedMessagesPaused: {\n\t\t\tget() {\n\t\t\t\treturn this._queuedMessagesPaused;\n\t\t\t},\n\t\t},\n\t\tresourceLoader: {\n\t\t\tget() {\n\t\t\t\treturn this._resourceLoader;\n\t\t\t},\n\t\t},\n\t\tautoCompactionEnabled: {\n\t\t\tget() {\n\t\t\t\treturn this.settingsManager.getCompactionEnabled();\n\t\t\t},\n\t\t},\n\t\tisRetrying: {\n\t\t\tget() {\n\t\t\t\treturn this._retryPromise !== undefined;\n\t\t\t},\n\t\t},\n\t\tautoRetryEnabled: {\n\t\t\tget() {\n\t\t\t\treturn this.settingsManager.getRetryEnabled();\n\t\t\t},\n\t\t},\n\t\tisBashRunning: {\n\t\t\tget() {\n\t\t\t\treturn this._bashAbortControllers.size > 0;\n\t\t\t},\n\t\t},\n\t\thasPendingBashMessages: {\n\t\t\tget() {\n\t\t\t\treturn this._pendingBashMessages.length > 0;\n\t\t\t},\n\t\t},\n\t\textensionRunner: {\n\t\t\tget() {\n\t\t\t\treturn this._extensionRunner;\n\t\t\t},\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-accessors.js","sourceRoot":"","sources":["../../src/core/agent-session-accessors.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,4BAA4B,CAAC,SAAuB;IACnE,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE;QAClC,oBAAoB,EAAE;YACrB,GAAG;gBACF,OAAO,IAAI,CAAC,qBAAqB,CAAC;YACnC,CAAC;SACD;QACD,YAAY,EAAE;YACb,GAAG;gBACF,OAAO,IAAI,CAAC,aAAa,CAAC;YAC3B,CAAC;SACD;QACD,KAAK,EAAE;YACN,GAAG;gBACF,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;YACzB,CAAC;SACD;QACD,KAAK,EAAE;YACN,GAAG;gBACF,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC;YAC/B,CAAC;SACD;QACD,aAAa,EAAE;YACd,GAAG;gBACF,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC;YACvC,CAAC;SACD;QACD,WAAW,EAAE;YACZ,GAAG;gBACF,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC;YACrC,CAAC;SACD;QACD,YAAY,EAAE;YACb,GAAG;gBACF,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC;YACtC,CAAC;SACD;QACD,YAAY,EAAE;YACb,GAAG;gBACF,OAAO,IAAI,CAAC,aAAa,CAAC;YAC3B,CAAC;SACD;QACD,YAAY,EAAE;YACb,GAAG;gBACF,OAAO,CACN,IAAI,CAAC,8BAA8B,KAAK,SAAS;oBACjD,IAAI,CAAC,0BAA0B,KAAK,SAAS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;YAC7B,CAAC;SACD;QACD,qBAAqB,EAAE;YACtB,GAAG;gBACF,OAAO,IAAI,CAAC,eAAe,CAAC,oBAAoB,EAAE,CAAC;YACpD,CAAC;SACD;QACD,UAAU,EAAE;YACX,GAAG;gBACF,OAAO,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC;YACzC,CAAC;SACD;QACD,gBAAgB,EAAE;YACjB,GAAG;gBACF,OAAO,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC;YAC/C,CAAC;SACD;QACD,aAAa,EAAE;YACd,GAAG;gBACF,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,GAAG,CAAC,CAAC;YAC5C,CAAC;SACD;QACD,sBAAsB,EAAE;YACvB,GAAG;gBACF,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC;YAC7C,CAAC;SACD;QACD,eAAe,EAAE;YAChB,GAAG;gBACF,OAAO,IAAI,CAAC,gBAAgB,CAAC;YAC9B,CAAC;SACD;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport function installAgentSessionAccessors(prototype: AgentSession): void {\n\tObject.defineProperties(prototype, {\n\t\torchestrationContext: {\n\t\t\tget() {\n\t\t\t\treturn this._orchestrationContext;\n\t\t\t},\n\t\t},\n\t\tmodelRuntime: {\n\t\t\tget() {\n\t\t\t\treturn this._modelRuntime;\n\t\t\t},\n\t\t},\n\t\tstate: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state;\n\t\t\t},\n\t\t},\n\t\tmodel: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.model;\n\t\t\t},\n\t\t},\n\t\tthinkingLevel: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.thinkingLevel;\n\t\t\t},\n\t\t},\n\t\tisStreaming: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.isStreaming;\n\t\t\t},\n\t\t},\n\t\tsystemPrompt: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.systemPrompt;\n\t\t\t},\n\t\t},\n\t\tretryAttempt: {\n\t\t\tget() {\n\t\t\t\treturn this._retryAttempt;\n\t\t\t},\n\t\t},\n\t\tisCompacting: {\n\t\t\tget() {\n\t\t\t\treturn (\n\t\t\t\t\tthis._autoCompactionAbortController !== undefined ||\n\t\t\t\t\tthis._compactionAbortController !== undefined ||\n\t\t\t\t\tthis._branchSummaryAbortController !== undefined\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tcompactionReason: {\n\t\t\tget() {\n\t\t\t\treturn this._compactionReason;\n\t\t\t},\n\t\t},\n\t\tmessages: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.state.messages;\n\t\t\t},\n\t\t},\n\t\tsteeringMode: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.steeringMode;\n\t\t\t},\n\t\t},\n\t\tfollowUpMode: {\n\t\t\tget() {\n\t\t\t\treturn this.agent.followUpMode;\n\t\t\t},\n\t\t},\n\t\tsessionFile: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionFile();\n\t\t\t},\n\t\t},\n\t\tsessionId: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionId();\n\t\t\t},\n\t\t},\n\t\tsessionName: {\n\t\t\tget() {\n\t\t\t\treturn this.sessionManager.getSessionName();\n\t\t\t},\n\t\t},\n\t\tscopedModels: {\n\t\t\tget() {\n\t\t\t\treturn this._scopedModels;\n\t\t\t},\n\t\t},\n\t\tpromptTemplates: {\n\t\t\tget() {\n\t\t\t\treturn this._resourceLoader.getPrompts().prompts;\n\t\t\t},\n\t\t},\n\t\tpendingMessageCount: {\n\t\t\tget() {\n\t\t\t\treturn this._steeringMessages.length + this._followUpMessages.length;\n\t\t\t},\n\t\t},\n\t\tqueuedMessagesPaused: {\n\t\t\tget() {\n\t\t\t\treturn this._queuedMessagesPaused;\n\t\t\t},\n\t\t},\n\t\tresourceLoader: {\n\t\t\tget() {\n\t\t\t\treturn this._resourceLoader;\n\t\t\t},\n\t\t},\n\t\tautoCompactionEnabled: {\n\t\t\tget() {\n\t\t\t\treturn this.settingsManager.getCompactionEnabled();\n\t\t\t},\n\t\t},\n\t\tisRetrying: {\n\t\t\tget() {\n\t\t\t\treturn this._retryPromise !== undefined;\n\t\t\t},\n\t\t},\n\t\tautoRetryEnabled: {\n\t\t\tget() {\n\t\t\t\treturn this.settingsManager.getRetryEnabled();\n\t\t\t},\n\t\t},\n\t\tisBashRunning: {\n\t\t\tget() {\n\t\t\t\treturn this._bashAbortControllers.size > 0;\n\t\t\t},\n\t\t},\n\t\thasPendingBashMessages: {\n\t\t\tget() {\n\t\t\t\treturn this._pendingBashMessages.length > 0;\n\t\t\t},\n\t\t},\n\t\textensionRunner: {\n\t\t\tget() {\n\t\t\t\treturn this._extensionRunner;\n\t\t\t},\n\t\t},\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAK9F;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAc/D,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,CAuIf;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAqDD,wBAAgB,8BAA8B,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ1F;AAED,wBAAgB,mCAAmC,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAE/F;AAED;;GAEG;AAEH,wBAAgB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQ3F;AAED;;;;;GAKG;AAEH,wBAAgB,4CAA4C,CAC3D,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,UAAU,GAAG,WAAW,EACjC,SAAS,EAAE,OAAO,GAChB,IAAI,CA4BN;AAED,wBAAsB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAI/F;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAED;;;;;;GAMG;AAEH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAMD,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,OAAO,CAAC,IAAI,CAAC,CAqFf;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC"}
1
+ {"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAK9F;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAc/D,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,CAuIf;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAqDD,wBAAgB,8BAA8B,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ1F;AAED,wBAAgB,mCAAmC,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAE/F;AAED;;GAEG;AAEH,wBAAgB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQ3F;AAED;;;;;GAKG;AAEH,wBAAgB,4CAA4C,CAC3D,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,UAAU,GAAG,WAAW,EACjC,SAAS,EAAE,OAAO,GAChB,IAAI,CA4BN;AAED,wBAAsB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAI/F;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAED;;;;;;GAMG;AAEH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAMD,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,OAAO,CAAC,IAAI,CAAC,CAwFf;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC"}
@@ -302,6 +302,7 @@ export async function _runAutoCompaction(reason, willRetry) {
302
302
  // `compact()` must already observe this controller and be rejected rather than
303
303
  // racing the run that was just announced.
304
304
  this._autoCompactionAbortController = new AbortController();
305
+ this._compactionReason = reason;
305
306
  try {
306
307
  this._emit({ type: "compaction_start", reason });
307
308
  }
@@ -309,6 +310,8 @@ export async function _runAutoCompaction(reason, willRetry) {
309
310
  // A throwing start listener still propagates, matching current behavior,
310
311
  // but must not leave ownership published with no owner running.
311
312
  this._autoCompactionAbortController = undefined;
313
+ if (this._compactionReason === reason)
314
+ this._compactionReason = undefined;
312
315
  throw error;
313
316
  }
314
317
  try {
@@ -378,6 +381,8 @@ export async function _runAutoCompaction(reason, willRetry) {
378
381
  }
379
382
  finally {
380
383
  this._autoCompactionAbortController = undefined;
384
+ if (this._compactionReason === reason)
385
+ this._compactionReason = undefined;
381
386
  }
382
387
  }
383
388
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAErC,gBAAkC,EAClC,gBAAgB,GAAG,IAAI;IAEvB,IAAI,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,+BAA+B,CAAC;QACxD,IAAI,CAAC,+BAA+B,GAAG,SAAS,CAAC;QACjD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM;YACN,OAAO,EAAE,IAAI;YACb,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;SACb,CAAC,CAAC;IACJ,CAAC;IACD,IACC,IAAI,CAAC,iCAAiC,KAAK,SAAS;QACpD,gBAAgB,CAAC,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C","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) return;\n\t\t\t\t\t}\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): Promise<void> {\n\t// Publish automatic ownership before notifying listeners. `_emit()` invokes\n\t// public listeners synchronously, so a `compaction_start` listener that calls\n\t// `compact()` must already observe this controller and be rejected rather than\n\t// racing the run that was just announced.\n\tthis._autoCompactionAbortController = new AbortController();\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\t// Overflow recovery is load-bearing: the turn cannot continue without it.\n\t\t\t// A threshold crossing has already passed its turn boundary, so failing is safe.\n\t\t\turgency: reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n\t\t\t// A real provider overflow already proved the context does not fit, so a\n\t\t\t// sub-minimum region may reach the fresh rung.\n\t\t\t...(reason === \"overflow\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
1
+ {"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6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AAC,mBAAmB,CAAC;QAClF,MAAM,OAAO,GACZ,YAAY,KAAK,sBAAsB,IAAI,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;QACpG,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM;YACN,MAAM,EAAE,SAAS;YACjB,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,kBAAkB,EAAE,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;YACvD,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACrD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QAChD,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;IAC3E,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) return;\n\t\t\t\t\t}\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): Promise<void> {\n\t// Publish automatic ownership before notifying listeners. `_emit()` invokes\n\t// public listeners synchronously, so a `compaction_start` listener that calls\n\t// `compact()` must already observe this controller and be rejected rather than\n\t// racing the run that was just announced.\n\tthis._autoCompactionAbortController = new AbortController();\n\tthis._compactionReason = reason;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\t// Overflow recovery is load-bearing: the turn cannot continue without it.\n\t\t\t// A threshold crossing has already passed its turn boundary, so failing is safe.\n\t\t\turgency: reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n\t\t\t// A real provider overflow already proved the context does not fit, so a\n\t\t\t// sub-minimum region may reach the fresh rung.\n\t\t\t...(reason === \"overflow\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAWN,KAAK,4BAA4B,EAEjC,KAAK,wBAAwB,EAE7B,MAAM,uBAAuB,CAAC;AAkD/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAyJ/C;AAED,sFAAsF;AACtF,eAAO,MAAM,wCAAwC,mGAC4C,CAAC;AA2ClG;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CACtB,IAAI,EAAE,YAAY,EAClB,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,GACjD,OAAO,CAAC,wBAAwB,CAAC,CAsBnC;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAGxD;AACD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAE3D;AACD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnF;AAED,eAAO,MAAM,6BAA6B;;;;;;CAMzC,CAAC"}
1
+ {"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAWN,KAAK,4BAA4B,EAEjC,KAAK,wBAAwB,EAE7B,MAAM,uBAAuB,CAAC;AAkD/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAyJ/C;AAED,sFAAsF;AACtF,eAAO,MAAM,wCAAwC,mGAC4C,CAAC;AA2ClG;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CACtB,IAAI,EAAE,YAAY,EAClB,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,GACjD,OAAO,CAAC,wBAAwB,CAAC,CAwBnC;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAGxD;AACD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAE3D;AACD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnF;AAED,eAAO,MAAM,6BAA6B;;;;;;CAMzC,CAAC"}
@@ -240,6 +240,7 @@ export function compact(options = {}) {
240
240
  const controller = new AbortController();
241
241
  this._disconnectFromAgent();
242
242
  this._compactionAbortController = controller;
243
+ this._compactionReason = "manual";
243
244
  let flight;
244
245
  // Start the owned run in a microtask so both single-flight fields are
245
246
  // published before any joiner can observe a partially claimed compaction.
@@ -248,6 +249,8 @@ export function compact(options = {}) {
248
249
  .finally(() => {
249
250
  if (this._compactionAbortController === controller) {
250
251
  this._compactionAbortController = undefined;
252
+ if (this._compactionReason === "manual")
253
+ this._compactionReason = undefined;
251
254
  this._reconnectToAgent();
252
255
  }
253
256
  if (this._manualCompactionPromise === flight)
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,GAM5B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,SAAS,wBAAwB;IAChC,MAAM,IAAI,SAAS,CAAC,6CAA6C,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,UAAU,CAAI,KAAQ;IAC9B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAChF,IAAI,KAAK,YAAY,GAAG,EAAE,CAAC;QAC1B,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;YACnC,UAAU,CAAC,GAAG,CAAC,CAAC;YAChB,UAAU,CAAC,MAAM,CAAC,CAAC;QACpB,CAAC;QACD,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE;YAC9B,GAAG,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE;YACxC,MAAM,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE;YAC3C,KAAK,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE;SAC1C,CAAC,CAAC;IACJ,CAAC;SAAM,IAAI,KAAK,YAAY,GAAG,EAAE,CAAC;QACjC,KAAK,MAAM,MAAM,IAAI,KA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C,CAAC,CAAC;IACJ,IAAI,CAAC,wBAAwB,GAAG,MAAM,CAAC;IACvC,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,eAAe;IAC9B,IAAI,CAAC,0BAA0B,EAAE,KAAK,EAAE,CAAC;IACzC,IAAI,CAAC,8BAA8B,EAAE,KAAK,EAAE,CAAC;AAC9C,CAAC;AACD,MAAM,UAAU,kBAAkB;IACjC,IAAI,CAAC,6BAA6B,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type {\n\tAgentSessionInternalSurface as AgentSession,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport {\n\ttype CompactionPlannerModel,\n\ttype CompactionPlanOptions,\n\ttype CompactionRung,\n\ttype FallbackPlannerContext,\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n} from \"./compaction/index.ts\";\nimport type { SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionCompactEvent } from \"./extensions/index.ts\";\nimport type { CompactionEntry } from \"./session-manager.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nfunction frozenCollectionMutation(): never {\n\tthrow new TypeError(\"Cannot mutate frozen compaction preparation\");\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tif (value instanceof Map) {\n\t\tfor (const [key, nested] of value) {\n\t\t\tdeepFreeze(key);\n\t\t\tdeepFreeze(nested);\n\t\t}\n\t\tObject.defineProperties(value, {\n\t\t\tset: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else if (value instanceof Set) {\n\t\tfor (const nested of value) deepFreeze(nested);\n\t\tObject.defineProperties(value, {\n\t\t\tadd: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else {\n\t\tfor (const nested of Object.values(value)) deepFreeze(nested);\n\t}\n\treturn Object.freeze(value);\n}\n\nfunction extensionStats(preparation: VerbatimCompactionPreparation, compactedText: string): VerbatimCompactionStats {\n\tconst linesBefore = preparation.region.lines.length;\n\tconst linesKept = compactedText.split(\"\\n\").length;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4) + getKeptTailTokenEstimate(preparation);\n\treturn {\n\t\tlinesBefore,\n\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\tlinesKept,\n\t\trangeCount: 0,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\ttokensAfter,\n\t\tpercentReduction:\n\t\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10,\n\t};\n}\n\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\tconst model = this.model;\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings();\n\t// A sub-minimum region is admitted only when the caller already knows the\n\t// context does not fit: overflow recovery, or a post-tool preflight over the\n\t// provider hard input limit. A threshold crossing that still fits must not\n\t// clear context — its follow-up request can be sent as-is. `load_bearing`\n\t// alone does not mean \"must destroy context\".\n\tconst allowSmallRegion = options.urgency === \"load_bearing\" && options.allowSmallRegion === true;\n\tconst preparation = prepareCompactionBoundary(\n\t\tpathEntries,\n\t\tsettings,\n\t\t{\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t},\n\t\t{ allowSmallRegion },\n\t);\n\tif (!preparation) {\n\t\tif (options.reason === \"overflow\")\n\t\t\tthrow new Error(\n\t\t\t\t\"Context compaction found no compactable transcript entries; nothing more was safely deletable\",\n\t\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst plan: CompactionPlanOptions = {\n\t\tstreamFn: this.agent.streamFunction,\n\t\tsessionFilePath: this.sessionManager.getSessionFile(),\n\t\tretry: this.settingsManager.getRetrySettings(),\n\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"compaction\", reason: options.reason }),\n\t};\n\tlet fromExtension = false;\n\tlet compacted:\n\t\t| {\n\t\t\t\ttext: string;\n\t\t\t\tstats: VerbatimCompactionStats;\n\t\t\t\trung: CompactionRung;\n\t\t\t\tplannerModel?: CompactionPlannerModel;\n\t\t\t\tkeptTail: boolean;\n\t\t }\n\t\t| undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\tlet snapshot: VerbatimCompactionPreparation;\n\t\ttry {\n\t\t\tsnapshot = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tpreparation: snapshot,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\t\tif (hookResult?.cancel) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.compactedText !== undefined) {\n\t\t\tif (hookResult.compactedText.trim().length === 0) throw new Error(\"No compacted text provided by extension\");\n\t\t\tcompacted = {\n\t\t\t\ttext: hookResult.compactedText,\n\t\t\t\tstats: extensionStats(preparation, hookResult.compactedText),\n\t\t\t\trung: \"extension\",\n\t\t\t\tkeptTail: true,\n\t\t\t};\n\t\t\tfromExtension = true;\n\t\t}\n\t}\n\n\tif (!compacted) {\n\t\t// Borrowing walks the session's *effective* fallback list, which SDK\n\t\t// options may override, and resolves credentials per candidate. It never\n\t\t// touches session model state or the main chat's attempted-key set.\n\t\tconst fallback: FallbackPlannerContext = {\n\t\t\tfallbackModels: this._fallbackModels,\n\t\t\tregistry: this._modelRuntime,\n\t\t\tpreferredProvider: model.provider,\n\t\t\tsessionThinkingLevel: this.thinkingLevel,\n\t\t};\n\t\tconst run = await runVerbatimCompaction(preparation, model, {\n\t\t\t...plan,\n\t\t\tresolveAuth: options.resolvePlannerAuth,\n\t\t\tsignal: options.abortController.signal,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t});\n\t\tcompacted = {\n\t\t\ttext: run.text,\n\t\t\tstats: run.stats,\n\t\t\trung: run.rung,\n\t\t\t...(run.plannerModel ? { plannerModel: run.plannerModel } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t};\n\t}\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\t// A fresh rung that had to drop the protected tail persists no tail boundary.\n\tconst firstKeptEntryId = compacted.keptTail ? preparation.firstKeptEntryId : null;\n\tconst backupPath = this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: preparation.parameters,\n\t\tstats: compacted.stats,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst entryId = this.sessionManager.appendCompaction(\n\t\tcompacted.text,\n\t\tfirstKeptEntryId,\n\t\tpreparation.tokensBefore,\n\t\tdetails,\n\t);\n\tthis.agent.state.messages = this.sessionManager.buildSessionContext().messages;\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\tstats: compacted.stats,\n\t\tparameters: preparation.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst compactionEntry = this.sessionManager.getEntry(entryId) as CompactionEntry<VerbatimCompactionDetails>;\n\ttry {\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension,\n\t\t} satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<session_compact>\",\n\t\t\tevent: \"session_compact\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\n/** Message surfaced when a manual compaction is requested during an automatic one. */\nexport const AUTOMATIC_COMPACTION_IN_PROGRESS_MESSAGE =\n\t\"Automatic compaction is already in progress; wait for it to finish before compacting manually.\";\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: Partial<VerbatimCompactionParameters>,\n): Promise<VerbatimCompactionResult> {\n\tawait this.abort();\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\ttry {\n\t\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\t// Caller parameters are projected explicitly, so no extra runtime\n\t\t\t// property survives. A widened or cast object could otherwise carry\n\t\t\t// `urgency: \"load_bearing\"` through a public `session.compact()` call and\n\t\t\t// reach the context-destroying rung, which manual compaction must never do.\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t\tresolvePlannerAuth: (candidate) => this._getRequiredRequestAuth(candidate),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t});\n\t\tthrow error;\n\t}\n}\n\n/**\n * Persist one verbatim line-subset compaction boundary.\n *\n * Re-entrancy safe: a call made while a manual compaction is still in flight\n * joins that run instead of starting a second one, and a call made while an\n * automatic compaction owns `_autoCompactionAbortController` fails fast rather\n * than racing it. Only the owning call clears `_compactionAbortController` and\n * reconnects agent events, so `abortCompaction()` always reaches the live run.\n */\nexport function compact(\n\tthis: AgentSession,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n): Promise<VerbatimCompactionResult> {\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\tif (this._autoCompactionAbortController) return Promise.reject(new Error(AUTOMATIC_COMPACTION_IN_PROGRESS_MESSAGE));\n\n\tconst controller = new AbortController();\n\tthis._disconnectFromAgent();\n\tthis._compactionAbortController = controller;\n\tlet flight!: Promise<VerbatimCompactionResult>;\n\t// Start the owned run in a microtask so both single-flight fields are\n\t// published before any joiner can observe a partially claimed compaction.\n\tflight = Promise.resolve()\n\t\t.then(() => runOwnedManualCompaction.call(this, controller, options))\n\t\t.finally(() => {\n\t\t\tif (this._compactionAbortController === controller) {\n\t\t\t\tthis._compactionAbortController = undefined;\n\t\t\t\tthis._reconnectToAgent();\n\t\t\t}\n\t\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\t\t});\n\tthis._manualCompactionPromise = flight;\n\treturn flight;\n}\n\nexport function abortCompaction(this: AgentSession): void {\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setCompactionEnabled(enabled);\n}\n\nexport const agentSessionCompactionMethods = {\n\t_applyVerbatimCompaction,\n\tcompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
1
+ {"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,GAM5B,MAAM,uBAAuB,CAAC;AA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,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type {\n\tAgentSessionInternalSurface as AgentSession,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport {\n\ttype CompactionPlannerModel,\n\ttype CompactionPlanOptions,\n\ttype CompactionRung,\n\ttype FallbackPlannerContext,\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n} from \"./compaction/index.ts\";\nimport type { SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionCompactEvent } from \"./extensions/index.ts\";\nimport type { CompactionEntry } from \"./session-manager.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nfunction frozenCollectionMutation(): never {\n\tthrow new TypeError(\"Cannot mutate frozen compaction preparation\");\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tif (value instanceof Map) {\n\t\tfor (const [key, nested] of value) {\n\t\t\tdeepFreeze(key);\n\t\t\tdeepFreeze(nested);\n\t\t}\n\t\tObject.defineProperties(value, {\n\t\t\tset: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else if (value instanceof Set) {\n\t\tfor (const nested of value) deepFreeze(nested);\n\t\tObject.defineProperties(value, {\n\t\t\tadd: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else {\n\t\tfor (const nested of Object.values(value)) deepFreeze(nested);\n\t}\n\treturn Object.freeze(value);\n}\n\nfunction extensionStats(preparation: VerbatimCompactionPreparation, compactedText: string): VerbatimCompactionStats {\n\tconst linesBefore = preparation.region.lines.length;\n\tconst linesKept = compactedText.split(\"\\n\").length;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4) + getKeptTailTokenEstimate(preparation);\n\treturn {\n\t\tlinesBefore,\n\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\tlinesKept,\n\t\trangeCount: 0,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\ttokensAfter,\n\t\tpercentReduction:\n\t\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10,\n\t};\n}\n\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\tconst model = this.model;\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings();\n\t// A sub-minimum region is admitted only when the caller already knows the\n\t// context does not fit: overflow recovery, or a post-tool preflight over the\n\t// provider hard input limit. A threshold crossing that still fits must not\n\t// clear context — its follow-up request can be sent as-is. `load_bearing`\n\t// alone does not mean \"must destroy context\".\n\tconst allowSmallRegion = options.urgency === \"load_bearing\" && options.allowSmallRegion === true;\n\tconst preparation = prepareCompactionBoundary(\n\t\tpathEntries,\n\t\tsettings,\n\t\t{\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t},\n\t\t{ allowSmallRegion },\n\t);\n\tif (!preparation) {\n\t\tif (options.reason === \"overflow\")\n\t\t\tthrow new Error(\n\t\t\t\t\"Context compaction found no compactable transcript entries; nothing more was safely deletable\",\n\t\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst plan: CompactionPlanOptions = {\n\t\tstreamFn: this.agent.streamFunction,\n\t\tsessionFilePath: this.sessionManager.getSessionFile(),\n\t\tretry: this.settingsManager.getRetrySettings(),\n\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"compaction\", reason: options.reason }),\n\t};\n\tlet fromExtension = false;\n\tlet compacted:\n\t\t| {\n\t\t\t\ttext: string;\n\t\t\t\tstats: VerbatimCompactionStats;\n\t\t\t\trung: CompactionRung;\n\t\t\t\tplannerModel?: CompactionPlannerModel;\n\t\t\t\tkeptTail: boolean;\n\t\t }\n\t\t| undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\tlet snapshot: VerbatimCompactionPreparation;\n\t\ttry {\n\t\t\tsnapshot = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tpreparation: snapshot,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\t\tif (hookResult?.cancel) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.compactedText !== undefined) {\n\t\t\tif (hookResult.compactedText.trim().length === 0) throw new Error(\"No compacted text provided by extension\");\n\t\t\tcompacted = {\n\t\t\t\ttext: hookResult.compactedText,\n\t\t\t\tstats: extensionStats(preparation, hookResult.compactedText),\n\t\t\t\trung: \"extension\",\n\t\t\t\tkeptTail: true,\n\t\t\t};\n\t\t\tfromExtension = true;\n\t\t}\n\t}\n\n\tif (!compacted) {\n\t\t// Borrowing walks the session's *effective* fallback list, which SDK\n\t\t// options may override, and resolves credentials per candidate. It never\n\t\t// touches session model state or the main chat's attempted-key set.\n\t\tconst fallback: FallbackPlannerContext = {\n\t\t\tfallbackModels: this._fallbackModels,\n\t\t\tregistry: this._modelRuntime,\n\t\t\tpreferredProvider: model.provider,\n\t\t\tsessionThinkingLevel: this.thinkingLevel,\n\t\t};\n\t\tconst run = await runVerbatimCompaction(preparation, model, {\n\t\t\t...plan,\n\t\t\tresolveAuth: options.resolvePlannerAuth,\n\t\t\tsignal: options.abortController.signal,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t});\n\t\tcompacted = {\n\t\t\ttext: run.text,\n\t\t\tstats: run.stats,\n\t\t\trung: run.rung,\n\t\t\t...(run.plannerModel ? { plannerModel: run.plannerModel } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t};\n\t}\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\t// A fresh rung that had to drop the protected tail persists no tail boundary.\n\tconst firstKeptEntryId = compacted.keptTail ? preparation.firstKeptEntryId : null;\n\tconst backupPath = this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: preparation.parameters,\n\t\tstats: compacted.stats,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst entryId = this.sessionManager.appendCompaction(\n\t\tcompacted.text,\n\t\tfirstKeptEntryId,\n\t\tpreparation.tokensBefore,\n\t\tdetails,\n\t);\n\tthis.agent.state.messages = this.sessionManager.buildSessionContext().messages;\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\tstats: compacted.stats,\n\t\tparameters: preparation.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst compactionEntry = this.sessionManager.getEntry(entryId) as CompactionEntry<VerbatimCompactionDetails>;\n\ttry {\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension,\n\t\t} satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<session_compact>\",\n\t\t\tevent: \"session_compact\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\n/** Message surfaced when a manual compaction is requested during an automatic one. */\nexport const AUTOMATIC_COMPACTION_IN_PROGRESS_MESSAGE =\n\t\"Automatic compaction is already in progress; wait for it to finish before compacting manually.\";\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: Partial<VerbatimCompactionParameters>,\n): Promise<VerbatimCompactionResult> {\n\tawait this.abort();\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\ttry {\n\t\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\t// Caller parameters are projected explicitly, so no extra runtime\n\t\t\t// property survives. A widened or cast object could otherwise carry\n\t\t\t// `urgency: \"load_bearing\"` through a public `session.compact()` call and\n\t\t\t// reach the context-destroying rung, which manual compaction must never do.\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t\tresolvePlannerAuth: (candidate) => this._getRequiredRequestAuth(candidate),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t});\n\t\tthrow error;\n\t}\n}\n\n/**\n * Persist one verbatim line-subset compaction boundary.\n *\n * Re-entrancy safe: a call made while a manual compaction is still in flight\n * joins that run instead of starting a second one, and a call made while an\n * automatic compaction owns `_autoCompactionAbortController` fails fast rather\n * than racing it. Only the owning call clears `_compactionAbortController` and\n * reconnects agent events, so `abortCompaction()` always reaches the live run.\n */\nexport function compact(\n\tthis: AgentSession,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n): Promise<VerbatimCompactionResult> {\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\tif (this._autoCompactionAbortController) return Promise.reject(new Error(AUTOMATIC_COMPACTION_IN_PROGRESS_MESSAGE));\n\n\tconst controller = new AbortController();\n\tthis._disconnectFromAgent();\n\tthis._compactionAbortController = controller;\n\tthis._compactionReason = \"manual\";\n\tlet flight!: Promise<VerbatimCompactionResult>;\n\t// Start the owned run in a microtask so both single-flight fields are\n\t// published before any joiner can observe a partially claimed compaction.\n\tflight = Promise.resolve()\n\t\t.then(() => runOwnedManualCompaction.call(this, controller, options))\n\t\t.finally(() => {\n\t\t\tif (this._compactionAbortController === controller) {\n\t\t\t\tthis._compactionAbortController = undefined;\n\t\t\t\tif (this._compactionReason === \"manual\") this._compactionReason = undefined;\n\t\t\t\tthis._reconnectToAgent();\n\t\t\t}\n\t\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\t\t});\n\tthis._manualCompactionPromise = flight;\n\treturn flight;\n}\n\nexport function abortCompaction(this: AgentSession): void {\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setCompactionEnabled(enabled);\n}\n\nexport const agentSessionCompactionMethods = {\n\t_applyVerbatimCompaction,\n\tcompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-events.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAe,MAAM,8BAA8B,CAAC;AAE3F,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAS9F,OAAO,EACN,KAAK,iBAAiB,EACtB,KAAK,yBAAyB,EAI9B,MAAM,0BAA0B,CAAC;AAelC,wBAAgB,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAIxE;AAED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;;;;;;;;;;;;;CAkBrC,CAAC"}
@@ -121,8 +121,9 @@ export async function _processAgentEvent(event) {
121
121
  if (event.type === "message_end") {
122
122
  // Check if this is a custom message from extensions
123
123
  if (event.message.role === "custom") {
124
+ const admitted = event.message;
124
125
  if (protectedMessage === undefined) {
125
- this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details, customMessageExcludesContext(event.message));
126
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details, customMessageExcludesContext(event.message), undefined, admitted.stageAdmissionKey);
126
127
  }
127
128
  }
128
129
  else if (event.message.role === "user" ||