@bastani/atomic 0.9.73 → 0.9.74

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 (193) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/CHANGELOG.md +32 -0
  7. package/dist/builtin/workflows/README.md +2 -2
  8. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  9. package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
  10. package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
  13. package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
  14. package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
  15. package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
  18. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  19. package/dist/builtin/workflows/builtin/goal.js +4 -4
  20. package/dist/builtin/workflows/builtin/index.js +9 -9
  21. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  22. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  23. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  24. package/dist/builtin/workflows/package.json +1 -1
  25. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  26. package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
  27. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
  28. package/dist/builtin/workflows/src/index.js +393 -62
  29. package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
  30. package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
  31. package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
  32. package/dist/config.d.ts +2 -0
  33. package/dist/config.d.ts.map +1 -1
  34. package/dist/config.js +4 -0
  35. package/dist/config.js.map +1 -1
  36. package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
  37. package/dist/core/agent-session-background-compaction.js +2 -1
  38. package/dist/core/agent-session-background-compaction.js.map +1 -1
  39. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  40. package/dist/core/agent-session-compaction.js +98 -4
  41. package/dist/core/agent-session-compaction.js.map +1 -1
  42. package/dist/core/agent-session-detached-tools.d.ts +20 -5
  43. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  44. package/dist/core/agent-session-detached-tools.js +97 -21
  45. package/dist/core/agent-session-detached-tools.js.map +1 -1
  46. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  47. package/dist/core/agent-session-message-queue.js +2 -1
  48. package/dist/core/agent-session-message-queue.js.map +1 -1
  49. package/dist/core/agent-session-methods.d.ts +3 -1
  50. package/dist/core/agent-session-methods.d.ts.map +1 -1
  51. package/dist/core/agent-session-methods.js.map +1 -1
  52. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  53. package/dist/core/agent-session-persistent-custom-messages.js +12 -4
  54. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  55. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  56. package/dist/core/agent-session-prompt.js +33 -0
  57. package/dist/core/agent-session-prompt.js.map +1 -1
  58. package/dist/core/compaction/background-compaction.d.ts +11 -5
  59. package/dist/core/compaction/background-compaction.d.ts.map +1 -1
  60. package/dist/core/compaction/background-compaction.js +19 -10
  61. package/dist/core/compaction/background-compaction.js.map +1 -1
  62. package/dist/core/compaction/compaction-boundary.d.ts +10 -0
  63. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  64. package/dist/core/compaction/compaction-boundary.js +30 -2
  65. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  66. package/dist/core/compaction/compaction-runner.d.ts +7 -0
  67. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  68. package/dist/core/compaction/compaction-runner.js +13 -5
  69. package/dist/core/compaction/compaction-runner.js.map +1 -1
  70. package/dist/core/compaction/compaction-types.d.ts +1 -1
  71. package/dist/core/compaction/compaction-types.js +1 -1
  72. package/dist/core/compaction/compaction-types.js.map +1 -1
  73. package/dist/core/compaction/deleted-ranges.d.ts +17 -2
  74. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  75. package/dist/core/compaction/deleted-ranges.js +44 -5
  76. package/dist/core/compaction/deleted-ranges.js.map +1 -1
  77. package/dist/core/compaction/history-recall.d.ts +32 -0
  78. package/dist/core/compaction/history-recall.d.ts.map +1 -0
  79. package/dist/core/compaction/history-recall.js +275 -0
  80. package/dist/core/compaction/history-recall.js.map +1 -0
  81. package/dist/core/compaction/index.d.ts +2 -0
  82. package/dist/core/compaction/index.d.ts.map +1 -1
  83. package/dist/core/compaction/index.js +2 -0
  84. package/dist/core/compaction/index.js.map +1 -1
  85. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  86. package/dist/core/compaction/pi-summary-fallback.js +1 -0
  87. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  88. package/dist/core/compaction/planner-outcome.d.ts +14 -0
  89. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  90. package/dist/core/compaction/planner-outcome.js +8 -0
  91. package/dist/core/compaction/planner-outcome.js.map +1 -1
  92. package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
  93. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  94. package/dist/core/compaction/range-planner-diagnostics.js +67 -24
  95. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  96. package/dist/core/compaction/range-planner.d.ts +7 -4
  97. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  98. package/dist/core/compaction/range-planner.js +43 -19
  99. package/dist/core/compaction/range-planner.js.map +1 -1
  100. package/dist/core/compaction/refusal-recovery.d.ts +27 -0
  101. package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
  102. package/dist/core/compaction/refusal-recovery.js +65 -0
  103. package/dist/core/compaction/refusal-recovery.js.map +1 -0
  104. package/dist/core/compaction/region-trimming.d.ts +23 -0
  105. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  106. package/dist/core/compaction/region-trimming.js +59 -15
  107. package/dist/core/compaction/region-trimming.js.map +1 -1
  108. package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
  109. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
  110. package/dist/core/compaction/structured-compaction-input.js +30 -17
  111. package/dist/core/compaction/structured-compaction-input.js.map +1 -1
  112. package/dist/core/compaction/transcript-serialization.d.ts +9 -3
  113. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  114. package/dist/core/compaction/transcript-serialization.js +18 -10
  115. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  116. package/dist/core/messages.d.ts +5 -1
  117. package/dist/core/messages.d.ts.map +1 -1
  118. package/dist/core/messages.js +21 -3
  119. package/dist/core/messages.js.map +1 -1
  120. package/dist/core/session-manager-core.js +1 -1
  121. package/dist/core/session-manager-core.js.map +1 -1
  122. package/dist/core/session-manager-history.d.ts +1 -1
  123. package/dist/core/session-manager-history.d.ts.map +1 -1
  124. package/dist/core/session-manager-history.js +2 -5
  125. package/dist/core/session-manager-history.js.map +1 -1
  126. package/dist/core/settings-defaults.d.ts +2 -0
  127. package/dist/core/settings-defaults.d.ts.map +1 -1
  128. package/dist/core/settings-defaults.js +2 -0
  129. package/dist/core/settings-defaults.js.map +1 -1
  130. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  131. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  132. package/dist/core/settings-manager-basic-accessors.js +3 -0
  133. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  134. package/dist/core/settings-schema.d.ts +2 -0
  135. package/dist/core/settings-schema.d.ts.map +1 -1
  136. package/dist/core/settings-schema.js +4 -0
  137. package/dist/core/settings-schema.js.map +1 -1
  138. package/dist/core/storage/session/conformance.d.ts.map +1 -1
  139. package/dist/core/storage/session/conformance.js +12 -0
  140. package/dist/core/storage/session/conformance.js.map +1 -1
  141. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.js +3 -0
  143. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  144. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  145. package/dist/core/storage/session/legacy-session-store.js +3 -0
  146. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  147. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  148. package/dist/core/storage/session/memory-session-store.js +3 -0
  149. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  150. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  151. package/dist/core/storage/session/sql-session-store.js +12 -3
  152. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  153. package/dist/core/storage/session/types.d.ts +3 -0
  154. package/dist/core/storage/session/types.d.ts.map +1 -1
  155. package/dist/core/storage/session/types.js +3 -0
  156. package/dist/core/storage/session/types.js.map +1 -1
  157. package/dist/core/tools/history-protocol.d.ts +3 -0
  158. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  159. package/dist/core/tools/history-protocol.js +7 -87
  160. package/dist/core/tools/history-protocol.js.map +1 -1
  161. package/dist/core/tools/history-transcript.d.ts +24 -0
  162. package/dist/core/tools/history-transcript.d.ts.map +1 -0
  163. package/dist/core/tools/history-transcript.js +110 -0
  164. package/dist/core/tools/history-transcript.js.map +1 -0
  165. package/dist/index.d.ts +1 -1
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/main-session.d.ts.map +1 -1
  169. package/dist/main-session.js +21 -5
  170. package/dist/main-session.js.map +1 -1
  171. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  172. package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
  173. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  174. package/dist/modes/interactive/interactive-render-chat.js +2 -2
  175. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  176. package/dist/session-id-target.d.ts +1 -0
  177. package/dist/session-id-target.d.ts.map +1 -1
  178. package/dist/session-id-target.js +3 -0
  179. package/dist/session-id-target.js.map +1 -1
  180. package/docs/compaction/reference.md +3 -2
  181. package/docs/compaction.md +35 -7
  182. package/docs/development.md +1 -1
  183. package/docs/sdk/reference.md +6 -5
  184. package/docs/sessions.md +3 -3
  185. package/docs/settings.md +3 -0
  186. package/docs/storage.md +2 -0
  187. package/docs/workflows/api-reference.md +15 -3
  188. package/docs/workflows/authoring.md +2 -2
  189. package/docs/workflows/operations.md +1 -0
  190. package/docs/workflows/reliable-design.md +1 -1
  191. package/npm-shrinkwrap.json +32 -32
  192. package/package.json +3 -3
  193. package/schemas/settings.schema.json +5 -0
@@ -74,16 +74,14 @@ function isPassiveEntry(entry) {
74
74
  entry.type === "context_edit");
75
75
  }
