@bastani/atomic 0.9.19-alpha.2 → 0.9.19-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +15 -0
  3. package/dist/builtin/intercom/broker/broker.ts +8 -0
  4. package/dist/builtin/intercom/broker/client.ts +18 -0
  5. package/dist/builtin/intercom/broker/send-handler.ts +9 -0
  6. package/dist/builtin/intercom/index.bundle.mjs +161 -30
  7. package/dist/builtin/intercom/package.json +1 -1
  8. package/dist/builtin/intercom/types.ts +2 -1
  9. package/dist/builtin/mcp/package.json +1 -1
  10. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  11. package/dist/builtin/subagents/README.md +14 -14
  12. package/dist/builtin/subagents/package.json +1 -1
  13. package/dist/builtin/subagents/skills/subagent/SKILL.md +14 -14
  14. package/dist/builtin/subagents/src/extension/index.bundle.mjs +142 -60
  15. package/dist/builtin/web-access/package.json +1 -1
  16. package/dist/builtin/workflows/CHANGELOG.md +33 -0
  17. package/dist/builtin/workflows/README.md +14 -15
  18. package/dist/builtin/workflows/builtin/{chunk-mygmtz6e.js → chunk-9k3ywfgd.js} +1 -1
  19. package/dist/builtin/workflows/builtin/{chunk-r9qq7xfj.js → chunk-ahbntmx2.js} +1 -1
  20. package/dist/builtin/workflows/builtin/{chunk-zggjyg5z.js → chunk-n8zysf1t.js} +1 -1
  21. package/dist/builtin/workflows/builtin/goal.js +2 -2
  22. package/dist/builtin/workflows/builtin/index.js +3 -3
  23. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  24. package/dist/builtin/workflows/package.json +5 -5
  25. package/dist/builtin/workflows/src/extension/index.bundle.mjs +171 -207
  26. package/dist/builtin/workflows/src/index.js +33 -6
  27. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -1
  28. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +1 -1
  29. package/dist/core/agent-session-auto-compaction.js +1 -1
  30. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  31. package/dist/core/agent-session-compaction.js +1 -1
  32. package/dist/core/agent-session-compaction.js.map +1 -1
  33. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  34. package/dist/core/agent-session-custom-message-commit.js +33 -2
  35. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  36. package/dist/core/agent-session-message-queue.d.ts +1 -1
  37. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  38. package/dist/core/agent-session-message-queue.js +22 -8
  39. package/dist/core/agent-session-message-queue.js.map +1 -1
  40. package/dist/core/agent-session-methods.d.ts +7 -1
  41. package/dist/core/agent-session-methods.d.ts.map +1 -1
  42. package/dist/core/agent-session-methods.js.map +1 -1
  43. package/dist/core/agent-session-persistent-custom-messages.d.ts +1 -1
  44. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  45. package/dist/core/agent-session-persistent-custom-messages.js +13 -3
  46. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  47. package/dist/core/agent-session-post-tool-compaction.js +1 -1
  48. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  49. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  50. package/dist/core/agent-session-prompt.js +83 -0
  51. package/dist/core/agent-session-prompt.js.map +1 -1
  52. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  53. package/dist/core/agent-session-queue-pause.js +11 -0
  54. package/dist/core/agent-session-queue-pause.js.map +1 -1
  55. package/dist/core/agent-session-tasks.d.ts +5 -0
  56. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  57. package/dist/core/agent-session-tasks.js +8 -1
  58. package/dist/core/agent-session-tasks.js.map +1 -1
  59. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  60. package/dist/core/agent-session-tool-hooks.js +2 -0
  61. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  62. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  63. package/dist/core/agent-session-tool-registry.js +12 -0
  64. package/dist/core/agent-session-tool-registry.js.map +1 -1
  65. package/dist/core/agent-session-transfer.d.ts.map +1 -1
  66. package/dist/core/agent-session-transfer.js +7 -0
  67. package/dist/core/agent-session-transfer.js.map +1 -1
  68. package/dist/core/agent-session-types.d.ts +2 -0
  69. package/dist/core/agent-session-types.d.ts.map +1 -1
  70. package/dist/core/agent-session-types.js +2 -0
  71. package/dist/core/agent-session-types.js.map +1 -1
  72. package/dist/core/agent-session.d.ts +4 -0
  73. package/dist/core/agent-session.d.ts.map +1 -1
  74. package/dist/core/agent-session.js +22 -0
  75. package/dist/core/agent-session.js.map +1 -1
  76. package/dist/core/extensions/context-types.d.ts +6 -0
  77. package/dist/core/extensions/context-types.d.ts.map +1 -1
  78. package/dist/core/extensions/context-types.js.map +1 -1
  79. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  80. package/dist/core/extensions/loader-api.js +3 -0
  81. package/dist/core/extensions/loader-api.js.map +1 -1
  82. package/dist/core/extensions/loader-host-modules.d.ts +1 -1
  83. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  84. package/dist/core/extensions/loader-host-modules.js +2 -1
  85. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  86. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  87. package/dist/core/extensions/loader-virtual-modules.js +4 -1
  88. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  89. package/dist/core/extensions/runner-context.d.ts +1 -1
  90. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  91. package/dist/core/extensions/runner-context.js +9 -3
  92. package/dist/core/extensions/runner-context.js.map +1 -1
  93. package/dist/core/extensions/runner.js +1 -1
  94. package/dist/core/extensions/runner.js.map +1 -1
  95. package/dist/core/extensions/workflow-events.d.ts +1 -1
  96. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  97. package/dist/core/extensions/workflow-events.js.map +1 -1
  98. package/dist/core/retry-policy.d.ts +1 -0
  99. package/dist/core/retry-policy.d.ts.map +1 -1
  100. package/dist/core/retry-policy.js +2 -1
  101. package/dist/core/retry-policy.js.map +1 -1
  102. package/dist/core/sdk-exports.d.ts +1 -1
  103. package/dist/core/sdk-exports.d.ts.map +1 -1
  104. package/dist/core/sdk-exports.js +1 -1
  105. package/dist/core/sdk-exports.js.map +1 -1
  106. package/dist/core/settings-manager-basic-accessors.d.ts +6 -3
  107. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  108. package/dist/core/settings-manager-basic-accessors.js +25 -8
  109. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  110. package/dist/core/settings-manager.d.ts +1 -1
  111. package/dist/core/settings-manager.d.ts.map +1 -1
  112. package/dist/core/settings-manager.js.map +1 -1
  113. package/dist/core/settings-types.d.ts +6 -0
  114. package/dist/core/settings-types.d.ts.map +1 -1
  115. package/dist/core/settings-types.js.map +1 -1
  116. package/dist/core/slash-commands.d.ts.map +1 -1
  117. package/dist/core/slash-commands.js +4 -5
  118. package/dist/core/slash-commands.js.map +1 -1
  119. package/dist/core/tasks/agent-adapter.d.ts +14 -2
  120. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  121. package/dist/core/tasks/agent-adapter.js +45 -4
  122. package/dist/core/tasks/agent-adapter.js.map +1 -1
  123. package/dist/core/tasks/completion.d.ts.map +1 -1
  124. package/dist/core/tasks/completion.js +5 -1
  125. package/dist/core/tasks/completion.js.map +1 -1
  126. package/dist/core/tasks/pause.d.ts +4 -0
  127. package/dist/core/tasks/pause.d.ts.map +1 -0
  128. package/dist/core/tasks/pause.js +49 -0
  129. package/dist/core/tasks/pause.js.map +1 -0
  130. package/dist/core/tasks/supervisor.d.ts +3 -1
  131. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  132. package/dist/core/tasks/supervisor.js +48 -22
  133. package/dist/core/tasks/supervisor.js.map +1 -1
  134. package/dist/core/tools/bash-pty-native.d.ts +16 -2
  135. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  136. package/dist/core/tools/bash-pty-native.js +82 -0
  137. package/dist/core/tools/bash-pty-native.js.map +1 -1
  138. package/dist/core/tools/bash.d.ts +15 -2
  139. package/dist/core/tools/bash.d.ts.map +1 -1
  140. package/dist/core/tools/bash.js +49 -4
  141. package/dist/core/tools/bash.js.map +1 -1
  142. package/dist/core/tools/index.d.ts +4 -1
  143. package/dist/core/tools/index.d.ts.map +1 -1
  144. package/dist/core/tools/index.js +12 -0
  145. package/dist/core/tools/index.js.map +1 -1
  146. package/dist/core/tools/kill.d.ts +17 -0
  147. package/dist/core/tools/kill.d.ts.map +1 -0
  148. package/dist/core/tools/kill.js +49 -0
  149. package/dist/core/tools/kill.js.map +1 -0
  150. package/dist/core/tools/powershell.d.ts +84 -28
  151. package/dist/core/tools/powershell.d.ts.map +1 -1
  152. package/dist/core/tools/powershell.js +11 -3
  153. package/dist/core/tools/powershell.js.map +1 -1
  154. package/dist/core/tools/resource-selectors.d.ts +1 -1
  155. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  156. package/dist/core/tools/resource-selectors.js +7 -4
  157. package/dist/core/tools/resource-selectors.js.map +1 -1
  158. package/dist/core/workflow-stage-admission.d.ts +14 -0
  159. package/dist/core/workflow-stage-admission.d.ts.map +1 -1
  160. package/dist/core/workflow-stage-admission.js +63 -3
  161. package/dist/core/workflow-stage-admission.js.map +1 -1
  162. package/dist/index.d.ts +2 -2
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +1 -1
  165. package/dist/index.js.map +1 -1
  166. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  167. package/dist/modes/interactive/components/chat-session-host.js +3 -2
  168. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  169. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  170. package/dist/modes/interactive/components/task-row.js +8 -1
  171. package/dist/modes/interactive/components/task-row.js.map +1 -1
  172. package/docs/background-tasks.md +31 -2
  173. package/docs/compaction.md +20 -0
  174. package/docs/computer-use.md +390 -0
  175. package/docs/development.md +23 -74
  176. package/docs/docs.json +1 -0
  177. package/docs/extensions.md +15 -1
  178. package/docs/herdr.md +26 -77
  179. package/docs/index.md +1 -0
  180. package/docs/intercom.md +14 -2
  181. package/docs/models/evals.md +2 -0
  182. package/docs/models/model-selection.md +10 -7
  183. package/docs/quickstart.md +1 -1
  184. package/docs/sdk.md +11 -1
  185. package/docs/settings.md +24 -0
  186. package/docs/subagents.md +10 -6
  187. package/docs/tmux.md +2 -0
  188. package/docs/tools.md +11 -1
  189. package/docs/usage.md +1 -1
  190. package/docs/workflows/api-reference.md +5 -4
  191. package/docs/workflows/authoring.md +3 -3
  192. package/docs/workflows/operations.md +44 -33
  193. package/docs/workflows/reliable-design.md +3 -3
  194. package/docs/workflows/verification.md +99 -40
  195. package/docs/workflows.md +4 -2
  196. package/npm-shrinkwrap.json +59 -59
  197. package/package.json +3 -3
