@bastani/atomic 0.9.73-alpha.1 → 0.9.74-alpha.1

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 (194) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  8. package/dist/builtin/workflows/README.md +2 -2
  9. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  10. package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
  13. package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
  14. package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
  15. package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
  18. package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
  19. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  20. package/dist/builtin/workflows/builtin/goal.js +4 -4
  21. package/dist/builtin/workflows/builtin/index.js +9 -9
  22. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  23. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  24. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  25. package/dist/builtin/workflows/package.json +1 -1
  26. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  27. package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
  28. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
  29. package/dist/builtin/workflows/src/index.js +393 -62
  30. package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
  31. package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
  32. package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
  33. package/dist/config.d.ts +2 -0
  34. package/dist/config.d.ts.map +1 -1
  35. package/dist/config.js +4 -0
  36. package/dist/config.js.map +1 -1
  37. package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
  38. package/dist/core/agent-session-background-compaction.js +2 -1
  39. package/dist/core/agent-session-background-compaction.js.map +1 -1
  40. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  41. package/dist/core/agent-session-compaction.js +98 -4
  42. package/dist/core/agent-session-compaction.js.map +1 -1
  43. package/dist/core/agent-session-detached-tools.d.ts +20 -5
  44. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  45. package/dist/core/agent-session-detached-tools.js +97 -21
  46. package/dist/core/agent-session-detached-tools.js.map +1 -1
  47. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  48. package/dist/core/agent-session-message-queue.js +2 -1
  49. package/dist/core/agent-session-message-queue.js.map +1 -1
  50. package/dist/core/agent-session-methods.d.ts +3 -1
  51. package/dist/core/agent-session-methods.d.ts.map +1 -1
  52. package/dist/core/agent-session-methods.js.map +1 -1
  53. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  54. package/dist/core/agent-session-persistent-custom-messages.js +12 -4
  55. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  56. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  57. package/dist/core/agent-session-prompt.js +33 -0
  58. package/dist/core/agent-session-prompt.js.map +1 -1
  59. package/dist/core/compaction/background-compaction.d.ts +11 -5
  60. package/dist/core/compaction/background-compaction.d.ts.map +1 -1
  61. package/dist/core/compaction/background-compaction.js +19 -10
  62. package/dist/core/compaction/background-compaction.js.map +1 -1
  63. package/dist/core/compaction/compaction-boundary.d.ts +10 -0
  64. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  65. package/dist/core/compaction/compaction-boundary.js +30 -2
  66. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  67. package/dist/core/compaction/compaction-runner.d.ts +7 -0
  68. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  69. package/dist/core/compaction/compaction-runner.js +13 -5
  70. package/dist/core/compaction/compaction-runner.js.map +1 -1
  71. package/dist/core/compaction/compaction-types.d.ts +1 -1
  72. package/dist/core/compaction/compaction-types.js +1 -1
  73. package/dist/core/compaction/compaction-types.js.map +1 -1
  74. package/dist/core/compaction/deleted-ranges.d.ts +17 -2
  75. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  76. package/dist/core/compaction/deleted-ranges.js +44 -5
  77. package/dist/core/compaction/deleted-ranges.js.map +1 -1
  78. package/dist/core/compaction/history-recall.d.ts +32 -0
  79. package/dist/core/compaction/history-recall.d.ts.map +1 -0
  80. package/dist/core/compaction/history-recall.js +275 -0
  81. package/dist/core/compaction/history-recall.js.map +1 -0
  82. package/dist/core/compaction/index.d.ts +2 -0
  83. package/dist/core/compaction/index.d.ts.map +1 -1
  84. package/dist/core/compaction/index.js +2 -0
  85. package/dist/core/compaction/index.js.map +1 -1
  86. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  87. package/dist/core/compaction/pi-summary-fallback.js +1 -0
  88. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  89. package/dist/core/compaction/planner-outcome.d.ts +14 -0
  90. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  91. package/dist/core/compaction/planner-outcome.js +8 -0
  92. package/dist/core/compaction/planner-outcome.js.map +1 -1
  93. package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
  94. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  95. package/dist/core/compaction/range-planner-diagnostics.js +67 -24
  96. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  97. package/dist/core/compaction/range-planner.d.ts +7 -4
  98. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  99. package/dist/core/compaction/range-planner.js +43 -19
  100. package/dist/core/compaction/range-planner.js.map +1 -1
  101. package/dist/core/compaction/refusal-recovery.d.ts +27 -0
  102. package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
  103. package/dist/core/compaction/refusal-recovery.js +65 -0
  104. package/dist/core/compaction/refusal-recovery.js.map +1 -0
  105. package/dist/core/compaction/region-trimming.d.ts +23 -0
  106. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  107. package/dist/core/compaction/region-trimming.js +59 -15
  108. package/dist/core/compaction/region-trimming.js.map +1 -1
  109. package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
  110. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
  111. package/dist/core/compaction/structured-compaction-input.js +30 -17
  112. package/dist/core/compaction/structured-compaction-input.js.map +1 -1
  113. package/dist/core/compaction/transcript-serialization.d.ts +9 -3
  114. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  115. package/dist/core/compaction/transcript-serialization.js +18 -10
  116. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  117. package/dist/core/messages.d.ts +5 -1
  118. package/dist/core/messages.d.ts.map +1 -1
  119. package/dist/core/messages.js +21 -3
  120. package/dist/core/messages.js.map +1 -1
  121. package/dist/core/session-manager-core.js +1 -1
  122. package/dist/core/session-manager-core.js.map +1 -1
  123. package/dist/core/session-manager-history.d.ts +1 -1
  124. package/dist/core/session-manager-history.d.ts.map +1 -1
  125. package/dist/core/session-manager-history.js +2 -5
  126. package/dist/core/session-manager-history.js.map +1 -1
  127. package/dist/core/settings-defaults.d.ts +2 -0
  128. package/dist/core/settings-defaults.d.ts.map +1 -1
  129. package/dist/core/settings-defaults.js +2 -0
  130. package/dist/core/settings-defaults.js.map +1 -1
  131. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  132. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  133. package/dist/core/settings-manager-basic-accessors.js +3 -0
  134. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  135. package/dist/core/settings-schema.d.ts +2 -0
  136. package/dist/core/settings-schema.d.ts.map +1 -1
  137. package/dist/core/settings-schema.js +4 -0
  138. package/dist/core/settings-schema.js.map +1 -1
  139. package/dist/core/storage/session/conformance.d.ts.map +1 -1
  140. package/dist/core/storage/session/conformance.js +12 -0
  141. package/dist/core/storage/session/conformance.js.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  143. package/dist/core/storage/session/jsonl-session-store.js +3 -0
  144. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  145. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  146. package/dist/core/storage/session/legacy-session-store.js +3 -0
  147. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  148. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  149. package/dist/core/storage/session/memory-session-store.js +3 -0
  150. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  151. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  152. package/dist/core/storage/session/sql-session-store.js +12 -3
  153. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  154. package/dist/core/storage/session/types.d.ts +3 -0
  155. package/dist/core/storage/session/types.d.ts.map +1 -1
  156. package/dist/core/storage/session/types.js +3 -0
  157. package/dist/core/storage/session/types.js.map +1 -1
  158. package/dist/core/tools/history-protocol.d.ts +3 -0
  159. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  160. package/dist/core/tools/history-protocol.js +7 -87
  161. package/dist/core/tools/history-protocol.js.map +1 -1
  162. package/dist/core/tools/history-transcript.d.ts +24 -0
  163. package/dist/core/tools/history-transcript.d.ts.map +1 -0
  164. package/dist/core/tools/history-transcript.js +110 -0
  165. package/dist/core/tools/history-transcript.js.map +1 -0
  166. package/dist/index.d.ts +1 -1
  167. package/dist/index.d.ts.map +1 -1
  168. package/dist/index.js.map +1 -1
  169. package/dist/main-session.d.ts.map +1 -1
  170. package/dist/main-session.js +21 -5
  171. package/dist/main-session.js.map +1 -1
  172. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
  174. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  175. package/dist/modes/interactive/interactive-render-chat.js +2 -2
  176. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  177. package/dist/session-id-target.d.ts +1 -0
  178. package/dist/session-id-target.d.ts.map +1 -1
  179. package/dist/session-id-target.js +3 -0
  180. package/dist/session-id-target.js.map +1 -1
  181. package/docs/compaction/reference.md +3 -2
  182. package/docs/compaction.md +35 -7
  183. package/docs/development.md +1 -1
  184. package/docs/sdk/reference.md +6 -5
  185. package/docs/sessions.md +3 -3
  186. package/docs/settings.md +3 -0
  187. package/docs/storage.md +2 -0
  188. package/docs/workflows/api-reference.md +15 -3
  189. package/docs/workflows/authoring.md +2 -2
  190. package/docs/workflows/operations.md +1 -0
  191. package/docs/workflows/reliable-design.md +1 -1
  192. package/npm-shrinkwrap.json +32 -32
  193. package/package.json +3 -3
  194. package/schemas/settings.schema.json +5 -0