76
76
  /**
77
- * Path index of the last entry a background task may freeze, or -1 when nothing is safe.
78
- *
79
- * Walks the trailing run of tool calls and tool results backwards, tracking which calls have a
80
- * result, and cuts before the earliest assistant message in that run with an unanswered call: it and
81
- * everything after it stay out of the prefix (infinity's `safe_spawn_point`). Any other message ends
82
- * the run. A safe point never lands on a label, which a branched copy drops.
77
+ * Path index of the earliest assistant message of the trailing run of tool calls and tool results that has a call
78
+ * without a result, or undefined when every call of the run has one. Walks the run backwards, tracking which calls
79
+ * have a result; any other message ends the run. `awaitedEntryId` names a turn the context still waits on a result
80
+ * for whatever entries follow it, such as a custom message that was delivered meanwhile.
83
81
  */
84
- export function findBackgroundCompactionSafePoint(branch) {
82
+ export function findUnansweredToolCall(branch, awaitedEntryId) {
85
83
  const answered = new Set();
86
- let safe = branch.length;
84
+ let unanswered;
87
85
  for (let index = branch.length - 1; index >= 0; index--) {
88
86
  const entry = branch[index];
89
87
  if (isPassiveEntry(entry))
@@ -96,9 +94,20 @@ export function findBackgroundCompactionSafePoint(branch) {
96
94
  if (calls.length === 0)
97
95
  break;
98
96
  if (calls.some((id) => !answered.has(id)))
99
- safe = index;
97
+ unanswered = index;
100
98
  }
101
- let last = safe - 1;
99
+ const awaited = branch.findIndex((entry) => entry.id === awaitedEntryId);
100
+ return awaited >= 0 && (unanswered === undefined || awaited < unanswered) ? awaited : unanswered;
101
+ }
102
+ /**
103
+ * Path index of the last entry a background task may freeze, or -1 when nothing is safe.
104
+ *
105
+ * Cuts before the earliest assistant message of the trailing tool run with an unanswered call
106
+ * ({@link findUnansweredToolCall}): it and everything after it stay out of the prefix (infinity's
107
+ * `safe_spawn_point`). A safe point never lands on a label, which a branched copy drops.
108
+ */
109
+ export function findBackgroundCompactionSafePoint(branch, awaitedEntryId) {
110
+ let last = (findUnansweredToolCall(branch, awaitedEntryId) ?? branch.length) - 1;
102
111
  while (last >= 0 && branch[last].type === "label")
103
112
  last--;
104
113
  return last;
@@ -1 +1 @@
1
- {"version":3,"file":"background-compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/background-compaction.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EACN,+BAA+B,EAE/B,kCAAkC,EAGlC,kCAAkC,EAElC,kCAAkC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,4BAA4B,EAAkC,MAAM,uBAAuB,CAAC;AA+BrG,MAAM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F,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,2CAA2C,CAC1D,KAAc,EACd,MAAwC;IAExC,MAAM,KAAK,GAAG,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACtD,IAAI,KAAK;QAAE,MAAM,KAAK,CAAC;IACvB,OAAQ,KAA4B,IAAI,+CAA+C,CAAC;AACzF,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,iCAAiC,CAChD,UAAwG;IAExG,OAAO;QACN,sBAAsB,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC;QAC1D,wBAAwB,CAAC,UAAU,EAAE,0BAA0B,EAAE,UAAU,CAAC;KAC5E,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * Background compaction scheduling primitives (#4330).\n *\n * Pure functions over the active branch path. Positions are indices in that path, so a fork or a\n * branch taken before a result was stored never sees it, and the latest result that fits a position\n * wins. The compaction algorithm itself is unchanged; only when it runs and when its result is\n * committed is decided here.\n */\n\nimport type { Usage } from \"@bastani/pi-ai/compat\";\nimport type { CompactionEntry, CustomEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { SETTINGS_DEFAULTS } from \"../settings-defaults.ts\";\nimport {\n\tBackgroundCompactionConfigError,\n\ttype BackgroundCompactionConfigSource,\n\tBackgroundCompactionDiscardedError,\n\ttype BackgroundCompactionDiscardReason,\n\ttype BackgroundCompactionError,\n\trehydrateBackgroundCompactionError,\n\ttype SerializedBackgroundCompactionError,\n\tserializeBackgroundCompactionError,\n} from \"./background-compaction-errors.ts\";\nimport { VERBATIM_COMPACTION_STRATEGY, type VerbatimCompactionDetails } from \"./compaction-types.js\";\n\n/**\n * Background compaction state of one session.\n *\n * - `idle`: nothing is running and no result waits for a commit, including while background compaction is off.\n * - `running`: a task compacts the prefix through `upToEntryId`.\n * - `ready`: a stored result for `upToEntryId` waits for the next turn boundary.\n * - `failed`: the last task, or applying its result, failed with `error`; history is unchanged and a later boundary\n * retries. An invalid setting also reports `failed`, with background compaction off until it is fixed.\n */\nexport type BackgroundCompactionStatus = \"idle\" | \"running\" | \"ready\" | \"failed\";\n\nexport interface BackgroundCompactionState {\n\treadonly state: BackgroundCompactionStatus;\n\t/** Last entry of the frozen prefix; absent while idle. */\n\treadonly upToEntryId?: string;\n\t/** ISO time the task started; absent while idle. */\n\treadonly startedAt?: string;\n\t/** Typed reason of a failed task; present only when `state` is `failed`. */\n\treadonly error?: BackgroundCompactionError;\n}\n\n/** `BackgroundCompactionState` as RPC and workflow status carry it. */\nexport interface SerializedBackgroundCompactionState {\n\treadonly state: BackgroundCompactionStatus;\n\treadonly upToEntryId?: string;\n\treadonly startedAt?: string;\n\treadonly error?: SerializedBackgroundCompactionError;\n}\n\nexport const IDLE_BACKGROUND_COMPACTION_STATE: BackgroundCompactionState = Object.freeze({ state: \"idle\" });\n\nexport function serializeBackgroundCompactionState(\n\tstate: BackgroundCompactionState,\n): SerializedBackgroundCompactionState {\n\treturn {\n\t\tstate: state.state,\n\t\t...(state.upToEntryId === undefined ? {} : { upToEntryId: state.upToEntryId }),\n\t\t...(state.startedAt === undefined ? {} : { startedAt: state.startedAt }),\n\t\t...(state.error === undefined ? {} : { error: serializeBackgroundCompactionError(state.error) }),\n\t};\n}\n\nexport function rehydrateBackgroundCompactionState(\n\tserialized: SerializedBackgroundCompactionState,\n): BackgroundCompactionState {\n\treturn {\n\t\tstate: serialized.state,\n\t\t...(serialized.upToEntryId === undefined ? {} : { upToEntryId: serialized.upToEntryId }),\n\t\t...(serialized.startedAt === undefined ? {} : { startedAt: serialized.startedAt }),\n\t\t...(serialized.error === undefined ? {} : { error: rehydrateBackgroundCompactionError(serialized.error) }),\n\t};\n}\n\n/** The \"compaction ready\" wake for a session whose result is stored and waits for its next turn. */\nexport interface CompactionReadyWake {\n\treadonly sessionId: string;\n\t/** Session entry that stores the result. */\n\treadonly resultEntryId: string;\n\treadonly upToEntryId: string;\n}\n\n/**\n * Narrow wake interface for background compaction. The task never holds the agent: it stores its\n * result and calls `compactionReady`, and the agent applies the result at its next turn boundary.\n * Without a dispatcher the session notifies its own listeners in process.\n */\nexport interface CompactionWakeDispatcher {\n\tcompactionReady(wake: CompactionReadyWake): void;\n}\n\n/** `customType` of the session entry that stores a finished background compaction until it is committed. */\nexport const BACKGROUND_COMPACTION_RESULT_TYPE = \"atomic:background-compaction-result\";\n\n/** Default soft threshold, as a percentage of the context window. */\nexport const DEFAULT_BACKGROUND_COMPACTION_THRESHOLD_PERCENT: number =\n\tSETTINGS_DEFAULTS.compaction.backgroundThresholdPercent;\n\n/** First retry delay after a failed background compaction; doubles per failure up to the cap. */\nexport const BACKGROUND_COMPACTION_RETRY_BASE_MS = 15_000;\nexport const BACKGROUND_COMPACTION_RETRY_MAX_MS = 15 * 60_000;\n\n/** A finished compaction of the frozen prefix ending at `upToEntryId`, stored until a turn boundary commits it. */\nexport interface BackgroundCompactionResultRecord {\n\treadonly version: 1;\n\t/** Last entry of the frozen prefix. Entries after it are replayed unchanged after the commit. */\n\treadonly upToEntryId: string;\n\treadonly startedAt: string;\n\treadonly completedAt: string;\n\treadonly summary: string;\n\treadonly firstKeptEntryId: string | null;\n\treadonly tokensBefore: number;\n\treadonly details: VerbatimCompactionDetails;\n\treadonly usage?: Usage;\n\treadonly fromExtension: boolean;\n}\n\n/** A stored result selected for the current branch, with its path positions. */\nexport interface ReadyBackgroundCompaction {\n\treadonly entry: CustomEntry;\n\treadonly record: BackgroundCompactionResultRecord;\n\t/** Path index of `record.upToEntryId`. */\n\treadonly upToIndex: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Validate a stored record at the storage boundary; anything else is `malformed`. */\nexport function isBackgroundCompactionResultRecord(value: unknown): value is BackgroundCompactionResultRecord {\n\tif (!isRecord(value)) return false;\n\tconst details = value.details;\n\treturn (\n\t\tvalue.version === 1 &&\n\t\ttypeof value.upToEntryId === \"string\" &&\n\t\ttypeof value.startedAt === \"string\" &&\n\t\ttypeof value.completedAt === \"string\" &&\n\t\ttypeof value.summary === \"string\" &&\n\t\tvalue.summary.trim().length > 0 &&\n\t\t(value.firstKeptEntryId === null || typeof value.firstKeptEntryId === \"string\") &&\n\t\tNumber.isFinite(value.tokensBefore) &&\n\t\ttypeof value.fromExtension === \"boolean\" &&\n\t\t(value.usage === undefined || isRecord(value.usage)) &&\n\t\tisRecord(details) &&\n\t\tdetails.strategy === VERBATIM_COMPACTION_STRATEGY &&\n\t\tisRecord(details.stats) &&\n\t\tisRecord(details.parameters) &&\n\t\ttypeof details.rung === \"string\"\n\t);\n}\n\nfunction toolCallIds(entry: SessionEntry): string[] {\n\tif (entry.type !== \"message\" || entry.message.role !== \"assistant\") return [];\n\treturn entry.message.content.flatMap((block) => (block.type === \"toolCall\" ? [block.id] : []));\n}\n\n/** Entries that never end the trailing tool run: they contribute no model message. */\nfunction isPassiveEntry(entry: SessionEntry): boolean {\n\treturn (\n\t\tentry.type === \"custom\" ||\n\t\tentry.type === \"label\" ||\n\t\tentry.type === \"model_change\" ||\n\t\tentry.type === \"thinking_level_change\" ||\n\t\tentry.type === \"usage\" ||\n\t\tentry.type === \"session_info\" ||\n\t\tentry.type === \"session_summary\" ||\n\t\tentry.type === \"context_edit\"\n\t);\n}\n\n/**\n * Path index of the last entry a background task may freeze, or -1 when nothing is safe.\n *\n * Walks the trailing run of tool calls and tool results backwards, tracking which calls have a\n * result, and cuts before the earliest assistant message in that run with an unanswered call: it and\n * everything after it stay out of the prefix (infinity's `safe_spawn_point`). Any other message ends\n * the run. A safe point never lands on a label, which a branched copy drops.\n */\nexport function findBackgroundCompactionSafePoint(branch: readonly SessionEntry[]): number {\n\tconst answered = new Set<string>();\n\tlet safe = branch.length;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (isPassiveEntry(entry)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n\t\t\tanswered.add(entry.message.toolCallId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst calls = toolCallIds(entry);\n\t\tif (calls.length === 0) break;\n\t\tif (calls.some((id) => !answered.has(id))) safe = index;\n\t}\n\tlet last = safe - 1;\n\twhile (last >= 0 && branch[last].type === \"label\") last--;\n\treturn last;\n}\n\nfunction isVerbatimBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\treturn (\n\t\tentry.type === \"compaction\" &&\n\t\t(entry.details as { strategy?: string } | undefined)?.strategy === VERBATIM_COMPACTION_STRATEGY\n\t);\n}\n\n/**\n * Path index of the last entry the latest compaction boundary covers, or -1 without one.\n * A foreground boundary covers everything before it; a committed background boundary covers through\n * its `coveredThroughEntryId`.\n */\nexport function coveredThroughIndex(\n\tbranch: readonly SessionEntry[],\n\tindexById: ReadonlyMap<string, number> = indexBranch(branch),\n): number {\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isVerbatimBoundary(entry)) continue;\n\t\tconst covered = (indexById as ReadonlyMap<string | undefined, number>).get(entry.coveredThroughEntryId);\n\t\treturn Math.min(covered ?? index, index - 1);\n\t}\n\treturn -1;\n}\n\nfunction indexBranch(branch: readonly SessionEntry[]): Map<string, number> {\n\treturn new Map(branch.map((entry, index) => [entry.id, index]));\n}\n\n/** Why a stored result cannot be committed on this branch, or undefined when it can. */\nexport function backgroundCompactionDiscardReason(\n\tbranch: readonly SessionEntry[],\n\tresultIndex: number,\n\tindexById: ReadonlyMap<string, number> = indexBranch(branch),\n): BackgroundCompactionDiscardReason | undefined {\n\tconst record = (branch[resultIndex] as Partial<CustomEntry> | undefined)?.data;\n\tif (!isBackgroundCompactionResultRecord(record)) return \"malformed\";\n\tconst upToIndex = indexById.get(record.upToEntryId);\n\tif (upToIndex === undefined || upToIndex >= resultIndex) return \"off-branch\";\n\tif (record.firstKeptEntryId !== null) {\n\t\tconst keptIndex = indexById.get(record.firstKeptEntryId);\n\t\tif (keptIndex === undefined || keptIndex > upToIndex) return \"off-branch\";\n\t}\n\tif (upToIndex <= coveredThroughIndex(branch, indexById)) return \"superseded\";\n\tfor (let index = upToIndex + 1; index < branch.length; index++) {\n\t\tconst later = branch[index];\n\t\tif (later.type === \"context_edit\" && (indexById.get(later.targetId) ?? branch.length) <= upToIndex)\n\t\t\treturn \"context-edited\";\n\t}\n\treturn undefined;\n}\n\n/**\n * The stored result to commit on this branch: among results on the path that still fit, the one\n * covering the latest position wins, and a tie goes to the later record.\n */\nexport function selectReadyBackgroundCompaction(\n\tbranch: readonly SessionEntry[],\n): ReadyBackgroundCompaction | undefined {\n\tconst indexById = indexBranch(branch);\n\tlet best: ReadyBackgroundCompaction | undefined;\n\tfor (let index = 0; index < branch.length; index++) {\n\t\tconst entry = branch[index] as CustomEntry;\n\t\tif (entry.customType !== BACKGROUND_COMPACTION_RESULT_TYPE) continue;\n\t\tif (backgroundCompactionDiscardReason(branch, index, indexById) !== undefined) continue;\n\t\tconst record = entry.data as BackgroundCompactionResultRecord;\n\t\tconst upToIndex = indexById.get(record.upToEntryId) as number;\n\t\tif (best === undefined || upToIndex >= best.upToIndex) best = { entry, record, upToIndex };\n\t}\n\treturn best;\n}\n\n/** Why a finished task's prefix can no longer be saved: it left the branch, or a newer boundary covers it. */\nexport function staleBackgroundCompactionPrefix(\n\tbranch: readonly SessionEntry[],\n\tupToEntryId: string,\n): \"off-branch\" | \"superseded\" | undefined {\n\tconst upToIndex = indexBranch(branch).get(upToEntryId);\n\tif (upToIndex === undefined) return \"off-branch\";\n\treturn upToIndex <= coveredThroughIndex(branch) ? \"superseded\" : undefined;\n}\n\n/** What became of the stored result last announced as ready, judged against the current branch. */\nexport type AnnouncedResultOutcome =\n\t| { readonly kind: \"committable\" }\n\t| { readonly kind: \"discarded\"; readonly error: BackgroundCompactionDiscardedError }\n\t/** The result is not on this branch, for example after `/tree` navigation. It is not discarded. */\n\t| { readonly kind: \"not-on-branch\" };\n\n/** `resultEntryId` is undefined when no result was announced, which is never on any branch. */\nexport function announcedResultOutcome(\n\tbranch: readonly SessionEntry[],\n\tresultEntryId: string | undefined,\n): AnnouncedResultOutcome {\n\tconst indexById = indexBranch(branch);\n\tconst resultIndex = (indexById as ReadonlyMap<string | undefined, number>).get(resultEntryId);\n\tif (resultIndex === undefined) return { kind: \"not-on-branch\" };\n\tconst reason = backgroundCompactionDiscardReason(branch, resultIndex, indexById);\n\tif (reason === undefined) return { kind: \"committable\" };\n\tconst entry = branch[resultIndex] as CustomEntry;\n\tconst upToEntryId = isBackgroundCompactionResultRecord(entry.data) ? entry.data.upToEntryId : entry.id;\n\treturn { kind: \"discarded\", error: new BackgroundCompactionDiscardedError({ upToEntryId, reason }) };\n}\n\n/** Token count at which a background task starts for this window and percentage. */\nexport function backgroundCompactionThresholdTokens(contextWindow: number, thresholdPercent: number): number {\n\treturn (contextWindow * thresholdPercent) / 100;\n}\n\n/** Whether context usage has passed the soft threshold. A window of 0 (unknown) never triggers. */\nexport function shouldStartBackgroundCompaction(\n\tcontextTokens: number,\n\tcontextWindow: number,\n\tthresholdPercent: number,\n): boolean {\n\treturn contextWindow > 0 && contextTokens > backgroundCompactionThresholdTokens(contextWindow, thresholdPercent);\n}\n\n/** Delay before retry `failures + 1` after `failures` consecutive failures: exponential, capped. */\nexport function backgroundCompactionRetryDelayMs(failures: number): number {\n\tif (failures <= 0) return 0;\n\treturn Math.min(BACKGROUND_COMPACTION_RETRY_MAX_MS, BACKGROUND_COMPACTION_RETRY_BASE_MS * 2 ** (failures - 1));\n}\n\nfunction backgroundEnabledError(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): BackgroundCompactionConfigError | undefined {\n\tif (value === undefined || typeof value === \"boolean\") return undefined;\n\treturn new BackgroundCompactionConfigError({ source, field: \"compaction.background\", reason: \"not-a-boolean\" });\n}\n\nfunction backgroundThresholdError(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): BackgroundCompactionConfigError | undefined {\n\tif (value === undefined) return undefined;\n\tconst field = \"compaction.backgroundThresholdPercent\";\n\tif (typeof value !== \"number\" || Number.isNaN(value))\n\t\treturn new BackgroundCompactionConfigError({ source, field, reason: \"not-a-number\" });\n\tif (!(value > 0 && value < 100))\n\t\treturn new BackgroundCompactionConfigError({ source, field, reason: \"out-of-range\" });\n\treturn undefined;\n}\n\n/** `compaction.background`, or its default when unset; anything but a boolean is a typed config error. */\nexport function resolveBackgroundCompactionEnabled(value: unknown, source: BackgroundCompactionConfigSource): boolean {\n\tconst error = backgroundEnabledError(value, source);\n\tif (error) throw error;\n\treturn (value as boolean | undefined) ?? SETTINGS_DEFAULTS.compaction.background;\n}\n\n/** `compaction.backgroundThresholdPercent`, or 75 when unset; it must be a number above 0 and below 100. */\nexport function resolveBackgroundCompactionThresholdPercent(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): number {\n\tconst error = backgroundThresholdError(value, source);\n\tif (error) throw error;\n\treturn (value as number | undefined) ?? DEFAULT_BACKGROUND_COMPACTION_THRESHOLD_PERCENT;\n}\n\n/** The typed errors for the background compaction values a settings file holds. Absent values are valid. */\nexport function backgroundCompactionSettingErrors(\n\tcompaction: { readonly background?: unknown; readonly backgroundThresholdPercent?: unknown } | undefined,\n): BackgroundCompactionConfigError[] {\n\treturn [\n\t\tbackgroundEnabledError(compaction?.background, \"settings\"),\n\t\tbackgroundThresholdError(compaction?.backgroundThresholdPercent, \"settings\"),\n\t].filter((error) => error !== undefined);\n}\n"]}
1
+ {"version":3,"file":"background-compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/background-compaction.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EACN,+BAA+B,EAE/B,kCAAkC,EAGlC,kCAAkC,EAElC,kCAAkC,GAClC,MAAM,mCAAmC,CAAC;AAC3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,CAAC,CAAC;IACvF,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,GAAG,CAAC;QAC9B,OAAO,IAAI,+BAA+B,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;IACvF,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,0GAA0G;AAC1G,MAAM,UAAU,kCAAkC,CAAC,KAAc,EAAE,MAAwC;IAC1G,MAAM,KAAK,GAAG,sBAAsB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACpD,IAAI,KAAK;QAAE,MAAM,KAAK,CAAC;IACvB,OAAQ,KAA6B,IAAI,iBAAiB,CAAC,UAAU,CAAC,UAAU,CAAC;AAClF,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,2CAA2C,CAC1D,KAAc,EACd,MAAwC;IAExC,MAAM,KAAK,GAAG,wBAAwB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACtD,IAAI,KAAK;QAAE,MAAM,KAAK,CAAC;IACvB,OAAQ,KAA4B,IAAI,+CAA+C,CAAC;AACzF,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,iCAAiC,CAChD,UAAwG;IAExG,OAAO;QACN,sBAAsB,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC;QAC1D,wBAAwB,CAAC,UAAU,EAAE,0BAA0B,EAAE,UAAU,CAAC;KAC5E,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * Background compaction scheduling primitives (#4330).\n *\n * Pure functions over the active branch path. Positions are indices in that path, so a fork or a\n * branch taken before a result was stored never sees it, and the latest result that fits a position\n * wins. The compaction algorithm itself is unchanged; only when it runs and when its result is\n * committed is decided here.\n */\n\nimport type { Usage } from \"@bastani/pi-ai/compat\";\nimport type { CompactionEntry, CustomEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { SETTINGS_DEFAULTS } from \"../settings-defaults.ts\";\nimport {\n\tBackgroundCompactionConfigError,\n\ttype BackgroundCompactionConfigSource,\n\tBackgroundCompactionDiscardedError,\n\ttype BackgroundCompactionDiscardReason,\n\ttype BackgroundCompactionError,\n\trehydrateBackgroundCompactionError,\n\ttype SerializedBackgroundCompactionError,\n\tserializeBackgroundCompactionError,\n} from \"./background-compaction-errors.ts\";\nimport { VERBATIM_COMPACTION_STRATEGY, type VerbatimCompactionDetails } from \"./compaction-types.js\";\n\n/**\n * Background compaction state of one session.\n *\n * - `idle`: nothing is running and no result waits for a commit, including while background compaction is off.\n * - `running`: a task compacts the prefix through `upToEntryId`.\n * - `ready`: a stored result for `upToEntryId` waits for the next turn boundary.\n * - `failed`: the last task, or applying its result, failed with `error`; history is unchanged and a later boundary\n * retries. An invalid setting also reports `failed`, with background compaction off until it is fixed.\n */\nexport type BackgroundCompactionStatus = \"idle\" | \"running\" | \"ready\" | \"failed\";\n\nexport interface BackgroundCompactionState {\n\treadonly state: BackgroundCompactionStatus;\n\t/** Last entry of the frozen prefix; absent while idle. */\n\treadonly upToEntryId?: string;\n\t/** ISO time the task started; absent while idle. */\n\treadonly startedAt?: string;\n\t/** Typed reason of a failed task; present only when `state` is `failed`. */\n\treadonly error?: BackgroundCompactionError;\n}\n\n/** `BackgroundCompactionState` as RPC and workflow status carry it. */\nexport interface SerializedBackgroundCompactionState {\n\treadonly state: BackgroundCompactionStatus;\n\treadonly upToEntryId?: string;\n\treadonly startedAt?: string;\n\treadonly error?: SerializedBackgroundCompactionError;\n}\n\nexport const IDLE_BACKGROUND_COMPACTION_STATE: BackgroundCompactionState = Object.freeze({ state: \"idle\" });\n\nexport function serializeBackgroundCompactionState(\n\tstate: BackgroundCompactionState,\n): SerializedBackgroundCompactionState {\n\treturn {\n\t\tstate: state.state,\n\t\t...(state.upToEntryId === undefined ? {} : { upToEntryId: state.upToEntryId }),\n\t\t...(state.startedAt === undefined ? {} : { startedAt: state.startedAt }),\n\t\t...(state.error === undefined ? {} : { error: serializeBackgroundCompactionError(state.error) }),\n\t};\n}\n\nexport function rehydrateBackgroundCompactionState(\n\tserialized: SerializedBackgroundCompactionState,\n): BackgroundCompactionState {\n\treturn {\n\t\tstate: serialized.state,\n\t\t...(serialized.upToEntryId === undefined ? {} : { upToEntryId: serialized.upToEntryId }),\n\t\t...(serialized.startedAt === undefined ? {} : { startedAt: serialized.startedAt }),\n\t\t...(serialized.error === undefined ? {} : { error: rehydrateBackgroundCompactionError(serialized.error) }),\n\t};\n}\n\n/** The \"compaction ready\" wake for a session whose result is stored and waits for its next turn. */\nexport interface CompactionReadyWake {\n\treadonly sessionId: string;\n\t/** Session entry that stores the result. */\n\treadonly resultEntryId: string;\n\treadonly upToEntryId: string;\n}\n\n/**\n * Narrow wake interface for background compaction. The task never holds the agent: it stores its\n * result and calls `compactionReady`, and the agent applies the result at its next turn boundary.\n * Without a dispatcher the session notifies its own listeners in process.\n */\nexport interface CompactionWakeDispatcher {\n\tcompactionReady(wake: CompactionReadyWake): void;\n}\n\n/** `customType` of the session entry that stores a finished background compaction until it is committed. */\nexport const BACKGROUND_COMPACTION_RESULT_TYPE = \"atomic:background-compaction-result\";\n\n/** Default soft threshold, as a percentage of the context window. */\nexport const DEFAULT_BACKGROUND_COMPACTION_THRESHOLD_PERCENT: number =\n\tSETTINGS_DEFAULTS.compaction.backgroundThresholdPercent;\n\n/** First retry delay after a failed background compaction; doubles per failure up to the cap. */\nexport const BACKGROUND_COMPACTION_RETRY_BASE_MS = 15_000;\nexport const BACKGROUND_COMPACTION_RETRY_MAX_MS = 15 * 60_000;\n\n/** A finished compaction of the frozen prefix ending at `upToEntryId`, stored until a turn boundary commits it. */\nexport interface BackgroundCompactionResultRecord {\n\treadonly version: 1;\n\t/** Last entry of the frozen prefix. Entries after it are replayed unchanged after the commit. */\n\treadonly upToEntryId: string;\n\treadonly startedAt: string;\n\treadonly completedAt: string;\n\treadonly summary: string;\n\treadonly firstKeptEntryId: string | null;\n\treadonly tokensBefore: number;\n\treadonly details: VerbatimCompactionDetails;\n\treadonly usage?: Usage;\n\treadonly fromExtension: boolean;\n}\n\n/** A stored result selected for the current branch, with its path positions. */\nexport interface ReadyBackgroundCompaction {\n\treadonly entry: CustomEntry;\n\treadonly record: BackgroundCompactionResultRecord;\n\t/** Path index of `record.upToEntryId`. */\n\treadonly upToIndex: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Validate a stored record at the storage boundary; anything else is `malformed`. */\nexport function isBackgroundCompactionResultRecord(value: unknown): value is BackgroundCompactionResultRecord {\n\tif (!isRecord(value)) return false;\n\tconst details = value.details;\n\treturn (\n\t\tvalue.version === 1 &&\n\t\ttypeof value.upToEntryId === \"string\" &&\n\t\ttypeof value.startedAt === \"string\" &&\n\t\ttypeof value.completedAt === \"string\" &&\n\t\ttypeof value.summary === \"string\" &&\n\t\tvalue.summary.trim().length > 0 &&\n\t\t(value.firstKeptEntryId === null || typeof value.firstKeptEntryId === \"string\") &&\n\t\tNumber.isFinite(value.tokensBefore) &&\n\t\ttypeof value.fromExtension === \"boolean\" &&\n\t\t(value.usage === undefined || isRecord(value.usage)) &&\n\t\tisRecord(details) &&\n\t\tdetails.strategy === VERBATIM_COMPACTION_STRATEGY &&\n\t\tisRecord(details.stats) &&\n\t\tisRecord(details.parameters) &&\n\t\ttypeof details.rung === \"string\"\n\t);\n}\n\nfunction toolCallIds(entry: SessionEntry): string[] {\n\tif (entry.type !== \"message\" || entry.message.role !== \"assistant\") return [];\n\treturn entry.message.content.flatMap((block) => (block.type === \"toolCall\" ? [block.id] : []));\n}\n\n/** Entries that never end the trailing tool run: they contribute no model message. */\nfunction isPassiveEntry(entry: SessionEntry): boolean {\n\treturn (\n\t\tentry.type === \"custom\" ||\n\t\tentry.type === \"label\" ||\n\t\tentry.type === \"model_change\" ||\n\t\tentry.type === \"thinking_level_change\" ||\n\t\tentry.type === \"usage\" ||\n\t\tentry.type === \"session_info\" ||\n\t\tentry.type === \"session_summary\" ||\n\t\tentry.type === \"context_edit\"\n\t);\n}\n\n/**\n * Path index of the earliest assistant message of the trailing run of tool calls and tool results that has a call\n * without a result, or undefined when every call of the run has one. Walks the run backwards, tracking which calls\n * have a result; any other message ends the run. `awaitedEntryId` names a turn the context still waits on a result\n * for whatever entries follow it, such as a custom message that was delivered meanwhile.\n */\nexport function findUnansweredToolCall(branch: readonly SessionEntry[], awaitedEntryId?: string): number | undefined {\n\tconst answered = new Set<string>();\n\tlet unanswered: number | undefined;\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (isPassiveEntry(entry)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"toolResult\") {\n\t\t\tanswered.add(entry.message.toolCallId);\n\t\t\tcontinue;\n\t\t}\n\t\tconst calls = toolCallIds(entry);\n\t\tif (calls.length === 0) break;\n\t\tif (calls.some((id) => !answered.has(id))) unanswered = index;\n\t}\n\tconst awaited = branch.findIndex((entry) => entry.id === awaitedEntryId);\n\treturn awaited >= 0 && (unanswered === undefined || awaited < unanswered) ? awaited : unanswered;\n}\n\n/**\n * Path index of the last entry a background task may freeze, or -1 when nothing is safe.\n *\n * Cuts before the earliest assistant message of the trailing tool run with an unanswered call\n * ({@link findUnansweredToolCall}): it and everything after it stay out of the prefix (infinity's\n * `safe_spawn_point`). A safe point never lands on a label, which a branched copy drops.\n */\nexport function findBackgroundCompactionSafePoint(branch: readonly SessionEntry[], awaitedEntryId?: string): number {\n\tlet last = (findUnansweredToolCall(branch, awaitedEntryId) ?? branch.length) - 1;\n\twhile (last >= 0 && branch[last].type === \"label\") last--;\n\treturn last;\n}\n\nfunction isVerbatimBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\treturn (\n\t\tentry.type === \"compaction\" &&\n\t\t(entry.details as { strategy?: string } | undefined)?.strategy === VERBATIM_COMPACTION_STRATEGY\n\t);\n}\n\n/**\n * Path index of the last entry the latest compaction boundary covers, or -1 without one.\n * A foreground boundary covers everything before it; a committed background boundary covers through\n * its `coveredThroughEntryId`.\n */\nexport function coveredThroughIndex(\n\tbranch: readonly SessionEntry[],\n\tindexById: ReadonlyMap<string, number> = indexBranch(branch),\n): number {\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (!isVerbatimBoundary(entry)) continue;\n\t\tconst covered = (indexById as ReadonlyMap<string | undefined, number>).get(entry.coveredThroughEntryId);\n\t\treturn Math.min(covered ?? index, index - 1);\n\t}\n\treturn -1;\n}\n\nfunction indexBranch(branch: readonly SessionEntry[]): Map<string, number> {\n\treturn new Map(branch.map((entry, index) => [entry.id, index]));\n}\n\n/** Why a stored result cannot be committed on this branch, or undefined when it can. */\nexport function backgroundCompactionDiscardReason(\n\tbranch: readonly SessionEntry[],\n\tresultIndex: number,\n\tindexById: ReadonlyMap<string, number> = indexBranch(branch),\n): BackgroundCompactionDiscardReason | undefined {\n\tconst record = (branch[resultIndex] as Partial<CustomEntry> | undefined)?.data;\n\tif (!isBackgroundCompactionResultRecord(record)) return \"malformed\";\n\tconst upToIndex = indexById.get(record.upToEntryId);\n\tif (upToIndex === undefined || upToIndex >= resultIndex) return \"off-branch\";\n\tif (record.firstKeptEntryId !== null) {\n\t\tconst keptIndex = indexById.get(record.firstKeptEntryId);\n\t\tif (keptIndex === undefined || keptIndex > upToIndex) return \"off-branch\";\n\t}\n\tif (upToIndex <= coveredThroughIndex(branch, indexById)) return \"superseded\";\n\tfor (let index = upToIndex + 1; index < branch.length; index++) {\n\t\tconst later = branch[index];\n\t\tif (later.type === \"context_edit\" && (indexById.get(later.targetId) ?? branch.length) <= upToIndex)\n\t\t\treturn \"context-edited\";\n\t}\n\treturn undefined;\n}\n\n/**\n * The stored result to commit on this branch: among results on the path that still fit, the one\n * covering the latest position wins, and a tie goes to the later record.\n */\nexport function selectReadyBackgroundCompaction(\n\tbranch: readonly SessionEntry[],\n): ReadyBackgroundCompaction | undefined {\n\tconst indexById = indexBranch(branch);\n\tlet best: ReadyBackgroundCompaction | undefined;\n\tfor (let index = 0; index < branch.length; index++) {\n\t\tconst entry = branch[index] as CustomEntry;\n\t\tif (entry.customType !== BACKGROUND_COMPACTION_RESULT_TYPE) continue;\n\t\tif (backgroundCompactionDiscardReason(branch, index, indexById) !== undefined) continue;\n\t\tconst record = entry.data as BackgroundCompactionResultRecord;\n\t\tconst upToIndex = indexById.get(record.upToEntryId) as number;\n\t\tif (best === undefined || upToIndex >= best.upToIndex) best = { entry, record, upToIndex };\n\t}\n\treturn best;\n}\n\n/** Why a finished task's prefix can no longer be saved: it left the branch, or a newer boundary covers it. */\nexport function staleBackgroundCompactionPrefix(\n\tbranch: readonly SessionEntry[],\n\tupToEntryId: string,\n): \"off-branch\" | \"superseded\" | undefined {\n\tconst upToIndex = indexBranch(branch).get(upToEntryId);\n\tif (upToIndex === undefined) return \"off-branch\";\n\treturn upToIndex <= coveredThroughIndex(branch) ? \"superseded\" : undefined;\n}\n\n/** What became of the stored result last announced as ready, judged against the current branch. */\nexport type AnnouncedResultOutcome =\n\t| { readonly kind: \"committable\" }\n\t| { readonly kind: \"discarded\"; readonly error: BackgroundCompactionDiscardedError }\n\t/** The result is not on this branch, for example after `/tree` navigation. It is not discarded. */\n\t| { readonly kind: \"not-on-branch\" };\n\n/** `resultEntryId` is undefined when no result was announced, which is never on any branch. */\nexport function announcedResultOutcome(\n\tbranch: readonly SessionEntry[],\n\tresultEntryId: string | undefined,\n): AnnouncedResultOutcome {\n\tconst indexById = indexBranch(branch);\n\tconst resultIndex = (indexById as ReadonlyMap<string | undefined, number>).get(resultEntryId);\n\tif (resultIndex === undefined) return { kind: \"not-on-branch\" };\n\tconst reason = backgroundCompactionDiscardReason(branch, resultIndex, indexById);\n\tif (reason === undefined) return { kind: \"committable\" };\n\tconst entry = branch[resultIndex] as CustomEntry;\n\tconst upToEntryId = isBackgroundCompactionResultRecord(entry.data) ? entry.data.upToEntryId : entry.id;\n\treturn { kind: \"discarded\", error: new BackgroundCompactionDiscardedError({ upToEntryId, reason }) };\n}\n\n/** Token count at which a background task starts for this window and percentage. */\nexport function backgroundCompactionThresholdTokens(contextWindow: number, thresholdPercent: number): number {\n\treturn (contextWindow * thresholdPercent) / 100;\n}\n\n/** Whether context usage has passed the soft threshold. A window of 0 (unknown) never triggers. */\nexport function shouldStartBackgroundCompaction(\n\tcontextTokens: number,\n\tcontextWindow: number,\n\tthresholdPercent: number,\n): boolean {\n\treturn contextWindow > 0 && contextTokens > backgroundCompactionThresholdTokens(contextWindow, thresholdPercent);\n}\n\n/** Delay before retry `failures + 1` after `failures` consecutive failures: exponential, capped. */\nexport function backgroundCompactionRetryDelayMs(failures: number): number {\n\tif (failures <= 0) return 0;\n\treturn Math.min(BACKGROUND_COMPACTION_RETRY_MAX_MS, BACKGROUND_COMPACTION_RETRY_BASE_MS * 2 ** (failures - 1));\n}\n\nfunction backgroundEnabledError(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): BackgroundCompactionConfigError | undefined {\n\tif (value === undefined || typeof value === \"boolean\") return undefined;\n\treturn new BackgroundCompactionConfigError({ source, field: \"compaction.background\", reason: \"not-a-boolean\" });\n}\n\nfunction backgroundThresholdError(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): BackgroundCompactionConfigError | undefined {\n\tif (value === undefined) return undefined;\n\tconst field = \"compaction.backgroundThresholdPercent\";\n\tif (typeof value !== \"number\" || Number.isNaN(value))\n\t\treturn new BackgroundCompactionConfigError({ source, field, reason: \"not-a-number\" });\n\tif (!(value > 0 && value < 100))\n\t\treturn new BackgroundCompactionConfigError({ source, field, reason: \"out-of-range\" });\n\treturn undefined;\n}\n\n/** `compaction.background`, or its default when unset; anything but a boolean is a typed config error. */\nexport function resolveBackgroundCompactionEnabled(value: unknown, source: BackgroundCompactionConfigSource): boolean {\n\tconst error = backgroundEnabledError(value, source);\n\tif (error) throw error;\n\treturn (value as boolean | undefined) ?? SETTINGS_DEFAULTS.compaction.background;\n}\n\n/** `compaction.backgroundThresholdPercent`, or 75 when unset; it must be a number above 0 and below 100. */\nexport function resolveBackgroundCompactionThresholdPercent(\n\tvalue: unknown,\n\tsource: BackgroundCompactionConfigSource,\n): number {\n\tconst error = backgroundThresholdError(value, source);\n\tif (error) throw error;\n\treturn (value as number | undefined) ?? DEFAULT_BACKGROUND_COMPACTION_THRESHOLD_PERCENT;\n}\n\n/** The typed errors for the background compaction values a settings file holds. Absent values are valid. */\nexport function backgroundCompactionSettingErrors(\n\tcompaction: { readonly background?: unknown; readonly backgroundThresholdPercent?: unknown } | undefined,\n): BackgroundCompactionConfigError[] {\n\treturn [\n\t\tbackgroundEnabledError(compaction?.background, \"settings\"),\n\t\tbackgroundThresholdError(compaction?.backgroundThresholdPercent, \"settings\"),\n\t].filter((error) => error !== undefined);\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { SessionEntry } from "../session-manager-types.ts";
2
+ import type { HistoryLineRange } from "../tools/history-transcript.ts";
2
3
  import { type CompactionSettings } from "./compaction.ts";
3
4
  import { type VerbatimCompactionParameters, type VerbatimCompactionPreparation } from "./compaction-types.js";
4
5
  /**
@@ -48,6 +49,15 @@ export interface CompactionBoundaryControl {
48
49
  * straight to the fresh rung without invoking a planner.
49
50
  */
50
51
  allowSmallRegion?: boolean;
52
+ /**
53
+ * Where this session's own entries sit in its `history://sessions/<sessionId>` view. A truncated tool result of
54
+ * an entry listed here says where its full output can be read; without it the marker only says the output is
55
+ * in the session's history.
56
+ */
57
+ history?: {
58
+ sessionId: string;
59
+ entryRanges: ReadonlyMap<string, HistoryLineRange>;
60
+ };
51
61
  }
52
62
  /** Prepare the complete compactable transcript and its exact context-visible message tail. */
53
63
  export declare function prepareCompactionBoundary(pathEntries: SessionEntry[], settings: CompactionSettings, options?: Partial<VerbatimCompactionParameters>, control?: CompactionBoundaryControl): VerbatimCompactionPreparation | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-boundary.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAqC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,KAAK,kBAAkB,EAAkD,MAAM,iBAAiB,CAAC;AAM1G,OAAO,EAKN,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EAClC,MAAM,uBAAuB,CAAC;AAW/B;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,MAAM,CAG3F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,OAAO,CAE5F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE3G;AAqDD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CASlF;AA2BD;;;;;;;;GAQG;AACH,MAAM,WAAW,yBAAyB;IACzC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,8FAA8F;AAC9F,wBAAgB,yBAAyB,CACxC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,EACnD,OAAO,GAAE,yBAA8B,GACrC,6BAA6B,GAAG,SAAS,CAyC3C"}
1
+ {"version":3,"file":"compaction-boundary.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAqC,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACnG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,KAAK,kBAAkB,EAAkD,MAAM,iBAAiB,CAAC;AAM1G,OAAO,EAKN,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EAClC,MAAM,uBAAuB,CAAC;AAe/B;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,MAAM,CAG3F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,OAAO,CAE5F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE3G;AAqDD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CASlF;AA2BD;;;;;;;;GAQG;AACH,MAAM,WAAW,yBAAyB;IACzC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE;QACT,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;KACnD,CAAC;CACF;AAgCD,8FAA8F;AAC9F,wBAAgB,yBAAyB,CACxC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,EACnD,OAAO,GAAE,yBAA8B,GACrC,6BAA6B,GAAG,SAAS,CA2C3C"}
@@ -4,7 +4,7 @@ import { applyContextEdit, buildSessionProjection, collectContextEdits } from ".
4
4
  import { estimateProjectedContextTokens, estimateTokens } from "./compaction.js";
5
5
  import { COMPACTION_AUTO_QUERY, normalizeCompactionParameters, normalizeCompactionQuery, } from "./compaction-parameters.js";
6
6
  import { MIN_COMPACTABLE_REGION_LINES, THINKING_FREE_PROMPT_VERSION, VERBATIM_COMPACTION_STRATEGY, } from "./compaction-types.js";
7
- import { createConversationRegion, omitLegacyThinkingSections } from "./transcript-serialization.js";
7
+ import { createConversationRegion, omitLegacyThinkingSections, } from "./transcript-serialization.js";
8
8
  const keptTailTokensByPreparation = new WeakMap();
9
9
  /**
10
10
  * Return the independently estimated cost of the protected tail.
@@ -120,6 +120,33 @@ function previousSummaryText(boundary) {
120
120
  ? boundary.summary
121
121
  : omitLegacyThinkingSections(boundary.summary);
122
122
  }
123
+ /**
124
+ * Locate each tool result of a converted region in the session's history view.
125
+ *
126
+ * Conversion drops orphan results, inserts synthetic ones and clones renamed ones, so messages are matched to
127
+ * entries by their content array in order rather than by position. A result whose content a context edit rewrote
128
+ * has no locator: history holds the original output, not what the model saw.
129
+ */
130
+ function fullOutputLocators(items, converted, history) {
131
+ const locators = new Map();
132
+ let cursor = 0;
133
+ for (const message of converted) {
134
+ if (message.role !== "toolResult")
135
+ continue;
136
+ for (let index = cursor; index < items.length; index++) {
137
+ const item = items[index];
138
+ if (item.message.role !== "toolResult" || item.message.content !== message.content)
139
+ continue;
140
+ cursor = index + 1;
141
+ const range = history.entryRanges.get(item.entry.id);
142
+ const unedited = item.entry.type === "message" && item.entry.message === item.message;
143
+ if (range && unedited)
144
+ locators.set(message, `history://sessions/${history.sessionId}:${range.start}-${range.end}`);
145
+ break;
146
+ }
147
+ }
148
+ return locators;
149
+ }
123
150
  /** Prepare the complete compactable transcript and its exact context-visible message tail. */
124
151
  export function prepareCompactionBoundary(pathEntries, settings, options = {}, control = {}) {
125
152
  const entries = normalizeDerivedSessionEntries(pathEntries);
@@ -137,7 +164,8 @@ export function prepareCompactionBoundary(pathEntries, settings, options = {}, c
137
164
  const tailStart = Math.max(0, visible.length - parameters.preserve_recent);
138
165
  const regionMessages = visible.slice(0, tailStart);
139
166
  const tailMessages = visible.slice(tailStart);
140
- const region = createConversationRegion(convertToLlm(regionMessages.map((item) => item.message)), previous ? previousSummaryText(previous.entry) : undefined);
167
+ const regionConversation = convertToLlm(regionMessages.map((item) => item.message));
168
+ const region = createConversationRegion(regionConversation, previous ? previousSummaryText(previous.entry) : undefined, control.history && fullOutputLocators(regionMessages, regionConversation, control.history));
141
169
  if (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES)
142
170
  return undefined;
143
171
  const preparation = {
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAE9G,OAAO,EAA2B,8BAA8B,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC1G,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,4BAA4B,EAC5B,4BAA4B,EAC5B,4BAA4B,GAI5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAQrG,MAAM,2BAA2B,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEzF;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,MAAM,UAAU,GAAG,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAChE,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AAClD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,OAAO,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C,EAAE,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ACnD,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAE9C,MAAM,MAAM,GAAG,wBAAwB,CACtC,YAAY,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,EACxD,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAC1D,CAAC;IACF,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,4BAA4B;QAAE,OAAO,SAAS,CAAC;IAEtG,MAAM,WAAW,GAAkC;QAClD,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,8BAA8B,CAAC,sBAAsB,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,MAAM;QAC7F,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { applyContextEdit, buildSessionProjection, collectContextEdits } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, ContextEditEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateProjectedContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tTHINKING_FREE_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createConversationRegion, omitLegacyThinkingSections } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/**\n * Return the independently estimated cost of the protected tail.\n *\n * Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)\n * is returned. The old fallback of `tokensBefore - region.tokenEstimate` was\n * removed because it mixed the authoritative whole-context count with the\n * heuristic region estimate; when no explicit estimate exists the tail simply\n * contributes nothing rather than a wrong-numbered value. Whether an estimate is\n * registered at all is visible through `hasKeptTailTokenEstimate`, which the\n * fresh rung uses to decide a tail whose size is unknown (P1 #3010).\n */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\tconst registered = keptTailTokensByPreparation.get(preparation);\n\treturn registered === undefined ? 0 : registered;\n}\n\n/**\n * Whether an independent tail estimate is registered for this preparation.\n *\n * A preparation built by `prepareCompactionBoundary` always has one. A directly\n * constructed preparation may not; the fresh rung treats a kept tail whose size\n * is unregistered as unknown and drops it conservatively rather than assuming it\n * fits (P1 #3010).\n */\nexport function hasKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): boolean {\n\treturn keptTailTokensByPreparation.has(preparation);\n}\n\n/**\n * Record the independent tail estimate for a preparation.\n *\n * `prepareCompactionBoundary` does this itself from the kept-tail messages;\n * this setter is for test preparations built directly and for any other code\n * that constructs a `VerbatimCompactionPreparation` without the boundary\n * preparer. The estimate lives in a module-private map and is never persisted.\n */\nexport function setKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation, estimate: number): void {\n\tkeptTailTokensByPreparation.set(preparation, Math.max(0, estimate));\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\t// Prompt state is replayed separately at the boundary, never offered for deletion.\n\tif (entry.type === \"message\") return entry.message.role === \"system\" ? undefined : entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\n/** Context-visible entries from `start`, with append-only context edits applied to their content. */\nfunction visibleEntries(entries: SessionEntry[], start = 0, edits?: Map<string, ContextEditEntry>): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst raw = messageFromEntry(entry);\n\t\tif (!raw) continue;\n\t\tconst edit = edits?.get(entry.id);\n\t\tconst message = edit ? applyContextEdit([raw], edit)[0] : raw;\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * The previous boundary's durable text in the current transcript grammar.\n *\n * Boundaries written before `THINKING_FREE_PROMPT_VERSION` serialized thinking as\n * `[Assistant thinking]: ` sections, so those sections are dropped before the text\n * reaches the planner again. A current boundary is used as written: any such line in\n * it is quoted payload, not a section header.\n */\nfunction previousSummaryText(boundary: CompactionEntry<VerbatimCompactionDetails>): string {\n\tconst { promptVersion } = boundary.details as { promptVersion?: number };\n\treturn (promptVersion ?? 0) >= THINKING_FREE_PROMPT_VERSION\n\t\t? boundary.summary\n\t\t: omitLegacyThinkingSections(boundary.summary);\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tconst coveredIndex = entries.findIndex(\n\t\t\t(entry, index) => index < previous.index && entry.id === previous.entry.coveredThroughEntryId,\n\t\t);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : coveredIndex >= 0 ? coveredIndex + 1 : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart, collectContextEdits(entries));\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst region = createConversationRegion(\n\t\tconvertToLlm(regionMessages.map((item) => item.message)),\n\t\tprevious ? previousSummaryText(previous.entry) : undefined,\n\t);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateProjectedContextTokens(buildSessionProjection(entries), entries).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
1
+ {"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAG9G,OAAO,EAA2B,8BAA8B,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC1G,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,4BAA4B,EAC5B,4BAA4B,EAC5B,4BAA4B,GAI5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,wBAAwB,EAExB,0BAA0B,GAC1B,MAAM,+BAA+B,CAAC;AAQvC,MAAM,2BAA2B,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEzF;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,MAAM,UAAU,GAAG,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAChE,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AAClD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,OAAO,2BAA2B,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SAAS,CAAC,CAAC;IAE9C,MAAM,kBAAkB,GAAG,YAAY,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IACpF,MAAM,MAAM,GAAG,wBAAwB,CACtC,kBAAkB,EAClB,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,EAC1D,OAAO,CAAC,OAAO,IAAI,kBAAkB,CAAC,cAAc,EAAE,kBAAkB,EAAE,OAAO,CAAC,OAAO,CAAC,CAC1F,CAAC;IACF,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,4BAA4B;QAAE,OAAO,SAAS,CAAC;IAEtG,MAAM,WAAW,GAAkC;QAClD,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,8BAA8B,CAAC,sBAAsB,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,MAAM;QAC7F,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { Message } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { applyContextEdit, buildSessionProjection, collectContextEdits } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, ContextEditEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport type { HistoryLineRange } from \"../tools/history-transcript.ts\";\nimport { type CompactionSettings, estimateProjectedContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tTHINKING_FREE_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport {\n\tcreateConversationRegion,\n\ttype FullOutputLocators,\n\tomitLegacyThinkingSections,\n} from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/**\n * Return the independently estimated cost of the protected tail.\n *\n * Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)\n * is returned. The old fallback of `tokensBefore - region.tokenEstimate` was\n * removed because it mixed the authoritative whole-context count with the\n * heuristic region estimate; when no explicit estimate exists the tail simply\n * contributes nothing rather than a wrong-numbered value. Whether an estimate is\n * registered at all is visible through `hasKeptTailTokenEstimate`, which the\n * fresh rung uses to decide a tail whose size is unknown (P1 #3010).\n */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\tconst registered = keptTailTokensByPreparation.get(preparation);\n\treturn registered === undefined ? 0 : registered;\n}\n\n/**\n * Whether an independent tail estimate is registered for this preparation.\n *\n * A preparation built by `prepareCompactionBoundary` always has one. A directly\n * constructed preparation may not; the fresh rung treats a kept tail whose size\n * is unregistered as unknown and drops it conservatively rather than assuming it\n * fits (P1 #3010).\n */\nexport function hasKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): boolean {\n\treturn keptTailTokensByPreparation.has(preparation);\n}\n\n/**\n * Record the independent tail estimate for a preparation.\n *\n * `prepareCompactionBoundary` does this itself from the kept-tail messages;\n * this setter is for test preparations built directly and for any other code\n * that constructs a `VerbatimCompactionPreparation` without the boundary\n * preparer. The estimate lives in a module-private map and is never persisted.\n */\nexport function setKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation, estimate: number): void {\n\tkeptTailTokensByPreparation.set(preparation, Math.max(0, estimate));\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\t// Prompt state is replayed separately at the boundary, never offered for deletion.\n\tif (entry.type === \"message\") return entry.message.role === \"system\" ? undefined : entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\n/** Context-visible entries from `start`, with append-only context edits applied to their content. */\nfunction visibleEntries(entries: SessionEntry[], start = 0, edits?: Map<string, ContextEditEntry>): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst raw = messageFromEntry(entry);\n\t\tif (!raw) continue;\n\t\tconst edit = edits?.get(entry.id);\n\t\tconst message = edit ? applyContextEdit([raw], edit)[0] : raw;\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * The previous boundary's durable text in the current transcript grammar.\n *\n * Boundaries written before `THINKING_FREE_PROMPT_VERSION` serialized thinking as\n * `[Assistant thinking]: ` sections, so those sections are dropped before the text\n * reaches the planner again. A current boundary is used as written: any such line in\n * it is quoted payload, not a section header.\n */\nfunction previousSummaryText(boundary: CompactionEntry<VerbatimCompactionDetails>): string {\n\tconst { promptVersion } = boundary.details as { promptVersion?: number };\n\treturn (promptVersion ?? 0) >= THINKING_FREE_PROMPT_VERSION\n\t\t? boundary.summary\n\t\t: omitLegacyThinkingSections(boundary.summary);\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n\t/**\n\t * Where this session's own entries sit in its `history://sessions/<sessionId>` view. A truncated tool result of\n\t * an entry listed here says where its full output can be read; without it the marker only says the output is\n\t * in the session's history.\n\t */\n\thistory?: {\n\t\tsessionId: string;\n\t\tentryRanges: ReadonlyMap<string, HistoryLineRange>;\n\t};\n}\n\n/**\n * Locate each tool result of a converted region in the session's history view.\n *\n * Conversion drops orphan results, inserts synthetic ones and clones renamed ones, so messages are matched to\n * entries by their content array in order rather than by position. A result whose content a context edit rewrote\n * has no locator: history holds the original output, not what the model saw.\n */\nfunction fullOutputLocators(\n\titems: readonly VisibleEntry[],\n\tconverted: readonly Message[],\n\thistory: NonNullable<CompactionBoundaryControl[\"history\"]>,\n): FullOutputLocators {\n\tconst locators = new Map<Message, string>();\n\tlet cursor = 0;\n\tfor (const message of converted) {\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tfor (let index = cursor; index < items.length; index++) {\n\t\t\tconst item = items[index];\n\t\t\tif (item.message.role !== \"toolResult\" || item.message.content !== message.content) continue;\n\t\t\tcursor = index + 1;\n\t\t\tconst range = history.entryRanges.get(item.entry.id);\n\t\t\tconst unedited = item.entry.type === \"message\" && item.entry.message === item.message;\n\t\t\tif (range && unedited)\n\t\t\t\tlocators.set(message, `history://sessions/${history.sessionId}:${range.start}-${range.end}`);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn locators;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tconst coveredIndex = entries.findIndex(\n\t\t\t(entry, index) => index < previous.index && entry.id === previous.entry.coveredThroughEntryId,\n\t\t);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : coveredIndex >= 0 ? coveredIndex + 1 : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart, collectContextEdits(entries));\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst regionConversation = convertToLlm(regionMessages.map((item) => item.message));\n\tconst region = createConversationRegion(\n\t\tregionConversation,\n\t\tprevious ? previousSummaryText(previous.entry) : undefined,\n\t\tcontrol.history && fullOutputLocators(regionMessages, regionConversation, control.history),\n\t);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateProjectedContextTokens(buildSessionProjection(entries), entries).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
@@ -5,10 +5,13 @@ import type { SessionEntry } from "../session-manager-types.ts";
5
5
  import type { CompactedTranscript, CompactionPlannerModel, CompactionUrgency, PlannerAuth, VerbatimCompactionPreparation } from "./compaction-types.js";
6
6
  import { type FallbackPlannerContext } from "./fallback-planner.js";
7
7
  import type { CompactionModelSelection } from "./model-resolver.js";
8
+ import { type SidecarDirectory } from "./range-planner-diagnostics.js";
8
9
  export interface CompactionPlanOptions {
9
10
  streamFn: StreamFn;
10
11
  /** Absolute path of the persisted session file. Undefined for in-memory sessions. */
11
12
  sessionFilePath?: string;
13
+ /** Where diagnostics go for a persisted session that has no session file, such as one in SQLite. */
14
+ sidecarDirectory?: SidecarDirectory;
12
15
  retry?: RetryPolicy;
13
16
  callbacks?: RetryCallbacks;
14
17
  }
@@ -99,6 +102,10 @@ export declare function startNewContextWindow(preparation: VerbatimCompactionPre
99
102
  * a fresh context window. A manual `/compact` runs at `recoverable` urgency and
100
103
  * therefore cannot reach the context-destroying rung; it fails honestly instead.
101
104
  *
105
+ * A planner that is refused partway through its output (#4543) is retried once and then given the
106
+ * region in parts split at message boundaries; the lossy summary fallback runs only after that
107
+ * fails, or at once for an immediate input refusal.
108
+ *
102
109
  * Unavailable credentials are ladder control flow, not an early throw: a
103
110
  * borrowed candidate with its own working credentials can still rank the lines,
104
111
  * and a load-bearing caller still reaches the credential-free fresh rung.
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,GAAG,EAAE,K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,GAAG,MAAM,CAGlF;AAwDD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,6BAA6B,GAAG,mBAAmB,CAErG;AAgOD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,qBAAqB,CAC1C,WAAW,EAAE,6BAA6B,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,oBAAoB,GAC3B,OAAO,CAAC,oBAAoB,CAAC,CAQ/B"}
@@ -6,8 +6,9 @@ import { createFallbackPlannerBorrower, plannerAttemptKey, } from "./fallback-pl
6
6
  import { planMorphRanges } from "./morph-compaction.js";
7
7
  import { runPiSummaryFallback } from "./pi-summary-fallback.js";
8
8
  import { MALFORMED_OUTPUT_MESSAGE, NO_USABLE_RANGES_MESSAGE, planDeletedLineRanges, RangePlanError, resolvePlannerRequest, } from "./range-planner.js";
9
- import { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar } from "./range-planner-diagnostics.js";
10
- import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-trimming.js";
9
+ import { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar, } from "./range-planner-diagnostics.js";
10
+ import { planWithRefusalRecovery } from "./refusal-recovery.js";
11
+ import { keepTargetForView, nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-trimming.js";
11
12
  import { widenToWholeContextStats } from "./whole-context-stats.js";
12
13
  function addUsage(total, usage) {
13
14
  const cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);
@@ -168,7 +169,7 @@ async function planWithTrimming(preparation, planner, options) {
168
169
  const region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);
169
170
  if (!region)
170
171
  return { kind: "terminal", outcome: { kind: "overflowed" } };
171
- const keepTarget = Math.max(region.protectedLineNumbers?.size ?? 0, Math.round(region.lines.length * preparation.parameters.compression_ratio));
172
+ const keepTarget = keepTargetForView(region, preparation.parameters.compression_ratio);
172
173
  const outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);
173
174
  if (outcome.kind === "ranked" || outcome.kind === "recovered") {
174
175
  if (offset === 0)
@@ -297,6 +298,10 @@ function startPlanningTimeLimit(timeoutMs, signal) {
297
298
  * a fresh context window. A manual `/compact` runs at `recoverable` urgency and
298
299
  * therefore cannot reach the context-destroying rung; it fails honestly instead.
299
300
  *
301
+ * A planner that is refused partway through its output (#4543) is retried once and then given the
302
+ * region in parts split at message boundaries; the lossy summary fallback runs only after that
303
+ * fails, or at once for an immediate input refusal.
304
+ *
300
305
  * Unavailable credentials are ladder control flow, not an early throw: a
301
306
  * borrowed candidate with its own working credentials can still rank the lines,
302
307
  * and a load-bearing caller still reaches the credential-free fresh rung.
@@ -323,6 +328,7 @@ async function runCompactionLadder(preparation, model, request, timeLimit) {
323
328
  const plannerOptions = {
324
329
  streamFn: request.streamFn,
325
330
  sessionFilePath: request.sessionFilePath,
331
+ sidecarDirectory: request.sidecarDirectory,
326
332
  retry: request.retry,
327
333
  callbacks: request.callbacks,
328
334
  signal: timeLimit.signal,
@@ -381,7 +387,7 @@ async function runCompactionLadder(preparation, model, request, timeLimit) {
381
387
  apiKey: await untilAborted(Promise.resolve(request.resolveMorphApiKey?.()), timeLimit.signal),
382
388
  signal: timeLimit.signal,
383
389
  fetchFn: request.morphFetchFn,
384
- onDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),
390
+ onDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar({ sessionFilePath: request.sessionFilePath, sidecarDirectory: request.sidecarDirectory }, diagnostics),
385
391
  });
386
392
  return {
387
393
  ...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),
@@ -426,8 +432,9 @@ async function runCompactionLadder(preparation, model, request, timeLimit) {
426
432
  }
427
433
  while (planner && !timeLimit.expired()) {
428
434
  let attempt;
435
+ const activePlanner = planner;
429
436
  try {
430
- attempt = await planWithTrimming(preparation, planner, plannerOptions);
437
+ attempt = await planWithRefusalRecovery(preparation, (candidate) => planWithTrimming(candidate, activePlanner, plannerOptions));
431
438
  }
432
439
  catch (error) {
433
440
  // The time limit aborted the in-flight request: end planning, not the run.
@@ -444,6 +451,7 @@ async function runCompactionLadder(preparation, model, request, timeLimit) {
444
451
  // a sidecar write failure never affects compaction success.
445
452
  writeSuccessDiagnosticSidecar({
446
453
  sessionFilePath: request.sessionFilePath,
454
+ sidecarDirectory: request.sidecarDirectory,
447
455
  model: planner.model,
448
456
  successCategory: "borrowed_planner",
449
457
  ...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),