@@ -1656,7 +1656,7 @@ class WorkflowObservationRuntime {
1656
1656
  const run = this.runs().find((candidate) => candidate.id === runId);
1657
1657
  if (!run)
1658
1658
  return;
1659
- if ((action === "quit" || action === "kill" || action === "interrupt") && this.liveRunIds.has(runId))
1659
+ if ((action === "quit" || action === "kill" || action === "pause") && this.liveRunIds.has(runId))
1660
1660
  this.stoppingRunIds.add(runId);
1661
1661
  if (action === "resume")
1662
1662
  this.stoppingRunIds.delete(runId);
@@ -4830,6 +4830,7 @@ function durableStageCheckpointMetadata(stage, run, sourceOrder) {
4830
4830
  ...stage.sessionFile !== undefined ? { sessionFile: stage.sessionFile } : {},
4831
4831
  ...stage.durationMs !== undefined ? { durationMs: stage.durationMs } : {},
4832
4832
  ...stage.model !== undefined ? { model: stage.model } : {},
4833
+ ...stage.thinkingLevel !== undefined ? { thinkingLevel: stage.thinkingLevel } : {},
4833
4834
  ...stage.attemptedModels !== undefined ? { attemptedModels: [...stage.attemptedModels] } : {},
4834
4835
  ...stage.modelAttempts !== undefined ? { modelAttempts: [...stage.modelAttempts] } : {},
4835
4836
  ...stage.structured !== undefined ? { structured: stage.structured } : {},
@@ -5807,6 +5808,7 @@ function completeTaskResult(name, base, checkpoint) {
5807
5808
  ...base.sessionFile !== undefined || checkpoint.sessionFile !== undefined ? { sessionFile: base.sessionFile ?? checkpoint.sessionFile } : {},
5808
5809
  ...base.artifacts !== undefined || checkpoint.artifacts !== undefined ? { artifacts: [...base.artifacts ?? checkpoint.artifacts ?? []] } : {},
5809
5810
  ...base.model !== undefined || checkpoint.model !== undefined ? { model: base.model ?? checkpoint.model } : {},
5811
+ ...base.thinkingLevel !== undefined || checkpoint.thinkingLevel !== undefined ? { thinkingLevel: base.thinkingLevel ?? checkpoint.thinkingLevel } : {},
5810
5812
  ...base.attemptedModels !== undefined || checkpoint.attemptedModels !== undefined ? { attemptedModels: [...base.attemptedModels ?? checkpoint.attemptedModels ?? []] } : {},
5811
5813
  ...base.modelAttempts !== undefined || checkpoint.modelAttempts !== undefined ? { modelAttempts: [...base.modelAttempts ?? checkpoint.modelAttempts ?? []] } : {},
5812
5814
  ...base.warnings !== undefined || checkpoint.warnings !== undefined ? { warnings: [...base.warnings ?? checkpoint.warnings ?? []] } : {}
@@ -5907,6 +5909,7 @@ function taskCheckpointMetadata(result) {
5907
5909
  ...result.sessionId !== undefined ? { sessionId: result.sessionId } : {},
5908
5910
  ...result.sessionFile !== undefined ? { sessionFile: result.sessionFile } : {},
5909
5911
  ...result.model !== undefined ? { model: result.model } : {},
5912
+ ...result.thinkingLevel !== undefined ? { thinkingLevel: result.thinkingLevel } : {},
5910
5913
  ...result.attemptedModels !== undefined ? { attemptedModels: [...result.attemptedModels] } : {},
5911
5914
  ...result.modelAttempts !== undefined ? { modelAttempts: [...result.modelAttempts] } : {},
5912
5915
  ...result.structured !== undefined ? { structured: result.structured } : {},
@@ -5936,6 +5939,7 @@ function mergeCheckpointHydrationMetadata(replayValueCheckpoint, checkpoints) {
5936
5939
  ...replayValueCheckpoint.sessionId === undefined ? metadataValue(checkpoints, "sessionId") : {},
5937
5940
  ...replayValueCheckpoint.sessionFile === undefined ? metadataValue(checkpoints, "sessionFile") : {},
5938
5941
  ...replayValueCheckpoint.model === undefined ? metadataValue(checkpoints, "model") : {},
5942
+ ...replayValueCheckpoint.thinkingLevel === undefined ? metadataValue(checkpoints, "thinkingLevel") : {},
5939
5943
  ...replayValueCheckpoint.attemptedModels === undefined ? metadataValue(checkpoints, "attemptedModels") : {},
5940
5944
  ...replayValueCheckpoint.modelAttempts === undefined ? metadataValue(checkpoints, "modelAttempts") : {},
5941
5945
  ...replayValueCheckpoint.structured === undefined ? metadataValue(checkpoints, "structured") : {},
@@ -6025,6 +6029,7 @@ function recordCachedStageIntoStore(store, runId, name, replayKey, output, compl
6025
6029
  ...checkpoint?.sessionId !== undefined ? { sessionId: checkpoint.sessionId } : {},
6026
6030
  ...checkpoint?.sessionFile !== undefined ? { sessionFile: checkpoint.sessionFile } : {},
6027
6031
  ...checkpoint?.model !== undefined ? { model: checkpoint.model } : {},
6032
+ ...checkpoint?.thinkingLevel !== undefined ? { thinkingLevel: checkpoint.thinkingLevel } : {},
6028
6033
  ...checkpoint?.attemptedModels !== undefined ? { attemptedModels: checkpoint.attemptedModels } : {},
6029
6034
  ...checkpoint?.modelAttempts !== undefined ? { modelAttempts: checkpoint.modelAttempts } : {},
6030
6035
  ...checkpoint?.structured !== undefined ? { structured: checkpoint.structured } : {},
@@ -10462,7 +10467,7 @@ class ConcurrencyLimiter {
10462
10467
  }
10463
10468
  }
10464
10469
  function createRunLimiter(defaultConcurrency) {
10465
- return new ConcurrencyLimiter(defaultConcurrency ?? 4);
10470
+ return new ConcurrencyLimiter(defaultConcurrency ?? 3);
10466
10471
  }
10467
10472
 
10468
10473
  // dist/builtin/workflows/src/shared/abort.ts
@@ -11084,6 +11089,7 @@ function createTaskPrimitive(runtime) {
11084
11089
  ...sessionId !== undefined ? { sessionId } : {},
11085
11090
  ...stage.sessionFile !== undefined ? { sessionFile: stage.sessionFile } : {},
11086
11091
  ...stageMeta.model !== undefined ? { model: stageMeta.model } : {},
11092
+ ...stageMeta.thinkingLevel !== undefined ? { thinkingLevel: stageMeta.thinkingLevel } : {},
11087
11093
  ...stageMeta.attemptedModels !== undefined ? { attemptedModels: stageMeta.attemptedModels } : {},
11088
11094
  ...stageMeta.modelAttempts !== undefined ? { modelAttempts: stageMeta.modelAttempts } : {},
11089
11095
  ...stageMeta.warnings !== undefined ? { warnings: stageMeta.warnings } : {}
@@ -11925,6 +11931,7 @@ function mergeStageDraft(existing, checkpoint, sequence) {
11925
11931
  ...valueOrExisting("endedAt", checkpoint, existing),
11926
11932
  ...valueOrExisting("durationMs", checkpoint, existing),
11927
11933
  ...valueOrExisting("model", checkpoint, existing),
11934
+ ...valueOrExisting("thinkingLevel", checkpoint, existing),
11928
11935
  ...valueOrExisting("attemptedModels", checkpoint, existing),
11929
11936
  ...valueOrExisting("modelAttempts", checkpoint, existing),
11930
11937
  ...checkpoint.topology !== undefined ? { topology: checkpoint.topology } : existing?.topology !== undefined ? { topology: existing.topology } : {}
@@ -12321,6 +12328,7 @@ function stageSnapshotFromDraft(draft, id, parentIds) {
12321
12328
  ...draft.sessionId !== undefined ? { sessionId: draft.sessionId } : {},
12322
12329
  ...draft.sessionFile !== undefined ? { sessionFile: draft.sessionFile } : {},
12323
12330
  ...draft.model !== undefined ? { model: draft.model } : {},
12331
+ ...draft.thinkingLevel !== undefined ? { thinkingLevel: draft.thinkingLevel } : {},
12324
12332
  ...draft.attemptedModels !== undefined ? { attemptedModels: draft.attemptedModels } : {},
12325
12333
  ...draft.modelAttempts !== undefined ? { modelAttempts: draft.modelAttempts } : {}
12326
12334
  };
@@ -14284,7 +14292,7 @@ function createReplayStageContext(input) {
14284
14292
  return replaySource.model;
14285
14293
  },
14286
14294
  get thinkingLevel() {
14287
- return;
14295
+ return replaySource.thinkingLevel;
14288
14296
  },
14289
14297
  get messages() {
14290
14298
  return [];
@@ -14310,6 +14318,7 @@ function createReplayStageContext(input) {
14310
14318
  __pendingMessageCount: () => 0,
14311
14319
  __modelFallbackMeta: () => ({
14312
14320
  ...replaySource.model !== undefined ? { model: replaySource.model } : {},
14321
+ ...replaySource.thinkingLevel !== undefined ? { thinkingLevel: replaySource.thinkingLevel } : {},
14313
14322
  ...replaySource.attemptedModels !== undefined ? { attemptedModels: replaySource.attemptedModels } : {},
14314
14323
  ...replaySource.modelAttempts !== undefined ? { modelAttempts: replaySource.modelAttempts } : {}
14315
14324
  }),
@@ -15448,7 +15457,8 @@ class StageSessionPause {
15448
15457
  abortBoundary: Promise.withResolvers(),
15449
15458
  runnerOwnedDeliveries: new Set,
15450
15459
  confirmed: false,
15451
- ...nativeQueuePause === undefined ? {} : { nativeQueuePause }
15460
+ ...nativeQueuePause === undefined ? {} : { nativeQueuePause },
15461
+ ...session?.pauseTasks && session.resumeTasks ? { taskControl: session } : {}
15452
15462
  };
15453
15463
  request.deferred.promise.catch(() => {});
15454
15464
  request.abortBoundary.promise.catch(() => {});
@@ -15456,7 +15466,11 @@ class StageSessionPause {
15456
15466
  let failed = false;
15457
15467
  try {
15458
15468
  request.nativeQueuePause?.pauseQueuedMessages();
15459
- await session?.abort();
15469
+ const tasks = request.taskControl?.pauseTasks?.();
15470
+ const settled = await Promise.allSettled([tasks, (async () => session?.abort())()]);
15471
+ for (const result of settled)
15472
+ if (result.status === "rejected")
15473
+ throw result.reason;
15460
15474
  request.abortBoundary.resolve();
15461
15475
  await request.abortBoundary.promise;
15462
15476
  request.confirmed = true;
@@ -15464,6 +15478,7 @@ class StageSessionPause {
15464
15478
  failed = true;
15465
15479
  request.abortBoundary.reject(error);
15466
15480
  request.deferred.reject(error);
15481
+ request.taskControl?.resumeTasks?.();
15467
15482
  await this.rollbackNativePause(request.nativeQueuePause);
15468
15483
  throw error;
15469
15484
  } finally {
@@ -15531,6 +15546,7 @@ class StageSessionPause {
15531
15546
  if (releaseAdmitted)
15532
15547
  return;
15533
15548
  beforeRelease?.();
15549
+ request.taskControl?.resumeTasks?.();
15534
15550
  releaseAdmitted = true;
15535
15551
  };
15536
15552
  let releasedQueuedMessages;
@@ -15627,6 +15643,9 @@ async function rejectDisposedCreatedSession(result, stageName) {
15627
15643
  class StageSessionReplacement {
15628
15644
  previous;
15629
15645
  cleanups = new Set;
15646
+ get retiringSession() {
15647
+ return this.previous;
15648
+ }
15630
15649
  retire(session) {
15631
15650
  this.previous = session;
15632
15651
  }
@@ -16011,7 +16030,7 @@ class StageSessionController {
16011
16030
  pendingThinkingLevel;
16012
16031
  pendingListeners = new Set;
16013
16032
  listenerUnsubscribes = new Map;
16014
- pauseControl = new StageSessionPause(() => this.session);
16033
+ pauseControl = new StageSessionPause(() => this.session ?? this.replacement.retiringSession);
16015
16034
  hasExplicitModelFallbackConfig;
16016
16035
  candidatesPromise;
16017
16036
  activeCandidateIndex;
@@ -16290,8 +16309,10 @@ class StageSessionController {
16290
16309
  currentModelFallbackMeta() {
16291
16310
  const attemptedModels = this.modelAttempts.map((attempt) => attempt.model);
16292
16311
  const model = this.selectedModel ?? workflowModelId(this.session?.model);
16312
+ const thinkingLevel = this.session?.thinkingLevel ?? this.pendingThinkingLevel;
16293
16313
  return {
16294
16314
  ...model !== undefined ? { model } : {},
16315
+ ...thinkingLevel !== undefined ? { thinkingLevel } : {},
16295
16316
  ...attemptedModels.length > 0 ? { attemptedModels } : {},
16296
16317
  ...this.modelAttempts.length > 0 ? { modelAttempts: [...this.modelAttempts] } : {},
16297
16318
  ...this.modelWarnings.length > 0 ? { warnings: [...this.modelWarnings] } : {}
@@ -17661,6 +17682,8 @@ function createWorkflowStageFactory(input) {
17661
17682
  ...replaySource.result !== undefined ? { result: replaySource.result } : {},
17662
17683
  ...replaySource.sessionId !== undefined ? { sessionId: replaySource.sessionId } : {},
17663
17684
  ...replaySource.sessionFile !== undefined ? { sessionFile: replaySource.sessionFile } : {},
17685
+ ...replaySource.model !== undefined ? { model: replaySource.model } : {},
17686
+ ...replaySource.thinkingLevel !== undefined ? { thinkingLevel: replaySource.thinkingLevel } : {},
17664
17687
  replayedFromStageId: replaySource.id,
17665
17688
  replayed: true
17666
17689
  } : {},
@@ -17685,6 +17708,10 @@ function createWorkflowStageFactory(input) {
17685
17708
  const applyModelFallbackMeta = (meta) => {
17686
17709
  if (meta.model !== undefined)
17687
17710
  stageSnapshot.model = meta.model;
17711
+ if (meta.thinkingLevel !== undefined)
17712
+ stageSnapshot.thinkingLevel = meta.thinkingLevel;
17713
+ else
17714
+ delete stageSnapshot.thinkingLevel;
17688
17715
  if (meta.attemptedModels !== undefined)
17689
17716
  stageSnapshot.attemptedModels = meta.attemptedModels;
17690
17717
  if (meta.modelAttempts !== undefined)
@@ -31,7 +31,7 @@ export type RunStatus = "pending" | "running" | "paused" | WorkflowExitStatus |
31
31
  export type WorkflowActor = "user" | "agent";
32
32
  export type WorkflowDetailsMode = "named" | "inspection" | "control";
33
33
  export type WorkflowDetailsStatus = "accepted" | "running" | WorkflowExitStatus | "killed" | "noop";
34
- export type WorkflowAction = "list" | "get" | "inputs" | "run" | "status" | "interrupt" | "resume";
34
+ export type WorkflowAction = "list" | "get" | "inputs" | "run" | "status" | "pause" | "resume";
35
35
  type WorkflowExitOutputValues<TOutputs extends WorkflowOutputValues = WorkflowOutputValues> = [keyof TOutputs] extends [
36
36
  never
37
37
  ] ? Readonly<Record<string, never>> : Partial<TOutputs>;
@@ -327,6 +327,7 @@ export interface WorkflowTaskResult extends WorkflowTaskContext {
327
327
  readonly sessionFile?: string;
328
328
  readonly artifacts?: readonly WorkflowArtifact[];
329
329
  readonly model?: string;
330
+ readonly thinkingLevel?: string;
330
331
  readonly attemptedModels?: readonly string[];
331
332
  readonly modelAttempts?: readonly WorkflowModelAttempt[];
332
333
  readonly warnings?: readonly string[];
@@ -117,7 +117,7 @@ export type WorkflowToolThrowOptions = WorkflowToolOptions & {
117
117
  * Cancellation handle handed to every `ctx.tool` callback.
118
118
  *
119
119
  * The signal aborts when the run is cancelled, when the run is gracefully quit,
120
- * or when this single tool node is aborted through `/workflow quit|interrupt`
120
+ * or when this single tool node is aborted through the workflow quit/pause action
121
121
  * with the node's id or name. Callbacks that forward it to `fetch`, a child
122
122
  * process, or a network client unblock promptly; callbacks that ignore it are
123
123
  * abandoned after a bounded wait.
@@ -43,7 +43,7 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
43
43
  // false. Only the live turn-completion path may auto-continue a truncated
44
44
  // response — before a fresh user prompt we must not resume the old turn.
45
45
  const isLiveTurnCompletion = skipAbortedCheck;
46
- const settings = this.settingsManager.getCompactionSettings();
46
+ const settings = this.settingsManager.getCompactionSettings(this.model);
47
47
  const contextWindow = this.model?.contextWindow ?? 0;
48
48
  // Skip overflow handling if the message came from a different model.
49
49
  // This handles the case where user switched from a smaller-context model (e.g. opus)
@@ -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,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,C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age } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tshouldCompact,\n} 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 direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\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\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\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\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: 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\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling 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 !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\tconst contextOverflow = sameModel && isContextOverflow(assistantMessage, contextWindow);\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\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: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion && sameModel && isRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\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\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\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\t: \"Response truncation recovery stopped after one retry.\";\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\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tif (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\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\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});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\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 length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\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\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\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(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\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\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\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()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\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\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\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 reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that 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\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\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\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\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: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\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\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\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.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = 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,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;A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";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tshouldCompact,\n} 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 direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\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\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\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\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: 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(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling 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 !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\tconst contextOverflow = sameModel && isContextOverflow(assistantMessage, contextWindow);\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\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: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion && sameModel && isRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\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\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\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\t: \"Response truncation recovery stopped after one retry.\";\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\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tif (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\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\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});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\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 length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\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\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\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(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\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\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\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()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\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\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\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 reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that 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\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\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\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\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: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\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\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\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.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = 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"]}
@@ -52,7 +52,7 @@ export async function _applyVerbatimCompaction(options) {
52
52
  throw new Error(formatNoModelSelectedMessage());
53
53
  const model = this.model;
54
54
  const pathEntries = this.sessionManager.getBranch();
55
- const settings = this.settingsManager.getCompactionSettings();
55
+ const settings = this.settingsManager.getCompactionSettings(model);
56
56
  // A sub-minimum region is admitted only when the caller already knows the
57
57
  // context does not fit: overflow recovery, or a post-tool preflight over the
58
58
  // provider hard input limit. A threshold crossing that still fits must not
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,GAM5B,MAAM,uBAAuB,CAAC;AAQ/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;QAA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AC,IAAI,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC,CAAC;SACD,OAAO,CAAC,GAAG,EAAE;QACb,+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;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 { Usage } from \"@bastani/pi-ai/compat\";\nimport 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 {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\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\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 }\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\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};\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\t...(run.usage ? { usage: run.usage } : {}),\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\tcompacted.usage,\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...(compacted.usage ? { usage: compacted.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: 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\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 = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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: Partial<VerbatimCompactionParameters>,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\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\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(\n\tthis: AgentSession,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n): Promise<VerbatimCompactionResult> {\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\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 = Promise.resolve()\n\t\t.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\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t})\n\t\t.finally(() => {\n\t\t\tclearOwnedManualCompactionState.call(this, controller);\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":"AAKA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,GAM5B,MAAM,uBAAuB,CAAC;AAQ/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,wBA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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 { Usage } from \"@bastani/pi-ai/compat\";\nimport 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 {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\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(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 }\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\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};\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\t...(run.usage ? { usage: run.usage } : {}),\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\tcompacted.usage,\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...(compacted.usage ? { usage: compacted.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: 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\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 = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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: Partial<VerbatimCompactionParameters>,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\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\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(\n\tthis: AgentSession,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n): Promise<VerbatimCompactionResult> {\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\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 = Promise.resolve()\n\t\t.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\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t})\n\t\t.finally(() => {\n\t\t\tclearOwnedManualCompactionState.call(this, controller);\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-custom-message-commit.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAO9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAA8B,MAAM,eAAe,CAAC;AAO/E,6EAA6E;AAC7E,wBAAsB,2BAA2B,CAAC,CAAC,EAClD,OAAO,EAAE,YAAY,EACrB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CA4Ef;AAED,wBAAgB,4BAA4B,CAAC,CAAC,EAC7C,IAAI,EAAE,YAAY,EAClB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,+EAA+E;AAC/E,wBAAsB,4BAA4B,CAAC,CAAC,EACnD,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CA8Cf;AAED,wBAAgB,6BAA6B,CAAC,CAAC,EAC9C,IAAI,EAAE,YAAY,EAClB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,eAAO,MAAM,sCAAsC;;;CAGlD,CAAC"}
1
+ {"version":3,"file":"agent-session-custom-message-commit.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAO9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAA8B,MAAM,eAAe,CAAC;AA8B/E,6EAA6E;AAC7E,wBAAsB,2BAA2B,CAAC,CAAC,EAClD,OAAO,EAAE,YAAY,EACrB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CA0Ff;AAED,wBAAgB,4BAA4B,CAAC,CAAC,EAC7C,IAAI,EAAE,YAAY,EAClB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,+EAA+E;AAC/E,wBAAsB,4BAA4B,CAAC,CAAC,EACnD,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAiDf;AAED,wBAAgB,6BAA6B,CAAC,CAAC,EAC9C,IAAI,EAAE,YAAY,EAClB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,eAAO,MAAM,sCAAsC;;;CAGlD,CAAC"}