@@ -1,9 +1,23 @@
1
+ import { getCompactionDiagnosticsDir } from "../config.js";
2
+ import { awaitedToolTurnEntryId } from "./agent-session-detached-tools.js";
1
3
  import { authForStream } from "./agent-session-models.js";
2
4
  import { formatNoModelSelectedMessage } from "./auth-guidance.js";
3
- import { getKeptTailTokenEstimate, prepareCompactionBoundary, runVerbatimCompaction, VERBATIM_COMPACTION_PROMPT_VERSION, VERBATIM_COMPACTION_STRATEGY, widenToWholeContextStats, } from "./compaction/index.js";
5
+ import { findBackgroundCompactionSafePoint, findUnansweredToolCall } from "./compaction/background-compaction.js";
6
+ import { autoDetectCompactionQuery, getKeptTailTokenEstimate, prepareCompactionBoundary, recallHistory, runVerbatimCompaction, VERBATIM_COMPACTION_PROMPT_VERSION, VERBATIM_COMPACTION_STRATEGY, widenToWholeContextStats, withRecalledContext, } from "./compaction/index.js";
4
7
  import { resolveCompactionModel } from "./compaction/model-resolver.js";
5
8
  import { assertSessionOpen as assertCompactionOpen, trackSessionWork } from "./session-lifecycle-work.js";
6
9
  import { createSummarizationRetryCallbacks } from "./summarization-retry.js";
10
+ import { createHistoryRouter, transcriptEntryLines } from "./tools/history-protocol.js";
11
+ import { renderHistoryTranscript } from "./tools/history-transcript.js";
12
+ /** This session's own history layout, or undefined when it has no history a `read` could open. */
13
+ function historyLocation(session) {
14
+ const manager = session.sessionManager;
15
+ const header = manager.getHeader();
16
+ if (!header || !manager.isPersisted())
17
+ return undefined;
18
+ const { entryRanges } = renderHistoryTranscript(header, manager.getEntries(), true);
19
+ return { sessionId: manager.getSessionId(), entryRanges };
20
+ }
7
21
  function frozenCollectionMutation() {
8
22
  throw new TypeError("Cannot mutate frozen compaction preparation");
9
23
  }
@@ -56,6 +70,58 @@ function extensionStats(preparation, compactedText) {
56
70
  percentReduction: tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10,
57
71
  }, getKeptTailTokenEstimate(preparation), true);
58
72
  }
73
+ function entriesAfterRegion(branch, preparation) {
74
+ const lastRegionEntryId = preparation.regionEntryIds[preparation.regionEntryIds.length - 1];
75
+ if (lastRegionEntryId !== undefined) {
76
+ const index = branch.findIndex((entry) => entry.id === lastRegionEntryId);
77
+ return index < 0 ? [] : branch.slice(index + 1);
78
+ }
79
+ const keptIndex = branch.findIndex((entry) => entry.id === preparation.firstKeptEntryId);
80
+ return keptIndex < 0 ? [] : branch.slice(keptIndex);
81
+ }
82
+ /**
83
+ * The planned text with a `Recalled context` section from earlier history, or `undefined` to leave it as planned.
84
+ * Every failure, timeout and cancellation also leaves it as planned: recall is never a reason to fail or hold up
85
+ * compaction.
86
+ */
87
+ async function recallForPlannedText(session, preparation, pathEntries, planned, signal) {
88
+ try {
89
+ const router = createHistoryRouter({
90
+ cwd: session._cwd,
91
+ currentSessionId: session.sessionManager.getSessionId(),
92
+ sessionStore: () => session.sessionManager.getSessionStore(),
93
+ workflows: () => session._extensionRunner?.getWorkflowRunControl(),
94
+ });
95
+ const section = await recallHistory({
96
+ router,
97
+ sessionId: session.sessionManager.getSessionId(),
98
+ queries: [autoDetectCompactionQuery(pathEntries), preparation.parameters.query],
99
+ keptLines: [
100
+ ...planned.text.split("\n"),
101
+ ...transcriptEntryLines(entriesAfterRegion(session.sessionManager.getBranch(), preparation)),
102
+ ],
103
+ keptTokens: planned.stats.tokensAfter,
104
+ signal,
105
+ });
106
+ if (section === undefined)
107
+ return undefined;
108
+ const text = withRecalledContext(planned.text, section);
109
+ const tokensAfter = planned.stats.tokensAfter + Math.ceil((text.length - planned.text.length) / 4);
110
+ return {
111
+ text,
112
+ stats: {
113
+ ...planned.stats,
114
+ tokensAfter,
115
+ percentReduction: planned.stats.tokensBefore === 0
116
+ ? 0
117
+ : Math.round((1 - tokensAfter / planned.stats.tokensBefore) * 1000) / 10,
118
+ },
119
+ };
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
59
125
  /**
60
126
  * Plan one verbatim compaction of `pathEntries` without changing the session: the extension hook,
61
127
  * then the planner ladder. Returns undefined when nothing is compactable and the caller may proceed.
@@ -77,7 +143,7 @@ export async function planVerbatimCompaction(options, pathEntries) {
77
143
  ...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),
78
144
  ...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),
79
145
  ...(options.query === undefined ? {} : { query: options.query }),
80
- }, { allowSmallRegion });
146
+ }, { allowSmallRegion, history: historyLocation(this) });
81
147
  if (!preparation) {
82
148
  // Mid-turn threshold preflight needs the load-bearing planner fallback if
83
149
  // a region exists, but a context that still fits is safe to send unchanged.
@@ -91,6 +157,14 @@ export async function planVerbatimCompaction(options, pathEntries) {
91
157
  const plan = {
92
158
  streamFn: this.agent.streamFunction,
93
159
  sessionFilePath: this.sessionManager.getSessionFile(),
160
+ ...(this.sessionManager.isPersisted()
161
+ ? {
162
+ sidecarDirectory: {
163
+ directory: getCompactionDiagnosticsDir(),
164
+ stem: this.sessionManager.getSessionId(),
165
+ },
166
+ }
167
+ : {}),
94
168
  retry: this.settingsManager.getRetrySettings(),
95
169
  callbacks: createSummarizationRetryCallbacks(this, { source: "compaction", reason: options.reason }),
96
170
  };
@@ -179,6 +253,16 @@ export async function planVerbatimCompaction(options, pathEntries) {
179
253
  assertCompactionOpen(this);
180
254
  if (options.abortController.signal.aborted)
181
255
  throw new Error("Compaction cancelled");
256
+ if (compacted.rung === "planned" &&
257
+ compacted.backend !== "summary" &&
258
+ this.settingsManager.getCompactionHistoryRecall()) {
259
+ const recalled = await recallForPlannedText(this, preparation, pathEntries, compacted, options.abortController.signal);
260
+ assertCompactionOpen(this);
261
+ if (options.abortController.signal.aborted)
262
+ throw new Error("Compaction cancelled");
263
+ if (recalled)
264
+ compacted = { ...compacted, ...recalled };
265
+ }
182
266
  // A fresh rung that had to drop the protected tail persists no tail boundary.
183
267
  const firstKeptEntryId = compacted.summaryFirstKeptEntryId ?? (compacted.keptTail ? preparation.firstKeptEntryId : null);
184
268
  return {
@@ -255,10 +339,20 @@ export async function finishVerbatimCommit(planned, appended, reason) {
255
339
  return result;
256
340
  }
257
341
  export async function _applyVerbatimCompaction(options) {
258
- const planned = await planVerbatimCompaction.call(this, options, this.sessionManager.getBranch());
342
+ const branch = this.sessionManager.getBranch();
343
+ // A boundary folds the entries it covers into text. A call that has no result yet must stay a tool call for the
344
+ // result it is waiting on (a detached call's, #4580), so the boundary covers only what precedes its turn, as a
345
+ // background compaction does.
346
+ const awaited = awaitedToolTurnEntryId(this);
347
+ const waiting = findUnansweredToolCall(branch, awaited) !== undefined;
348
+ const covered = waiting ? branch.slice(0, findBackgroundCompactionSafePoint(branch, awaited) + 1) : branch;
349
+ const planned = await planVerbatimCompaction.call(this, options, covered);
259
350
  if (!planned)
260
351
  return undefined;
261
- const appended = await appendVerbatimBoundary.call(this, planned, { backupLabel: options.backupLabel });
352
+ const appended = await appendVerbatimBoundary.call(this, planned, {
353
+ backupLabel: options.backupLabel,
354
+ ...(waiting ? { coveredThroughEntryId: covered[covered.length - 1].id } : {}),
355
+ });
262
356
  return finishVerbatimCommit.call(this, planned, appended, options.reason);
263
357
  }
264
358
  export async function emitSessionCompactFailed(session, event) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,EAK5B,wBAAwB,GACxB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAOxE,OAAO,EAAE,iBAAiB,IAAI,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE1G,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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F,CAAC,OAAO,CAAC,GAAG,EAAE;QACd,+BAA+B,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACvD,IAAI,IAAI,CAAC,wBAAwB,KAAK,MAAM;YAAE,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;IACzF,CAAC,CAAC,CAAC;IACH,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;IAC7C,IAAI,CAAC,0BAA0B,EAAE,CAAC;AACnC,CAAC;AACD,MAAM,UAAU,kBAAkB;IACjC,IAAI,CAAC,6BAA6B,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,IAAI,CAAC,iCAAiC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;AAClG,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type { Usage } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgentSessionInternalSurface as AgentSession,\n\tSessionCompactOptions,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.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 VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n\twidenToWholeContextStats,\n} from \"./compaction/index.ts\";\nimport { resolveCompactionModel } from \"./compaction/model-resolver.js\";\nimport type {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\nimport { assertSessionOpen as assertCompactionOpen, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport type { CompactionEntry, SessionEntry } 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\t// Region-only view first — what the extension's replacement text now costs\n\t// inside the region — then widen it to the whole context with the\n\t// independently estimated kept tail (symmetric, present on both sides when\n\t// kept). The authoritative `preparation.tokensBefore` is never mixed into\n\t// this comparison (#2052).\n\tconst tokensBefore = preparation.region.tokenEstimate;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4);\n\treturn widenToWholeContextStats(\n\t\t{\n\t\t\tlinesBefore,\n\t\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\t\tlinesKept,\n\t\t\trangeCount: 0,\n\t\t\ttokensBefore,\n\t\t\ttokensAfter,\n\t\t\tpercentReduction: tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10,\n\t\t},\n\t\tgetKeptTailTokenEstimate(preparation),\n\t\ttrue,\n\t);\n}\n\n/** A finished compaction plan, ready to be persisted as one boundary. */\nexport interface PlannedVerbatimCompaction {\n\treadonly text: string;\n\treadonly firstKeptEntryId: string | null;\n\treadonly tokensBefore: number;\n\t/** Durable details without `backupPath`, which only a commit creates. */\n\treadonly details: VerbatimCompactionDetails;\n\treadonly usage?: Usage;\n\treadonly fromExtension: boolean;\n}\n\n/**\n * Plan one verbatim compaction of `pathEntries` without changing the session: the extension hook,\n * then the planner ladder. Returns undefined when nothing is compactable and the caller may proceed.\n */\nexport async function planVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: Omit<VerbatimCompactionApplyOptions, \"backupLabel\">,\n\tpathEntries: SessionEntry[],\n): Promise<PlannedVerbatimCompaction | undefined> {\n\tassertCompactionOpen(this);\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\toptions.abortController.signal.throwIfAborted();\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings(model);\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\t// Mid-turn threshold preflight needs the load-bearing planner fallback if\n\t\t// a region exists, but a context that still fits is safe to send unchanged.\n\t\t// True overflow and a hard-limit preflight have no such escape hatch.\n\t\tconst mustFreeContext = options.urgency === \"load_bearing\" && (options.reason === \"overflow\" || allowSmallRegion);\n\t\tif (mustFreeContext) {\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\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\t\tusage?: Usage;\n\t\t\t\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\t\t\t\tmodel?: string;\n\t\t\t\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t\t\t\tsummaryFirstKeptEntryId?: string;\n\t\t\t\tsummaryTokensBefore?: number;\n\t\t\t\tfreshReason?: string;\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\tassertCompactionOpen(this);\n\t\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.cancel) {\n\t\t\toptions.abortController.abort();\n\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t}\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\toptions.onCompactionSource?.(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\tisFallbackModelAllowed: this._isFallbackModelAllowed,\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\t// Automatic compaction runs inside or ahead of an unattended turn, so its planning\n\t\t\t// gets a time limit (#4198). A manual run is watched and cancelled with Escape.\n\t\t\t...(options.reason === \"manual\"\n\t\t\t\t? {}\n\t\t\t\t: { planningTimeoutMs: this.settingsManager.getCompactionPlanningTimeoutMs() }),\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t\tresolveMorphApiKey: async () =>\n\t\t\t\t(await this._modelRuntime.getAuth(\"morph\", { signal: options.abortController.signal }))?.auth.apiKey,\n\t\t\tclassify: (classifierModel, context, classifierOptions) =>\n\t\t\t\tthis._modelRuntime.classify(classifierModel, context, classifierOptions),\n\t\t\tcompactionModel: resolveCompactionModel(\n\t\t\t\toptions.compactionModel ?? this.settingsManager.getCompactionModel(),\n\t\t\t\tmodel,\n\t\t\t\tthis._modelRuntime.getAllModels(),\n\t\t\t),\n\t\t\tsummaryEntries: pathEntries,\n\t\t\tcwd: this._cwd,\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\t...(run.usage ? { usage: run.usage } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t\t...(run.backend ? { backend: run.backend } : {}),\n\t\t\t...(run.model ? { model: run.model } : {}),\n\t\t\t...(run.summary ? { summary: run.summary } : {}),\n\t\t\t...(run.summaryFirstKeptEntryId ? { summaryFirstKeptEntryId: run.summaryFirstKeptEntryId } : {}),\n\t\t\t...(run.summaryTokensBefore !== undefined ? { summaryTokensBefore: run.summaryTokensBefore } : {}),\n\t\t\t...(run.freshReason ? { freshReason: run.freshReason } : {}),\n\t\t};\n\t}\n\tassertCompactionOpen(this);\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 =\n\t\tcompacted.summaryFirstKeptEntryId ?? (compacted.keptTail ? preparation.firstKeptEntryId : null);\n\treturn {\n\t\ttext: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore: compacted.summaryTokensBefore ?? preparation.tokensBefore,\n\t\tdetails: {\n\t\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\t\tparameters: preparation.parameters,\n\t\t\tstats: compacted.stats,\n\t\t\trung: compacted.rung,\n\t\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t\t...(compacted.freshReason ? { freshReason: compacted.freshReason } : {}),\n\t\t},\n\t\t...(compacted.usage ? { usage: compacted.usage } : {}),\n\t\tfromExtension,\n\t};\n}\n\n/** A boundary entry that has been written but not yet announced. */\nexport interface AppendedVerbatimBoundary {\n\treadonly entryId: string;\n\treadonly details: VerbatimCompactionDetails;\n\treadonly backupPath: string | undefined;\n}\n\n/**\n * Back up the session and append a planned compaction as one boundary. Nothing else changes, so a\n * failure here leaves history and the in-memory context as they were. `coveredThroughEntryId` marks a\n * background result whose later entries replay unchanged. `precondition` runs inside the append's queued mutation\n * and throws to refuse it.\n */\nexport async function appendVerbatimBoundary(\n\tthis: AgentSession,\n\tplanned: PlannedVerbatimCompaction,\n\toptions: { backupLabel: string; coveredThroughEntryId?: string; precondition?: () => void },\n): Promise<AppendedVerbatimBoundary> {\n\tconst backupPath = await this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = { ...planned.details, ...(backupPath ? { backupPath } : {}) };\n\tconst entryId = await this.sessionManager.appendCompaction(\n\t\tplanned.text,\n\t\tplanned.firstKeptEntryId,\n\t\tplanned.tokensBefore,\n\t\tdetails,\n\t\tplanned.usage,\n\t\toptions.coveredThroughEntryId,\n\t\toptions.precondition,\n\t);\n\treturn { entryId, details, backupPath };\n}\n\n/** Refresh the in-memory context after an appended boundary and notify `session_compact` listeners. */\nexport async function finishVerbatimCommit(\n\tthis: AgentSession,\n\tplanned: PlannedVerbatimCompaction,\n\tappended: AppendedVerbatimBoundary,\n\treason: \"manual\" | \"threshold\" | \"overflow\",\n): Promise<VerbatimCompactionResult> {\n\tconst { entryId, details, backupPath } = appended;\n\tthis._refreshFinalizedContext();\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: planned.text,\n\t\tfirstKeptEntryId: planned.firstKeptEntryId,\n\t\ttokensBefore: planned.tokensBefore,\n\t\tstats: details.stats,\n\t\tparameters: details.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: details.rung,\n\t\t...(details.plannerModel ? { plannerModel: details.plannerModel } : {}),\n\t\t...(details.backend ? { backend: details.backend } : {}),\n\t\t...(details.model ? { model: details.model } : {}),\n\t\t...(details.summary ? { summary: details.summary } : {}),\n\t\t...(details.freshReason ? { freshReason: details.freshReason } : {}),\n\t\t...(planned.usage ? { usage: planned.usage } : {}),\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,\n\t\t\tparameters: details.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension: planned.fromExtension,\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\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tconst planned = await planVerbatimCompaction.call(this, options, this.sessionManager.getBranch());\n\tif (!planned) return undefined;\n\tconst appended = await appendVerbatimBoundary.call(this, planned, { backupLabel: options.backupLabel });\n\treturn finishVerbatimCommit.call(this, planned, appended, options.reason);\n}\n\nexport async function emitSessionCompactFailed(\n\tsession: AgentSession,\n\tevent: Omit<SessionCompactFailedEvent, \"type\">,\n): Promise<void> {\n\tif (session._extensionRunner?.hasHandlers(\"session_compact_failed\")) {\n\t\tawait session._extensionRunner.emit({ type: \"session_compact_failed\", ...event });\n\t}\n}\n\nfunction clearOwnedManualCompactionState(this: AgentSession, controller: AbortController): void {\n\tif (this._compactionAbortController !== controller) return;\n\tthis._compactionAbortController = undefined;\n\tif (this._compactionReason === \"manual\") this._compactionReason = undefined;\n\t// Lifecycle listeners run synchronously. Once the manual end event is\n\t// emitted, a new /compact must own a new run rather than join the settled one.\n\tthis._manualCompactionPromise = undefined;\n}\n\nasync function emitManualCompactionFailure(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\terror: unknown,\n\tfromExtension: boolean,\n): Promise<void> {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst aborted = controller.signal.aborted;\n\tconst errorMessage = aborted ? undefined : `Compaction failed: ${message}`;\n\tclearOwnedManualCompactionState.call(this, controller);\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"manual\",\n\t\tresult: undefined,\n\t\taborted,\n\t\twillRetry: false,\n\t\terrorMessage,\n\t});\n\tawait emitSessionCompactFailed(this, {\n\t\treason: \"manual\",\n\t\terrorMessage,\n\t\taborted,\n\t\twillRetry: false,\n\t\tfromExtension,\n\t});\n}\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: SessionCompactOptions,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\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\t...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),\n\t\t\tresolvePlannerAuth: async (candidate, signal) =>\n\t\t\t\tauthForStream(this, await this._getRequiredRequestAuth(candidate, signal ?? controller.signal)),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\t// compaction_end listeners synchronously flush queued prompts, so they must\n\t\t// observe an idle session before dispatching the next user turn.\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tawait emitManualCompactionFailure.call(this, controller, error, fromExtension);\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. Manual compaction aborts an\n * active agent run before it starts, while agent event delivery remains live so\n * a pending threshold check cannot race the requested manual boundary.\n */\nexport function compact(this: AgentSession, options: SessionCompactOptions = {}): Promise<VerbatimCompactionResult> {\n\ttry {\n\t\tassertCompactionOpen(this);\n\t\tif (options.compactionModel !== undefined && this.model) {\n\t\t\tresolveCompactionModel(options.compactionModel, this.model, this._modelRuntime.getAllModels());\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\n\t// A manual boundary replaces the automatic turn that scheduled any pending\n\t// retry. Invalidate its timer before this run claims compaction ownership.\n\tthis._postCompactionContinuationToken += 1;\n\tthis._pendingPostCompactionContinuation = undefined;\n\n\tconst automaticCompletion = this._autoCompactionCompletion;\n\t// The manual request wins. Abort the active automatic planner now, before the\n\t// next microtask can admit a post-tool or threshold boundary, then wait for\n\t// its owner to settle before mutating the transcript ourselves. Start the\n\t// session abort before publishing this new manual owner so abort() cancels\n\t// prior work rather than cancelling or waiting on the compaction being started.\n\tthis._autoCompactionAbortController?.abort();\n\tthis._abortBackgroundCompaction();\n\tconst abortBoundary = this.abort();\n\n\tconst controller = new AbortController();\n\tthis._compactionAbortController = controller;\n\tthis._compactionReason = \"manual\";\n\t// Handle rejection now so a failing event drain cannot become unhandled\n\t// while an automatic run finishes.\n\tvoid abortBoundary.catch(() => {});\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 = trackSessionWork(this, () =>\n\t\tPromise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tif (automaticCompletion !== undefined) await automaticCompletion;\n\t\t\t\tawait abortBoundary;\n\t\t\t} catch (error) {\n\t\t\t\t// The abort drain can fail before the planner starts. Finish the\n\t\t\t\t// manual lifecycle so event consumers can release queued input.\n\t\t\t\tawait emitManualCompactionFailure.call(this, controller, error, false);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCompactionOpen(this);\n\t\t\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t}),\n\t).finally(() => {\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\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\tthis._abortBackgroundCompaction();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tthis._writeBackgroundCompactionSetting(() => this.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":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAM3E,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,iCAAiC,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAClH,OAAO,EACN,yBAAyB,EAMzB,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,EACb,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,EAK5B,wBAAwB,EACxB,mBAAmB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAOxE,OAAO,EAAE,iBAAiB,IAAI,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE1G,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACxF,OAAO,EAAE,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jC,IAAI,CAAC,6BAA6B,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,IAAI,CAAC,iCAAiC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;AAClG,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type { Usage } from \"@bastani/pi-ai/compat\";\nimport { getCompactionDiagnosticsDir } from \"../config.js\";\nimport { awaitedToolTurnEntryId } from \"./agent-session-detached-tools.ts\";\nimport type {\n\tAgentSessionInternalSurface as AgentSession,\n\tSessionCompactOptions,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport { findBackgroundCompactionSafePoint, findUnansweredToolCall } from \"./compaction/background-compaction.ts\";\nimport {\n\tautoDetectCompactionQuery,\n\ttype CompactionBoundaryControl,\n\ttype CompactionPlannerModel,\n\ttype CompactionPlanOptions,\n\ttype CompactionRung,\n\ttype FallbackPlannerContext,\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trecallHistory,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n\twidenToWholeContextStats,\n\twithRecalledContext,\n} from \"./compaction/index.ts\";\nimport { resolveCompactionModel } from \"./compaction/model-resolver.js\";\nimport type {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\nimport { assertSessionOpen as assertCompactionOpen, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport type { CompactionEntry, SessionEntry } from \"./session-manager.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\nimport { createHistoryRouter, transcriptEntryLines } from \"./tools/history-protocol.ts\";\nimport { renderHistoryTranscript } from \"./tools/history-transcript.ts\";\n\n/** This session's own history layout, or undefined when it has no history a `read` could open. */\nfunction historyLocation(session: AgentSession): CompactionBoundaryControl[\"history\"] {\n\tconst manager = session.sessionManager;\n\tconst header = manager.getHeader();\n\tif (!header || !manager.isPersisted()) return undefined;\n\tconst { entryRanges } = renderHistoryTranscript(header, manager.getEntries(), true);\n\treturn { sessionId: manager.getSessionId(), entryRanges };\n}\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\t// Region-only view first — what the extension's replacement text now costs\n\t// inside the region — then widen it to the whole context with the\n\t// independently estimated kept tail (symmetric, present on both sides when\n\t// kept). The authoritative `preparation.tokensBefore` is never mixed into\n\t// this comparison (#2052).\n\tconst tokensBefore = preparation.region.tokenEstimate;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4);\n\treturn widenToWholeContextStats(\n\t\t{\n\t\t\tlinesBefore,\n\t\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\t\tlinesKept,\n\t\t\trangeCount: 0,\n\t\t\ttokensBefore,\n\t\t\ttokensAfter,\n\t\t\tpercentReduction: tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10,\n\t\t},\n\t\tgetKeptTailTokenEstimate(preparation),\n\t\ttrue,\n\t);\n}\n\nfunction entriesAfterRegion(branch: readonly SessionEntry[], preparation: VerbatimCompactionPreparation) {\n\tconst lastRegionEntryId = preparation.regionEntryIds[preparation.regionEntryIds.length - 1];\n\tif (lastRegionEntryId !== undefined) {\n\t\tconst index = branch.findIndex((entry) => entry.id === lastRegionEntryId);\n\t\treturn index < 0 ? [] : branch.slice(index + 1);\n\t}\n\tconst keptIndex = branch.findIndex((entry) => entry.id === preparation.firstKeptEntryId);\n\treturn keptIndex < 0 ? [] : branch.slice(keptIndex);\n}\n\n/**\n * The planned text with a `Recalled context` section from earlier history, or `undefined` to leave it as planned.\n * Every failure, timeout and cancellation also leaves it as planned: recall is never a reason to fail or hold up\n * compaction.\n */\nasync function recallForPlannedText(\n\tsession: AgentSession,\n\tpreparation: VerbatimCompactionPreparation,\n\tpathEntries: readonly SessionEntry[],\n\tplanned: { text: string; stats: VerbatimCompactionStats },\n\tsignal: AbortSignal,\n): Promise<{ text: string; stats: VerbatimCompactionStats } | undefined> {\n\ttry {\n\t\tconst router = createHistoryRouter({\n\t\t\tcwd: session._cwd,\n\t\t\tcurrentSessionId: session.sessionManager.getSessionId(),\n\t\t\tsessionStore: () => session.sessionManager.getSessionStore(),\n\t\t\tworkflows: () => session._extensionRunner?.getWorkflowRunControl(),\n\t\t});\n\t\tconst section = await recallHistory({\n\t\t\trouter,\n\t\t\tsessionId: session.sessionManager.getSessionId(),\n\t\t\tqueries: [autoDetectCompactionQuery(pathEntries), preparation.parameters.query],\n\t\t\tkeptLines: [\n\t\t\t\t...planned.text.split(\"\\n\"),\n\t\t\t\t...transcriptEntryLines(entriesAfterRegion(session.sessionManager.getBranch(), preparation)),\n\t\t\t],\n\t\t\tkeptTokens: planned.stats.tokensAfter,\n\t\t\tsignal,\n\t\t});\n\t\tif (section === undefined) return undefined;\n\t\tconst text = withRecalledContext(planned.text, section);\n\t\tconst tokensAfter = planned.stats.tokensAfter + Math.ceil((text.length - planned.text.length) / 4);\n\t\treturn {\n\t\t\ttext,\n\t\t\tstats: {\n\t\t\t\t...planned.stats,\n\t\t\t\ttokensAfter,\n\t\t\t\tpercentReduction:\n\t\t\t\t\tplanned.stats.tokensBefore === 0\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: Math.round((1 - tokensAfter / planned.stats.tokensBefore) * 1000) / 10,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A finished compaction plan, ready to be persisted as one boundary. */\nexport interface PlannedVerbatimCompaction {\n\treadonly text: string;\n\treadonly firstKeptEntryId: string | null;\n\treadonly tokensBefore: number;\n\t/** Durable details without `backupPath`, which only a commit creates. */\n\treadonly details: VerbatimCompactionDetails;\n\treadonly usage?: Usage;\n\treadonly fromExtension: boolean;\n}\n\n/**\n * Plan one verbatim compaction of `pathEntries` without changing the session: the extension hook,\n * then the planner ladder. Returns undefined when nothing is compactable and the caller may proceed.\n */\nexport async function planVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: Omit<VerbatimCompactionApplyOptions, \"backupLabel\">,\n\tpathEntries: SessionEntry[],\n): Promise<PlannedVerbatimCompaction | undefined> {\n\tassertCompactionOpen(this);\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\toptions.abortController.signal.throwIfAborted();\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings(model);\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, history: historyLocation(this) },\n\t);\n\tif (!preparation) {\n\t\t// Mid-turn threshold preflight needs the load-bearing planner fallback if\n\t\t// a region exists, but a context that still fits is safe to send unchanged.\n\t\t// True overflow and a hard-limit preflight have no such escape hatch.\n\t\tconst mustFreeContext = options.urgency === \"load_bearing\" && (options.reason === \"overflow\" || allowSmallRegion);\n\t\tif (mustFreeContext) {\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\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\t...(this.sessionManager.isPersisted()\n\t\t\t? {\n\t\t\t\t\tsidecarDirectory: {\n\t\t\t\t\t\tdirectory: getCompactionDiagnosticsDir(),\n\t\t\t\t\t\tstem: this.sessionManager.getSessionId(),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\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\t\tusage?: Usage;\n\t\t\t\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\t\t\t\tmodel?: string;\n\t\t\t\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t\t\t\tsummaryFirstKeptEntryId?: string;\n\t\t\t\tsummaryTokensBefore?: number;\n\t\t\t\tfreshReason?: string;\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\tassertCompactionOpen(this);\n\t\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.cancel) {\n\t\t\toptions.abortController.abort();\n\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t}\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\toptions.onCompactionSource?.(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\tisFallbackModelAllowed: this._isFallbackModelAllowed,\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\t// Automatic compaction runs inside or ahead of an unattended turn, so its planning\n\t\t\t// gets a time limit (#4198). A manual run is watched and cancelled with Escape.\n\t\t\t...(options.reason === \"manual\"\n\t\t\t\t? {}\n\t\t\t\t: { planningTimeoutMs: this.settingsManager.getCompactionPlanningTimeoutMs() }),\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t\tresolveMorphApiKey: async () =>\n\t\t\t\t(await this._modelRuntime.getAuth(\"morph\", { signal: options.abortController.signal }))?.auth.apiKey,\n\t\t\tclassify: (classifierModel, context, classifierOptions) =>\n\t\t\t\tthis._modelRuntime.classify(classifierModel, context, classifierOptions),\n\t\t\tcompactionModel: resolveCompactionModel(\n\t\t\t\toptions.compactionModel ?? this.settingsManager.getCompactionModel(),\n\t\t\t\tmodel,\n\t\t\t\tthis._modelRuntime.getAllModels(),\n\t\t\t),\n\t\t\tsummaryEntries: pathEntries,\n\t\t\tcwd: this._cwd,\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\t...(run.usage ? { usage: run.usage } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t\t...(run.backend ? { backend: run.backend } : {}),\n\t\t\t...(run.model ? { model: run.model } : {}),\n\t\t\t...(run.summary ? { summary: run.summary } : {}),\n\t\t\t...(run.summaryFirstKeptEntryId ? { summaryFirstKeptEntryId: run.summaryFirstKeptEntryId } : {}),\n\t\t\t...(run.summaryTokensBefore !== undefined ? { summaryTokensBefore: run.summaryTokensBefore } : {}),\n\t\t\t...(run.freshReason ? { freshReason: run.freshReason } : {}),\n\t\t};\n\t}\n\tassertCompactionOpen(this);\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\tif (\n\t\tcompacted.rung === \"planned\" &&\n\t\tcompacted.backend !== \"summary\" &&\n\t\tthis.settingsManager.getCompactionHistoryRecall()\n\t) {\n\t\tconst recalled = await recallForPlannedText(\n\t\t\tthis,\n\t\t\tpreparation,\n\t\t\tpathEntries,\n\t\t\tcompacted,\n\t\t\toptions.abortController.signal,\n\t\t);\n\t\tassertCompactionOpen(this);\n\t\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (recalled) compacted = { ...compacted, ...recalled };\n\t}\n\n\t// A fresh rung that had to drop the protected tail persists no tail boundary.\n\tconst firstKeptEntryId =\n\t\tcompacted.summaryFirstKeptEntryId ?? (compacted.keptTail ? preparation.firstKeptEntryId : null);\n\treturn {\n\t\ttext: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore: compacted.summaryTokensBefore ?? preparation.tokensBefore,\n\t\tdetails: {\n\t\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\t\tparameters: preparation.parameters,\n\t\t\tstats: compacted.stats,\n\t\t\trung: compacted.rung,\n\t\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t\t...(compacted.freshReason ? { freshReason: compacted.freshReason } : {}),\n\t\t},\n\t\t...(compacted.usage ? { usage: compacted.usage } : {}),\n\t\tfromExtension,\n\t};\n}\n\n/** A boundary entry that has been written but not yet announced. */\nexport interface AppendedVerbatimBoundary {\n\treadonly entryId: string;\n\treadonly details: VerbatimCompactionDetails;\n\treadonly backupPath: string | undefined;\n}\n\n/**\n * Back up the session and append a planned compaction as one boundary. Nothing else changes, so a\n * failure here leaves history and the in-memory context as they were. `coveredThroughEntryId` marks a\n * background result whose later entries replay unchanged. `precondition` runs inside the append's queued mutation\n * and throws to refuse it.\n */\nexport async function appendVerbatimBoundary(\n\tthis: AgentSession,\n\tplanned: PlannedVerbatimCompaction,\n\toptions: { backupLabel: string; coveredThroughEntryId?: string; precondition?: () => void },\n): Promise<AppendedVerbatimBoundary> {\n\tconst backupPath = await this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = { ...planned.details, ...(backupPath ? { backupPath } : {}) };\n\tconst entryId = await this.sessionManager.appendCompaction(\n\t\tplanned.text,\n\t\tplanned.firstKeptEntryId,\n\t\tplanned.tokensBefore,\n\t\tdetails,\n\t\tplanned.usage,\n\t\toptions.coveredThroughEntryId,\n\t\toptions.precondition,\n\t);\n\treturn { entryId, details, backupPath };\n}\n\n/** Refresh the in-memory context after an appended boundary and notify `session_compact` listeners. */\nexport async function finishVerbatimCommit(\n\tthis: AgentSession,\n\tplanned: PlannedVerbatimCompaction,\n\tappended: AppendedVerbatimBoundary,\n\treason: \"manual\" | \"threshold\" | \"overflow\",\n): Promise<VerbatimCompactionResult> {\n\tconst { entryId, details, backupPath } = appended;\n\tthis._refreshFinalizedContext();\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: planned.text,\n\t\tfirstKeptEntryId: planned.firstKeptEntryId,\n\t\ttokensBefore: planned.tokensBefore,\n\t\tstats: details.stats,\n\t\tparameters: details.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: details.rung,\n\t\t...(details.plannerModel ? { plannerModel: details.plannerModel } : {}),\n\t\t...(details.backend ? { backend: details.backend } : {}),\n\t\t...(details.model ? { model: details.model } : {}),\n\t\t...(details.summary ? { summary: details.summary } : {}),\n\t\t...(details.freshReason ? { freshReason: details.freshReason } : {}),\n\t\t...(planned.usage ? { usage: planned.usage } : {}),\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,\n\t\t\tparameters: details.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension: planned.fromExtension,\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\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tconst branch = this.sessionManager.getBranch();\n\t// A boundary folds the entries it covers into text. A call that has no result yet must stay a tool call for the\n\t// result it is waiting on (a detached call's, #4580), so the boundary covers only what precedes its turn, as a\n\t// background compaction does.\n\tconst awaited = awaitedToolTurnEntryId(this);\n\tconst waiting = findUnansweredToolCall(branch, awaited) !== undefined;\n\tconst covered = waiting ? branch.slice(0, findBackgroundCompactionSafePoint(branch, awaited) + 1) : branch;\n\tconst planned = await planVerbatimCompaction.call(this, options, covered);\n\tif (!planned) return undefined;\n\tconst appended = await appendVerbatimBoundary.call(this, planned, {\n\t\tbackupLabel: options.backupLabel,\n\t\t...(waiting ? { coveredThroughEntryId: covered[covered.length - 1].id } : {}),\n\t});\n\treturn finishVerbatimCommit.call(this, planned, appended, options.reason);\n}\n\nexport async function emitSessionCompactFailed(\n\tsession: AgentSession,\n\tevent: Omit<SessionCompactFailedEvent, \"type\">,\n): Promise<void> {\n\tif (session._extensionRunner?.hasHandlers(\"session_compact_failed\")) {\n\t\tawait session._extensionRunner.emit({ type: \"session_compact_failed\", ...event });\n\t}\n}\n\nfunction clearOwnedManualCompactionState(this: AgentSession, controller: AbortController): void {\n\tif (this._compactionAbortController !== controller) return;\n\tthis._compactionAbortController = undefined;\n\tif (this._compactionReason === \"manual\") this._compactionReason = undefined;\n\t// Lifecycle listeners run synchronously. Once the manual end event is\n\t// emitted, a new /compact must own a new run rather than join the settled one.\n\tthis._manualCompactionPromise = undefined;\n}\n\nasync function emitManualCompactionFailure(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\terror: unknown,\n\tfromExtension: boolean,\n): Promise<void> {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst aborted = controller.signal.aborted;\n\tconst errorMessage = aborted ? undefined : `Compaction failed: ${message}`;\n\tclearOwnedManualCompactionState.call(this, controller);\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"manual\",\n\t\tresult: undefined,\n\t\taborted,\n\t\twillRetry: false,\n\t\terrorMessage,\n\t});\n\tawait emitSessionCompactFailed(this, {\n\t\treason: \"manual\",\n\t\terrorMessage,\n\t\taborted,\n\t\twillRetry: false,\n\t\tfromExtension,\n\t});\n}\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: SessionCompactOptions,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\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\t...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),\n\t\t\tresolvePlannerAuth: async (candidate, signal) =>\n\t\t\t\tauthForStream(this, await this._getRequiredRequestAuth(candidate, signal ?? controller.signal)),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\t// compaction_end listeners synchronously flush queued prompts, so they must\n\t\t// observe an idle session before dispatching the next user turn.\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tawait emitManualCompactionFailure.call(this, controller, error, fromExtension);\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. Manual compaction aborts an\n * active agent run before it starts, while agent event delivery remains live so\n * a pending threshold check cannot race the requested manual boundary.\n */\nexport function compact(this: AgentSession, options: SessionCompactOptions = {}): Promise<VerbatimCompactionResult> {\n\ttry {\n\t\tassertCompactionOpen(this);\n\t\tif (options.compactionModel !== undefined && this.model) {\n\t\t\tresolveCompactionModel(options.compactionModel, this.model, this._modelRuntime.getAllModels());\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\n\t// A manual boundary replaces the automatic turn that scheduled any pending\n\t// retry. Invalidate its timer before this run claims compaction ownership.\n\tthis._postCompactionContinuationToken += 1;\n\tthis._pendingPostCompactionContinuation = undefined;\n\n\tconst automaticCompletion = this._autoCompactionCompletion;\n\t// The manual request wins. Abort the active automatic planner now, before the\n\t// next microtask can admit a post-tool or threshold boundary, then wait for\n\t// its owner to settle before mutating the transcript ourselves. Start the\n\t// session abort before publishing this new manual owner so abort() cancels\n\t// prior work rather than cancelling or waiting on the compaction being started.\n\tthis._autoCompactionAbortController?.abort();\n\tthis._abortBackgroundCompaction();\n\tconst abortBoundary = this.abort();\n\n\tconst controller = new AbortController();\n\tthis._compactionAbortController = controller;\n\tthis._compactionReason = \"manual\";\n\t// Handle rejection now so a failing event drain cannot become unhandled\n\t// while an automatic run finishes.\n\tvoid abortBoundary.catch(() => {});\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 = trackSessionWork(this, () =>\n\t\tPromise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tif (automaticCompletion !== undefined) await automaticCompletion;\n\t\t\t\tawait abortBoundary;\n\t\t\t} catch (error) {\n\t\t\t\t// The abort drain can fail before the planner starts. Finish the\n\t\t\t\t// manual lifecycle so event consumers can release queued input.\n\t\t\t\tawait emitManualCompactionFailure.call(this, controller, error, false);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCompactionOpen(this);\n\t\t\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t}),\n\t).finally(() => {\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\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\tthis._abortBackgroundCompaction();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tthis._writeBackgroundCompactionSetting(() => this.settingsManager.setCompactionEnabled(enabled));\n}\n\nexport const agentSessionCompactionMethods = {\n\t_applyVerbatimCompaction,\n\tcompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
@@ -86,6 +86,11 @@ export declare function detachableTool(session: AgentSession, tool: AgentTool, e
86
86
  export declare function withoutDetachedPlaceholders(session: AgentSession, event: AgentEvent): AgentEvent | undefined;
87
87
  export declare function setToolDetachment(this: AgentSession, policy: ToolDetachmentPolicy | undefined): void;
88
88
  export declare function takeDetachedToolCalls(this: AgentSession): DetachedToolCall[];
89
+ /**
90
+ * The id of the history entry of the turn that still waits for a call's result, or undefined when none does. A
91
+ * compaction keeps this turn out of what it folds into text, whatever entries came after it (#4580).
92
+ */
93
+ export declare function awaitedToolTurnEntryId(session: AgentSession): string | undefined;
89
94
  /**
90
95
  * Whether the transcript ends on a turn that issued a detachable call and has no answer from the model yet, with or
91
96
  * without its results: a session reopened after its process died continues that turn instead of being prompted again.
@@ -96,6 +101,14 @@ export declare function hasPendingDetachedTurn(this: AgentSession): boolean;
96
101
  * between such a call and its result, so input that would land there waits until the turn resumes.
97
102
  */
98
103
  export declare function waitsOnDetachedResults(session: AgentSession): boolean;
104
+ /**
105
+ * Whether this session must not start a turn of its own: its host set a detachment policy, so it hands back the results
106
+ * of the calls that detached, and its transcript waits on one. A turn that started now would move
107
+ * the transcript past the call; whatever would start it waits, and the turn the hand-back continues takes it up.
108
+ */
109
+ export declare function holdsTurnsForDetachedResults(session: AgentSession): boolean;
110
+ /** Whether the transcript ends on a turn still waiting for the result of a call of a detachable tool. */
111
+ export declare function isWaitingOnDetachedResults(this: AgentSession): boolean;
99
112
  /**
100
113
  * Mark every call of a detachable tool that the transcript ends on without a result as in flight, not interrupted,
101
114
  * until its result is recorded. A workflow stage resumed after its process died starts those calls again, or records
@@ -116,17 +129,19 @@ export declare function redispatchDetachedToolCalls(this: AgentSession): Detache
116
129
  * Record the results of detached calls the transcript is waiting on, each as its own call's result right after its
117
130
  * call, then continue the turn that issued them once every detachable call of that turn has its result. Results may
118
131
  * arrive together or across several calls: until the last one arrives, the session records what it is given and
119
- * resolves without continuing. A result for a call that already has one, or repeated in `results`, is ignored. With
120
- * no new result, a transcript that ends on a detachable turn whose every call has its result continues that turn
121
- * (its process stopped before the model answered), and a turn still waiting on a call is left as it is. Each result
122
- * is finalized as an inline call's is: extension `tool_result` handlers, image normalization and the
123
- * oversized-output spill.
132
+ * resolves without continuing. A result for a call that already has one, repeated in `results`, or issued by a turn
133
+ * the transcript has moved past is ignored (the last one is reported in the debug log); a result for a call no
134
+ * message of the transcript issued throws `unknown-tool-call`. With no new result, a transcript that ends on a
135
+ * detachable turn whose every call has its result continues that turn (its process stopped before the model
136
+ * answered), and a turn still waiting on a call is left as it is. Each result is finalized as an inline call's is:
137
+ * extension `tool_result` handlers, image normalization and the oversized-output spill.
124
138
  */
125
139
  export declare function resumeDetachedTurn(this: AgentSession, results: readonly DetachedToolResult[]): Promise<void>;
126
140
  export declare const agentSessionDetachedToolMethods: {
127
141
  setToolDetachment: typeof setToolDetachment;
128
142
  hasPendingDetachedTurn: typeof hasPendingDetachedTurn;
129
143
  takeDetachedToolCalls: typeof takeDetachedToolCalls;
144
+ isWaitingOnDetachedResults: typeof isWaitingOnDetachedResults;
130
145
  redispatchDetachedToolCalls: typeof redispatchDetachedToolCalls;
131
146
  resumeDetachedTurn: typeof resumeDetachedTurn;
132
147
  };
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-detached-tools.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-detached-tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEX,UAAU,EAEV,SAAS,E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GrE;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAE3E;AAED,yGAAyG;AACzG,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAMvE;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,YAAY,GAAG,gBAAgB,EAAE,CAoBlF;AAoJD;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,SAAS,kBAAkB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA0ClH;AAED,eAAO,MAAM,+BAA+B;;;;;;;CAO3C,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { deliverHeldTaskCompletions } from "./agent-session-tasks.js";
3
3
  import { finalizeToolResult } from "./agent-session-tool-hooks.js";
4
+ import { reportDebug } from "./debug.js";
4
5
  import { serializeErrorCause } from "./error-contract.js";
5
6
  import { sessionGenerationClosing, trackSessionWork } from "./session-lifecycle-work.js";
6
7
  import { MAX_TOOL_DETACHMENT_AFTER_MS, ToolDetachmentError } from "./tool-detachment-errors.js";
@@ -376,16 +377,52 @@ export function takeDetachedToolCalls() {
376
377
  return [];
377
378
  const calls = [...detached.values()];
378
379
  detached.clear();
379
- return calls;
380
+ return calls.filter((call) => !settleStaleCall(this, call));
380
381
  }
381
382
  /**
382
- * The last assistant message of the transcript, the calls of detachable tools it is still waiting on, and whether that
383
- * message issued a detachable call at all: a transcript that ends on such a turn has not had the model's answer yet.
384
- * A tool is detachable in this session when the session registered how its work starts.
383
+ * Settle a parked call whose turn the transcript has moved past: nothing waits on its result any more, so cancel its
384
+ * work and report it, so the host never waits for it. Says whether the call was dropped.
385
385
  */
386
- function pendingDetachableCalls(session) {
387
- const none = { assistant: undefined, calls: [], endsOnDetachableTurn: false };
388
- const messages = session.sessionManager.buildSessionProjection().messages;
386
+ function settleStaleCall(session, call) {
387
+ if (!transcriptMovedPast(session, call.toolCallId))
388
+ return false;
389
+ reportStaleDetachedCall(session, call);
390
+ call.abort(new DOMException("The transcript moved past this detached tool call", "AbortError"));
391
+ return true;
392
+ }
393
+ /** The debug record of a detached call the session dropped as stale: no exception, nothing for the host to handle. */
394
+ function reportStaleDetachedCall(session, call, reason = "transcript-moved") {
395
+ reportDebug("workflow", "stale-detached-call", {
396
+ sessionId: session.sessionManager.getSessionId(),
397
+ toolCallId: call.toolCallId,
398
+ toolName: call.toolName,
399
+ reason,
400
+ });
401
+ }
402
+ /** Whether an assistant message of the session's history issued `toolCallId`, even one a compaction folded into text. */
403
+ function wasIssued(session, toolCallId) {
404
+ return session.sessionManager
405
+ .getBranch()
406
+ .some((entry) => entry.type === "message" &&
407
+ entry.message.role === "assistant" &&
408
+ entry.message.content.some((block) => block.type === "toolCall" && block.id === toolCallId));
409
+ }
410
+ /**
411
+ * Whether `toolCallId` was issued by a turn the transcript no longer ends on, or already has its result: a call whose
412
+ * result nothing waits for. A call no message of the history issued is not one, so it reaches its host's checks.
413
+ */
414
+ function transcriptMovedPast(session, toolCallId) {
415
+ return wasIssued(session, toolCallId) && !trailingToolTurn(session).awaiting.has(toolCallId);
416
+ }
417
+ /**
418
+ * The last assistant message of the transcript when it issued tool calls and nothing but results follows it, and the
419
+ * ids of its calls that have no result yet. Any later user or assistant message means a later turn already moved past
420
+ * the calls: only a transcript that ends on the turn is waiting.
421
+ */
422
+ function trailingToolTurn(session) {
423
+ const none = { assistant: undefined, awaiting: new Set() };
424
+ const projection = session.sessionManager.buildSessionProjection();
425
+ const messages = projection.messages;
389
426
  let index = messages.length - 1;
390
427
  while (index >= 0 && messages[index]?.role !== "assistant")
391
428
  index--;
@@ -393,10 +430,30 @@ function pendingDetachableCalls(session) {
393
430
  if (assistant?.stopReason !== "toolUse")
394
431
  return none;
395
432
  const later = messages.slice(index + 1);
396
- // A later turn already moved past the call; only a transcript that ends on it is waiting.
397
433
  if (later.some((message) => message.role === "user" || message.role === "assistant"))
398
434
  return none;
399
435
  const answered = new Set(later.flatMap((message) => (message.role === "toolResult" ? [message.toolCallId] : [])));
436
+ const awaiting = new Set(assistant.content.flatMap((block) => (block.type === "toolCall" && !answered.has(block.id) ? [block.id] : [])));
437
+ const entryId = projection.entries.find((entry) => entry.messages.includes(assistant))?.sourceEntry.id;
438
+ return { assistant, awaiting, ...(entryId === undefined ? {} : { entryId }) };
439
+ }
440
+ /**
441
+ * The id of the history entry of the turn that still waits for a call's result, or undefined when none does. A
442
+ * compaction keeps this turn out of what it folds into text, whatever entries came after it (#4580).
443
+ */
444
+ export function awaitedToolTurnEntryId(session) {
445
+ const { awaiting, entryId } = trailingToolTurn(session);
446
+ return awaiting.size > 0 ? entryId : undefined;
447
+ }
448
+ /**
449
+ * The last assistant message of the transcript, the calls of detachable tools it is still waiting on, and whether that
450
+ * message issued a detachable call at all: a transcript that ends on such a turn has not had the model's answer yet.
451
+ * A tool is detachable in this session when the session registered how its work starts.
452
+ */
453
+ function pendingDetachableCalls(session) {
454
+ const { assistant, awaiting } = trailingToolTurn(session);
455
+ if (assistant === undefined)
456
+ return { assistant, calls: [], endsOnDetachableTurn: false };
400
457
  const state = states.get(session);
401
458
  const detachable = assistant.content.flatMap((block) => {
402
459
  if (block.type !== "toolCall")
@@ -410,7 +467,7 @@ function pendingDetachableCalls(session) {
410
467
  });
411
468
  return {
412
469
  assistant,
413
- calls: detachable.filter(({ toolCall }) => !answered.has(toolCall.id)),
470
+ calls: detachable.filter(({ toolCall }) => awaiting.has(toolCall.id)),
414
471
  endsOnDetachableTurn: detachable.length > 0,
415
472
  };
416
473
  }
@@ -430,6 +487,18 @@ export function waitsOnDetachedResults(session) {
430
487
  return false;
431
488
  return pendingDetachableCalls(session).calls.length > 0;
432
489
  }
490
+ /**
491
+ * Whether this session must not start a turn of its own: its host set a detachment policy, so it hands back the results
492
+ * of the calls that detached, and its transcript waits on one. A turn that started now would move
493
+ * the transcript past the call; whatever would start it waits, and the turn the hand-back continues takes it up.
494
+ */
495
+ export function holdsTurnsForDetachedResults(session) {
496
+ return hasToolDetachment(session) && waitsOnDetachedResults(session);
497
+ }
498
+ /** Whether the transcript ends on a turn still waiting for the result of a call of a detachable tool. */
499
+ export function isWaitingOnDetachedResults() {
500
+ return waitsOnDetachedResults(this);
501
+ }
433
502
  /**
434
503
  * Mark every call of a detachable tool that the transcript ends on without a result as in flight, not interrupted,
435
504
  * until its result is recorded. A workflow stage resumed after its process died starts those calls again, or records
@@ -607,11 +676,12 @@ function recordWithoutContinuing(session, answers) {
607
676
  * Record the results of detached calls the transcript is waiting on, each as its own call's result right after its
608
677
  * call, then continue the turn that issued them once every detachable call of that turn has its result. Results may
609
678
  * arrive together or across several calls: until the last one arrives, the session records what it is given and
610
- * resolves without continuing. A result for a call that already has one, or repeated in `results`, is ignored. With
611
- * no new result, a transcript that ends on a detachable turn whose every call has its result continues that turn
612
- * (its process stopped before the model answered), and a turn still waiting on a call is left as it is. Each result
613
- * is finalized as an inline call's is: extension `tool_result` handlers, image normalization and the
614
- * oversized-output spill.
679
+ * resolves without continuing. A result for a call that already has one, repeated in `results`, or issued by a turn
680
+ * the transcript has moved past is ignored (the last one is reported in the debug log); a result for a call no
681
+ * message of the transcript issued throws `unknown-tool-call`. With no new result, a transcript that ends on a
682
+ * detachable turn whose every call has its result continues that turn (its process stopped before the model
683
+ * answered), and a turn still waiting on a call is left as it is. Each result is finalized as an inline call's is:
684
+ * extension `tool_result` handlers, image normalization and the oversized-output spill.
615
685
  */
616
686
  export async function resumeDetachedTurn(results) {
617
687
  const sessionId = this.sessionManager.getSessionId();
@@ -625,22 +695,27 @@ export async function resumeDetachedTurn(results) {
625
695
  const recorded = new Set(this.sessionManager
626
696
  .buildSessionProjection()
627
697
  .messages.flatMap((message) => (message.role === "toolResult" ? [message.toolCallId] : [])));
628
- const pending = results.filter((result) => {
698
+ const given = results.filter((result) => {
629
699
  if (recorded.has(result.toolCallId))
630
700
  return false;
631
701
  recorded.add(result.toolCallId);
632
702
  return true;
633
703
  });
634
- const answers = pending.flatMap((result) => {
635
- const toolCall = issued.get(result.toolCallId);
636
- return toolCall === undefined ? [] : [{ toolCall, result }];
637
- });
638
- const unknown = pending.find((result) => !issued.has(result.toolCallId));
704
+ // A result for a turn the transcript moved past answers nothing: it is dropped, not refused, so a host that
705
+ // handed it back late goes on; only a call no message issued is refused.
706
+ const stale = given.filter((result) => !issued.has(result.toolCallId) && wasIssued(this, result.toolCallId));
707
+ const unknown = given.find((result) => !issued.has(result.toolCallId) && !stale.includes(result));
639
708
  if (unknown !== undefined)
640
709
  throw new ToolDetachmentError("unknown-tool-call", { sessionId, toolCallId: unknown.toolCallId });
710
+ const detached = states.get(this)?.detached;
711
+ for (const result of stale) {
712
+ detached?.delete(result.toolCallId);
713
+ reportStaleDetachedCall(this, result);
714
+ }
715
+ const pending = given.filter((result) => !stale.includes(result));
716
+ const answers = pending.map((result) => ({ toolCall: issued.get(result.toolCallId), result }));
641
717
  if (pending.length === 0 && !(endsOnDetachableTurn && [...issued.keys()].every((id) => recorded.has(id))))
642
718
  return;
643
- const detached = states.get(this)?.detached;
644
719
  for (const result of pending)
645
720
  detached?.delete(result.toolCallId);
646
721
  // The turn continues only once every detachable call it issued has a result; until then the results wait for it.
@@ -655,6 +730,7 @@ export const agentSessionDetachedToolMethods = {
655
730
  setToolDetachment,
656
731
  hasPendingDetachedTurn,
657
732
  takeDetachedToolCalls,
733
+ isWaitingOnDetachedResults,
658
734
  redispatchDetachedToolCalls,
659
735
  resumeDetachedTurn,
660
736
  };