@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
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EA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,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;gBAC7D,YAAY,GAAG,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5F,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,SAAS,CAAC,OAAO,EAAE;QAAE,YAAY,GAAG,SAAS,CAAC,OAAO,CAAC;IAC1D,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["import type {\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tRetryCallbacks,\n\tRetryPolicy,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { SessionEntry } from \"../session-manager-types.ts\";\nimport { planClassifierRanges } from \"./classifier-compaction.js\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { CompactionModelSelection } from \"./model-resolver.js\";\nimport { planMorphRanges } from \"./morph-compaction.js\";\nimport { runPiSummaryFallback } from \"./pi-summary-fallback.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/**\n\t * Per-model credentials; a borrowed candidate uses its own, never the session model's.\n\t * `signal` aborts when the run is cancelled or its planning time limit runs out.\n\t */\n\tresolveAuth: (model: Model<Api>, signal?: AbortSignal) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/**\n\t * Wall-clock limit on model planning: every backend, planner request, retry, overflow trim\n\t * and borrowed fallback model. When it runs out, the in-flight request is aborted and the\n\t * ladder ends as if every planner had failed (#4198). Omitted or non-positive means no limit.\n\t */\n\tplanningTimeoutMs?: number;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n\tcompactionModel?: CompactionModelSelection;\n\tresolveMorphApiKey?: () => Promise<string | undefined>;\n\tmorphFetchFn?: typeof fetch;\n\tclassify?: (\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t) => Promise<ClassifierResult>;\n\tsummaryEntries?: SessionEntry[];\n\tcwd?: string;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\tsummaryFirstKeptEntryId?: string;\n\tsummaryTokensBefore?: number;\n\t/** Present only on the fresh rung after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t\ttotalFromProvider:\n\t\t\t\t(total === undefined || total.cost.totalFromProvider === true) && usage.cost.totalFromProvider === true,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n\tmodel: string,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\tbackend: \"planner\",\n\t\tmodel,\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\" || outcome.kind === \"policyRefusal\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>,\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\n/**\n * Settle with `promise`, or reject as soon as `signal` aborts.\n *\n * Credential resolution may ignore the signal it is given; racing it keeps the\n * planning time limit and cancellation a hard bound on the ladder either way.\n */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n\tif (!signal) return promise;\n\tif (signal.aborted) {\n\t\tvoid promise.catch(() => {});\n\t\treturn Promise.reject(signal.reason);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tvoid promise.catch(() => {});\n\t\t\treject(signal.reason);\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The message a terminal planner outcome reports, as recorded on a fresh rung. */\nfunction terminalMessage(outcome: TerminalPlannerOutcome | undefined): string | undefined {\n\treturn outcome ? terminalError(outcome).message : undefined;\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n\tfreshReason?: string,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t\t...(freshReason ? { freshReason } : {}),\n\t};\n}\n\n/** The largest delay a platform timer accepts without clamping it to one millisecond. */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/**\n * One run's planning time limit.\n *\n * `signal` aborts on caller cancellation or when the limit runs out; only the latter sets\n * `expired`, so the ladder can tell a timeout (end planning, keep going) from cancellation\n * (stop the whole run).\n */\ninterface PlanningTimeLimit {\n\treadonly signal: AbortSignal | undefined;\n\texpired(): boolean;\n\treadonly outcome: TerminalPlannerOutcome;\n\tdispose(): void;\n}\n\nfunction startPlanningTimeLimit(timeoutMs: number | undefined, signal: AbortSignal | undefined): PlanningTimeLimit {\n\t// Any positive limit stays a limit: a sub-millisecond value rounds up rather than to \"disabled\".\n\tconst limitMs = timeoutMs !== undefined && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.ceil(timeoutMs) : 0;\n\tconst outcome: TerminalPlannerOutcome = {\n\t\tkind: \"providerError\",\n\t\tmessage: `Compaction planning timed out after ${limitMs} ms`,\n\t};\n\tif (limitMs <= 0) return { signal, expired: () => false, outcome, dispose: () => {} };\n\tconst controller = new AbortController();\n\tlet expired = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst startedAt = Date.now();\n\t// Re-arm in platform-sized steps so a limit beyond the timer maximum is honoured exactly.\n\tconst arm = () => {\n\t\tconst remainingMs = limitMs - (Date.now() - startedAt);\n\t\tif (remainingMs <= 0) {\n\t\t\texpired = true;\n\t\t\tcontroller.abort(new Error(outcome.message));\n\t\t\treturn;\n\t\t}\n\t\ttimer = setTimeout(arm, Math.min(remainingMs, MAX_TIMER_DELAY_MS));\n\t};\n\tarm();\n\tconst relayCancellation = () => controller.abort(signal?.reason);\n\tsignal?.addEventListener(\"abort\", relayCancellation, { once: true });\n\treturn {\n\t\tsignal: controller.signal,\n\t\texpired: () => expired,\n\t\toutcome,\n\t\tdispose: () => {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", relayCancellation);\n\t\t},\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n *\n * `planningTimeoutMs` bounds the whole planning phase. A planner that keeps\n * streaming never trips the per-request stream idle deadline, and retries,\n * trims and borrowed models each repeat it, so without this limit a mid-turn\n * compaction could hold the active turn for as long as the provider allowed.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tif (request.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst timeLimit = startPlanningTimeLimit(request.planningTimeoutMs, request.signal);\n\ttry {\n\t\treturn await runCompactionLadder(preparation, model, request, timeLimit);\n\t} finally {\n\t\ttimeLimit.dispose();\n\t}\n}\n\nasync function runCompactionLadder(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n\ttimeLimit: PlanningTimeLimit,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal: timeLimit.signal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\t// Credential waits count against the planning time limit too: each candidate's\n\t// resolution sees the limit's signal and is abandoned the moment it aborts. Once\n\t// it has aborted, no further lookup starts, so a borrower still walking its list\n\t// cannot launch abandoned work in a resolver that ignores the signal.\n\tconst resolveAuth = (candidate: Model<Api>): Promise<PlannerAuth | undefined> => {\n\t\tif (timeLimit.signal?.aborted) return Promise.reject(timeLimit.signal.reason);\n\t\treturn untilAborted(request.resolveAuth(candidate, timeLimit.signal), timeLimit.signal);\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst selection = request.compactionModel ?? { kind: \"chat\", fullId: `${model.provider}/${model.id}`, model };\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower({ ...request.fallback, selectedModelId: selection.fullId })\n\t\t: undefined;\n\tlet backendFailure: TerminalPlannerOutcome | undefined;\n\tif (selection.kind === \"classifier\") {\n\t\ttry {\n\t\t\tconst classify = request.classify;\n\t\t\tif (!classify) throw new Error(\"Compaction classifier is unavailable\");\n\t\t\tconst ranges = await planClassifierRanges(\n\t\t\t\tpreparation.region,\n\t\t\t\tpreparation.parameters,\n\t\t\t\t(context) => classify(selection.model, context, { signal: timeLimit.signal }),\n\t\t\t\tplannerOptions,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),\n\t\t\t\tbackend: \"classifier\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tif (selection.kind === \"morph\") {\n\t\ttry {\n\t\t\tconst ranges = await planMorphRanges(preparation.region, preparation.parameters, {\n\t\t\t\tapiKey: await untilAborted(Promise.resolve(request.resolveMorphApiKey?.()), timeLimit.signal),\n\t\t\t\tsignal: timeLimit.signal,\n\t\t\t\tfetchFn: request.morphFetchFn,\n\t\t\t\tonDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),\n\t\t\t\tbackend: \"morph\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tconst primaryModel = selection.kind === \"chat\" ? selection.model : undefined;\n\tconst primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);\n\tconst primaryAuth = primaryModel\n\t\t? await resolvePlannerAuth(resolveAuth, primaryModel)\n\t\t: {\n\t\t\t\tfailure: {\n\t\t\t\t\tkind: \"providerError\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\tbackendFailure?.kind === \"providerError\"\n\t\t\t\t\t\t\t? backendFailure.message\n\t\t\t\t\t\t\t: `Compaction backend ${selection.kind} is not yet available`,\n\t\t\t\t},\n\t\t\t};\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = primaryModel !== model;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (primaryModel && \"auth\" in primaryAuth) {\n\t\tplanner = { model: primaryModel, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\tif (primaryModel) attempted.add(plannerAttemptKey({ model: primaryModel, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\twhile (planner && !timeLimit.expired()) {\n\t\tlet attempt: PlannerAttempt;\n\t\ttry {\n\t\t\tattempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\t} catch (error) {\n\t\t\t// The time limit aborted the in-flight request: end planning, not the run.\n\t\t\tif (signal?.aborted || !timeLimit.expired()) throw error;\n\t\t\tbreak;\n\t\t}\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(\n\t\t\t\tpreparation,\n\t\t\t\tattempt.ranges,\n\t\t\t\tplannerModel,\n\t\t\t\tplannerUsage,\n\t\t\t\t`${planner.model.provider}/${planner.model.id}`,\n\t\t\t);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tif (attempt.outcome.kind === \"policyRefusal\" && request.summaryEntries) {\n\t\t\ttry {\n\t\t\t\tconst summary = await runPiSummaryFallback(request.summaryEntries, preparation.settings, planner, {\n\t\t\t\t\t...plannerOptions,\n\t\t\t\t\tcwd: request.cwd,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\ttext: summary.summary,\n\t\t\t\t\tranges: [],\n\t\t\t\t\tkeptRanges: [],\n\t\t\t\t\tstats: {\n\t\t\t\t\t\tlinesBefore: preparation.region.lines.length,\n\t\t\t\t\t\tlinesDeleted: 0,\n\t\t\t\t\t\tlinesKept: summary.summary.split(\"\\n\").length,\n\t\t\t\t\t\trangeCount: 0,\n\t\t\t\t\t\ttokensBefore: summary.tokensBefore,\n\t\t\t\t\t\ttokensAfter: summary.tokensAfter,\n\t\t\t\t\t\tpercentReduction:\n\t\t\t\t\t\t\tsummary.tokensBefore > 0 ? 100 * (1 - summary.tokensAfter / summary.tokensBefore) : 0,\n\t\t\t\t\t},\n\t\t\t\t\trung: \"planned\",\n\t\t\t\t\tkeptTail: true,\n\t\t\t\t\tbackend: \"summary\",\n\t\t\t\t\tmodel: `${planner.model.provider}/${planner.model.id}`,\n\t\t\t\t\tsummary: { readFiles: summary.readFiles, modifiedFiles: summary.modifiedFiles },\n\t\t\t\t\tsummaryFirstKeptEntryId: summary.firstKeptEntryId,\n\t\t\t\t\tsummaryTokensBefore: summary.tokensBefore,\n\t\t\t\t\t...(plannerUsage ? { usage: plannerUsage } : {}),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\tlastTerminal = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t}\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (timeLimit.expired()) lastTerminal = timeLimit.outcome;\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage, terminalMessage(lastTerminal));\n}\n"]}
1
+ {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,OAAO,EACN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CAAC,CAAC,CAAC,EAAE,CAAC;iBAChD,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;gBAC7D,YAAY,GAAG,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5F,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,SAAS,CAAC,OAAO,EAAE;QAAE,YAAY,GAAG,SAAS,CAAC,OAAO,CAAC;IAC1D,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["import type {\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tRetryCallbacks,\n\tRetryPolicy,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { SessionEntry } from \"../session-manager-types.ts\";\nimport { planClassifierRanges } from \"./classifier-compaction.js\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { CompactionModelSelection } from \"./model-resolver.js\";\nimport { planMorphRanges } from \"./morph-compaction.js\";\nimport { runPiSummaryFallback } from \"./pi-summary-fallback.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport {\n\ttype SidecarDirectory,\n\twriteMorphDiagnosticSidecar,\n\twriteSuccessDiagnosticSidecar,\n} from \"./range-planner-diagnostics.js\";\nimport { type PlannerAttempt, planWithRefusalRecovery } from \"./refusal-recovery.js\";\nimport { keepTargetForView, nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\t/** Where diagnostics go for a persisted session that has no session file, such as one in SQLite. */\n\tsidecarDirectory?: SidecarDirectory;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/**\n\t * Per-model credentials; a borrowed candidate uses its own, never the session model's.\n\t * `signal` aborts when the run is cancelled or its planning time limit runs out.\n\t */\n\tresolveAuth: (model: Model<Api>, signal?: AbortSignal) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/**\n\t * Wall-clock limit on model planning: every backend, planner request, retry, overflow trim\n\t * and borrowed fallback model. When it runs out, the in-flight request is aborted and the\n\t * ladder ends as if every planner had failed (#4198). Omitted or non-positive means no limit.\n\t */\n\tplanningTimeoutMs?: number;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n\tcompactionModel?: CompactionModelSelection;\n\tresolveMorphApiKey?: () => Promise<string | undefined>;\n\tmorphFetchFn?: typeof fetch;\n\tclassify?: (\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t) => Promise<ClassifierResult>;\n\tsummaryEntries?: SessionEntry[];\n\tcwd?: string;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\tsummaryFirstKeptEntryId?: string;\n\tsummaryTokensBefore?: number;\n\t/** Present only on the fresh rung after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t\ttotalFromProvider:\n\t\t\t\t(total === undefined || total.cost.totalFromProvider === true) && usage.cost.totalFromProvider === true,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n\tmodel: string,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\tbackend: \"planner\",\n\t\tmodel,\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\" || outcome.kind === \"policyRefusal\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = keepTargetForView(region, preparation.parameters.compression_ratio);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>,\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\n/**\n * Settle with `promise`, or reject as soon as `signal` aborts.\n *\n * Credential resolution may ignore the signal it is given; racing it keeps the\n * planning time limit and cancellation a hard bound on the ladder either way.\n */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n\tif (!signal) return promise;\n\tif (signal.aborted) {\n\t\tvoid promise.catch(() => {});\n\t\treturn Promise.reject(signal.reason);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tvoid promise.catch(() => {});\n\t\t\treject(signal.reason);\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The message a terminal planner outcome reports, as recorded on a fresh rung. */\nfunction terminalMessage(outcome: TerminalPlannerOutcome | undefined): string | undefined {\n\treturn outcome ? terminalError(outcome).message : undefined;\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n\tfreshReason?: string,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t\t...(freshReason ? { freshReason } : {}),\n\t};\n}\n\n/** The largest delay a platform timer accepts without clamping it to one millisecond. */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/**\n * One run's planning time limit.\n *\n * `signal` aborts on caller cancellation or when the limit runs out; only the latter sets\n * `expired`, so the ladder can tell a timeout (end planning, keep going) from cancellation\n * (stop the whole run).\n */\ninterface PlanningTimeLimit {\n\treadonly signal: AbortSignal | undefined;\n\texpired(): boolean;\n\treadonly outcome: TerminalPlannerOutcome;\n\tdispose(): void;\n}\n\nfunction startPlanningTimeLimit(timeoutMs: number | undefined, signal: AbortSignal | undefined): PlanningTimeLimit {\n\t// Any positive limit stays a limit: a sub-millisecond value rounds up rather than to \"disabled\".\n\tconst limitMs = timeoutMs !== undefined && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.ceil(timeoutMs) : 0;\n\tconst outcome: TerminalPlannerOutcome = {\n\t\tkind: \"providerError\",\n\t\tmessage: `Compaction planning timed out after ${limitMs} ms`,\n\t};\n\tif (limitMs <= 0) return { signal, expired: () => false, outcome, dispose: () => {} };\n\tconst controller = new AbortController();\n\tlet expired = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst startedAt = Date.now();\n\t// Re-arm in platform-sized steps so a limit beyond the timer maximum is honoured exactly.\n\tconst arm = () => {\n\t\tconst remainingMs = limitMs - (Date.now() - startedAt);\n\t\tif (remainingMs <= 0) {\n\t\t\texpired = true;\n\t\t\tcontroller.abort(new Error(outcome.message));\n\t\t\treturn;\n\t\t}\n\t\ttimer = setTimeout(arm, Math.min(remainingMs, MAX_TIMER_DELAY_MS));\n\t};\n\tarm();\n\tconst relayCancellation = () => controller.abort(signal?.reason);\n\tsignal?.addEventListener(\"abort\", relayCancellation, { once: true });\n\treturn {\n\t\tsignal: controller.signal,\n\t\texpired: () => expired,\n\t\toutcome,\n\t\tdispose: () => {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", relayCancellation);\n\t\t},\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * A planner that is refused partway through its output (#4543) is retried once and then given the\n * region in parts split at message boundaries; the lossy summary fallback runs only after that\n * fails, or at once for an immediate input refusal.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n *\n * `planningTimeoutMs` bounds the whole planning phase. A planner that keeps\n * streaming never trips the per-request stream idle deadline, and retries,\n * trims and borrowed models each repeat it, so without this limit a mid-turn\n * compaction could hold the active turn for as long as the provider allowed.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tif (request.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst timeLimit = startPlanningTimeLimit(request.planningTimeoutMs, request.signal);\n\ttry {\n\t\treturn await runCompactionLadder(preparation, model, request, timeLimit);\n\t} finally {\n\t\ttimeLimit.dispose();\n\t}\n}\n\nasync function runCompactionLadder(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n\ttimeLimit: PlanningTimeLimit,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tsidecarDirectory: request.sidecarDirectory,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal: timeLimit.signal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\t// Credential waits count against the planning time limit too: each candidate's\n\t// resolution sees the limit's signal and is abandoned the moment it aborts. Once\n\t// it has aborted, no further lookup starts, so a borrower still walking its list\n\t// cannot launch abandoned work in a resolver that ignores the signal.\n\tconst resolveAuth = (candidate: Model<Api>): Promise<PlannerAuth | undefined> => {\n\t\tif (timeLimit.signal?.aborted) return Promise.reject(timeLimit.signal.reason);\n\t\treturn untilAborted(request.resolveAuth(candidate, timeLimit.signal), timeLimit.signal);\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst selection = request.compactionModel ?? { kind: \"chat\", fullId: `${model.provider}/${model.id}`, model };\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower({ ...request.fallback, selectedModelId: selection.fullId })\n\t\t: undefined;\n\tlet backendFailure: TerminalPlannerOutcome | undefined;\n\tif (selection.kind === \"classifier\") {\n\t\ttry {\n\t\t\tconst classify = request.classify;\n\t\t\tif (!classify) throw new Error(\"Compaction classifier is unavailable\");\n\t\t\tconst ranges = await planClassifierRanges(\n\t\t\t\tpreparation.region,\n\t\t\t\tpreparation.parameters,\n\t\t\t\t(context) => classify(selection.model, context, { signal: timeLimit.signal }),\n\t\t\t\tplannerOptions,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),\n\t\t\t\tbackend: \"classifier\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tif (selection.kind === \"morph\") {\n\t\ttry {\n\t\t\tconst ranges = await planMorphRanges(preparation.region, preparation.parameters, {\n\t\t\t\tapiKey: await untilAborted(Promise.resolve(request.resolveMorphApiKey?.()), timeLimit.signal),\n\t\t\t\tsignal: timeLimit.signal,\n\t\t\t\tfetchFn: request.morphFetchFn,\n\t\t\t\tonDiagnostics: (diagnostics) =>\n\t\t\t\t\twriteMorphDiagnosticSidecar(\n\t\t\t\t\t\t{ sessionFilePath: request.sessionFilePath, sidecarDirectory: request.sidecarDirectory },\n\t\t\t\t\t\tdiagnostics,\n\t\t\t\t\t),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),\n\t\t\t\tbackend: \"morph\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tconst primaryModel = selection.kind === \"chat\" ? selection.model : undefined;\n\tconst primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);\n\tconst primaryAuth = primaryModel\n\t\t? await resolvePlannerAuth(resolveAuth, primaryModel)\n\t\t: {\n\t\t\t\tfailure: {\n\t\t\t\t\tkind: \"providerError\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\tbackendFailure?.kind === \"providerError\"\n\t\t\t\t\t\t\t? backendFailure.message\n\t\t\t\t\t\t\t: `Compaction backend ${selection.kind} is not yet available`,\n\t\t\t\t},\n\t\t\t};\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = primaryModel !== model;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (primaryModel && \"auth\" in primaryAuth) {\n\t\tplanner = { model: primaryModel, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\tif (primaryModel) attempted.add(plannerAttemptKey({ model: primaryModel, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\twhile (planner && !timeLimit.expired()) {\n\t\tlet attempt: PlannerAttempt;\n\t\tconst activePlanner = planner;\n\t\ttry {\n\t\t\tattempt = await planWithRefusalRecovery(preparation, (candidate) =>\n\t\t\t\tplanWithTrimming(candidate, activePlanner, plannerOptions),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The time limit aborted the in-flight request: end planning, not the run.\n\t\t\tif (signal?.aborted || !timeLimit.expired()) throw error;\n\t\t\tbreak;\n\t\t}\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tsidecarDirectory: request.sidecarDirectory,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(\n\t\t\t\tpreparation,\n\t\t\t\tattempt.ranges,\n\t\t\t\tplannerModel,\n\t\t\t\tplannerUsage,\n\t\t\t\t`${planner.model.provider}/${planner.model.id}`,\n\t\t\t);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tif (attempt.outcome.kind === \"policyRefusal\" && request.summaryEntries) {\n\t\t\ttry {\n\t\t\t\tconst summary = await runPiSummaryFallback(request.summaryEntries, preparation.settings, planner, {\n\t\t\t\t\t...plannerOptions,\n\t\t\t\t\tcwd: request.cwd,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\ttext: summary.summary,\n\t\t\t\t\tranges: [],\n\t\t\t\t\tkeptRanges: [],\n\t\t\t\t\tstats: {\n\t\t\t\t\t\tlinesBefore: preparation.region.lines.length,\n\t\t\t\t\t\tlinesDeleted: 0,\n\t\t\t\t\t\tlinesKept: summary.summary.split(\"\\n\").length,\n\t\t\t\t\t\trangeCount: 0,\n\t\t\t\t\t\ttokensBefore: summary.tokensBefore,\n\t\t\t\t\t\ttokensAfter: summary.tokensAfter,\n\t\t\t\t\t\tpercentReduction:\n\t\t\t\t\t\t\tsummary.tokensBefore > 0 ? 100 * (1 - summary.tokensAfter / summary.tokensBefore) : 0,\n\t\t\t\t\t},\n\t\t\t\t\trung: \"planned\",\n\t\t\t\t\tkeptTail: true,\n\t\t\t\t\tbackend: \"summary\",\n\t\t\t\t\tmodel: `${planner.model.provider}/${planner.model.id}`,\n\t\t\t\t\tsummary: { readFiles: summary.readFiles, modifiedFiles: summary.modifiedFiles },\n\t\t\t\t\tsummaryFirstKeptEntryId: summary.firstKeptEntryId,\n\t\t\t\t\tsummaryTokensBefore: summary.tokensBefore,\n\t\t\t\t\t...(plannerUsage ? { usage: plannerUsage } : {}),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\tlastTerminal = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t}\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (timeLimit.expired()) lastTerminal = timeLimit.outcome;\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage, terminalMessage(lastTerminal));\n}\n"]}
@@ -2,7 +2,7 @@ import type { ProviderHeaders } from "@bastani/pi-ai";
2
2
  import type { Api, Model, Usage } from "@bastani/pi-ai/compat";
3
3
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
4
  import type { CompactionSettings } from "./compaction.ts";
5
- export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 5;
5
+ export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 6;
6
6
  /** First prompt version whose durable transcripts carry no `[Assistant thinking]: ` sections. */
7
7
  export declare const THINKING_FREE_PROMPT_VERSION = 5;
8
8
  export declare const VERBATIM_COMPACTION_STRATEGY: "verbatim-lines";
@@ -1,4 +1,4 @@
1
- export const VERBATIM_COMPACTION_PROMPT_VERSION = 5;
1
+ export const VERBATIM_COMPACTION_PROMPT_VERSION = 6;
2
2
  /** First prompt version whose durable transcripts carry no `[Assistant thinking]: ` sections. */
3
3
  export const THINKING_FREE_PROMPT_VERSION = 5;
4
4
  export const VERBATIM_COMPACTION_STRATEGY = "verbatim-lines";
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,iGAAiG;AACjG,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 5 as const;\n/** First prompt version whose durable transcripts carry no `[Assistant thinking]: ` sections. */\nexport const THINKING_FREE_PROMPT_VERSION = 5;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\tmessageSpans?: { role: \"user\" | \"assistant\" | \"tool\"; start: number; end: number }[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed, e.g. `Compaction planning timed out after 300000 ms`. */\n\tfreshReason?: string;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
1
+ {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,iGAAiG;AACjG,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAC9C,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 6 as const;\n/** First prompt version whose durable transcripts carry no `[Assistant thinking]: ` sections. */\nexport const THINKING_FREE_PROMPT_VERSION = 5;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\tmessageSpans?: { role: \"user\" | \"assistant\" | \"tool\"; start: number; end: number }[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed, e.g. `Compaction planning timed out after 300000 ms`. */\n\tfreshReason?: string;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
@@ -1,6 +1,21 @@
1
1
  import type { CompactedTranscript, NumberedRegion, RawLineRange, ValidatedRanges } from "./compaction-types.js";
2
- /** Normalize untrusted model ranges into the sole range type accepted by reconstruction. */
3
- export declare function validateDeletedRanges(raw: RawLineRange[], region: NumberedRegion): ValidatedRanges;
2
+ /** Extra share of the region the planner may delete beyond the keep target before records stop applying. */
3
+ export declare const KEEP_TARGET_TOLERANCE_RATIO = 0.05;
4
+ /** Unprotected lines a plan may delete: the target delete count plus the named tolerance, at least one for a non-empty region. */
5
+ export declare function deleteBudget(totalLines: number, targetKeepLines: number): number;
6
+ export interface ValidateDeletedRangesOptions {
7
+ /**
8
+ * Apply records in emitted order and stop once this many unprotected lines are
9
+ * deleted, clipping the record that crosses the limit to its leading new lines.
10
+ * Omitted, every record applies.
11
+ */
12
+ maxDeletedLines?: number;
13
+ }
14
+ /**
15
+ * Normalize untrusted model ranges into the sole range type accepted by reconstruction.
16
+ * The output is sorted and merged; `maxDeletedLines` limits it by emitted (priority) order first.
17
+ */
18
+ export declare function validateDeletedRanges(raw: RawLineRange[], region: NumberedRegion, options?: ValidateDeletedRangesOptions): ValidatedRanges;
4
19
  /** Rebuild a compacted transcript mechanically from validated ranges. */
5
20
  export declare function reconstructCompactedTranscript(region: NumberedRegion, ranges: ValidatedRanges): CompactedTranscript;
6
21
  //# sourceMappingURL=deleted-ranges.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deleted-ranges.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/deleted-ranges.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,mBAAmB,EAEnB,cAAc,EAEd,YAAY,EACZ,eAAe,EACf,MAAM,uBAAuB,CAAC;AAgC/B,4FAA4F;AAC5F,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,eAAe,CAiBlG;AAmDD,yEAAyE;AACzE,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,eAAe,GAAG,mBAAmB,CA8BnH"}
1
+ {"version":3,"file":"deleted-ranges.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/deleted-ranges.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,mBAAmB,EAEnB,cAAc,EAEd,YAAY,EACZ,eAAe,EACf,MAAM,uBAAuB,CAAC;AAgC/B,4GAA4G;AAC5G,eAAO,MAAM,2BAA2B,OAAO,CAAC;AAEhD,kIAAkI;AAClI,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAEhF;AAED,MAAM,WAAW,4BAA4B;IAC5C;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AA4CD;;;GAGG;AACH,wBAAgB,qBAAqB,CACpC,GAAG,EAAE,YAAY,EAAE,EACnB,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,4BAAiC,GACxC,eAAe,CAWjB;AAmDD,yEAAyE;AACzE,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,eAAe,GAAG,mBAAmB,CA8BnH"}
@@ -31,9 +31,13 @@ function splitAroundProtected(range, protectedLines) {
31
31
  fragments.push({ start, end: range.end });
32
32
  return fragments;
33
33
  }
34
- /** Normalize untrusted model ranges into the sole range type accepted by reconstruction. */
35
- export function validateDeletedRanges(raw, region) {
36
- const totalLines = region.lines.length;
34
+ /** Extra share of the region the planner may delete beyond the keep target before records stop applying. */
35
+ export const KEEP_TARGET_TOLERANCE_RATIO = 0.05;
36
+ /** Unprotected lines a plan may delete: the target delete count plus the named tolerance, at least one for a non-empty region. */
37
+ export function deleteBudget(totalLines, targetKeepLines) {
38
+ return Math.max(0, totalLines - targetKeepLines) + Math.ceil(totalLines * KEEP_TARGET_TOLERANCE_RATIO);
39
+ }
40
+ function normalizeRanges(raw, totalLines) {
37
41
  const normalized = [];
38
42
  for (const candidate of raw) {
39
43
  let start = coerceEndpoint(candidate.start);
@@ -47,9 +51,44 @@ export function validateDeletedRanges(raw, region) {
47
51
  if (start <= end)
48
52
  normalized.push({ start, end });
49
53
  }
50
- normalized.sort((left, right) => left.start - right.start || left.end - right.end);
54
+ return normalized;
55
+ }
56
+ function capInEmittedOrder(records, protectedLines, totalLines, maxDeletedLines) {
57
+ const taken = new Uint8Array(totalLines + 1);
58
+ const accepted = [];
59
+ let remaining = Math.max(0, Math.trunc(maxDeletedLines));
60
+ for (const record of records) {
61
+ let runStart;
62
+ for (let line = record.start; line <= record.end + 1 && remaining > 0; line++) {
63
+ const available = line <= record.end && !taken[line] && !protectedLines.has(line);
64
+ if (available) {
65
+ taken[line] = 1;
66
+ remaining--;
67
+ runStart ??= line;
68
+ }
69
+ if ((!available || remaining === 0) && runStart !== undefined) {
70
+ accepted.push({ start: runStart, end: available ? line : line - 1 });
71
+ runStart = undefined;
72
+ }
73
+ }
74
+ if (remaining === 0)
75
+ break;
76
+ }
77
+ return accepted;
78
+ }
79
+ /**
80
+ * Normalize untrusted model ranges into the sole range type accepted by reconstruction.
81
+ * The output is sorted and merged; `maxDeletedLines` limits it by emitted (priority) order first.
82
+ */
83
+ export function validateDeletedRanges(raw, region, options = {}) {
84
+ const totalLines = region.lines.length;
51
85
  const protectedLines = new Set(region.protectedLineNumbers ?? []);
52
- const split = mergeRanges(normalized).flatMap((range) => splitAroundProtected(range, protectedLines));
86
+ const normalized = normalizeRanges(raw, totalLines);
87
+ const selected = options.maxDeletedLines === undefined
88
+ ? normalized
89
+ : capInEmittedOrder(normalized, protectedLines, totalLines, options.maxDeletedLines);
90
+ selected.sort((left, right) => left.start - right.start || left.end - right.end);
91
+ const split = mergeRanges(selected).flatMap((range) => splitAroundProtected(range, protectedLines));
53
92
  return Object.assign(split, { __brand: "ValidatedRanges" });
54
93
  }
55
94
  function rangesToDeletedLines(ranges, lineCount) {
@@ -1 +1 @@
1
- {"version":3,"file":"deleted-ranges.js","sourceRoot":"","sources":["../../../src/core/compaction/deleted-ranges.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,E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CAAC,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAClG,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC/C,MAAM,gBAAgB,GACrB,MAAM,CAAC,aAAa,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACnG,OAAO;QACN,IAAI;QACJ,MAAM,EAAE,WAAW;QACnB,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,oBAAoB,IAAI,IAAI,GAAG,EAAU,CAAC;QAC9E,KAAK,EAAE;YACN,WAAW,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM;YAChC,YAAY;YACZ,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,YAAY;YAC7C,UAAU,EAAE,WAAW,CAAC,MAAM;YAC9B,YAAY,EAAE,MAAM,CAAC,aAAa;YAClC,WAAW;YACX,gBAAgB;SAChB;KACD,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tCompactedTranscript,\n\tLineRange,\n\tNumberedRegion,\n\tRawLineEndpoint,\n\tRawLineRange,\n\tValidatedRanges,\n} from \"./compaction-types.js\";\nimport { filteredMarker } from \"./transcript-serialization.js\";\nimport { contiguousRanges } from \"./utils.ts\";\n\nfunction coerceEndpoint(value: RawLineEndpoint | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tconst number = Number(value);\n\treturn Number.isFinite(number) ? Math.trunc(number) : undefined;\n}\n\nfunction mergeRanges(ranges: LineRange[]): LineRange[] {\n\tconst merged: LineRange[] = [];\n\tfor (const range of ranges) {\n\t\tconst current = merged[merged.length - 1];\n\t\tif (current && range.start <= current.end + 1) current.end = Math.max(current.end, range.end);\n\t\telse merged.push({ ...range });\n\t}\n\treturn merged;\n}\n\nfunction splitAroundProtected(range: LineRange, protectedLines: ReadonlySet<number>): LineRange[] {\n\tconst fragments: LineRange[] = [];\n\tlet start = range.start;\n\tfor (let line = range.start; line <= range.end; line++) {\n\t\tif (!protectedLines.has(line)) continue;\n\t\tif (start < line) fragments.push({ start, end: line - 1 });\n\t\tstart = line + 1;\n\t}\n\tif (start <= range.end) fragments.push({ start, end: range.end });\n\treturn fragments;\n}\n\n/** Normalize untrusted model ranges into the sole range type accepted by reconstruction. */\nexport function validateDeletedRanges(raw: RawLineRange[], region: NumberedRegion): ValidatedRanges {\n\tconst totalLines = region.lines.length;\n\tconst normalized: LineRange[] = [];\n\tfor (const candidate of raw) {\n\t\tlet start = coerceEndpoint(candidate.start);\n\t\tlet end = coerceEndpoint(candidate.end);\n\t\tif (start === undefined || end === undefined) continue;\n\t\tif (start > end) [start, end] = [end, start];\n\t\tstart = Math.max(1, start);\n\t\tend = Math.min(totalLines, end);\n\t\tif (start <= end) normalized.push({ start, end });\n\t}\n\tnormalized.sort((left, right) => left.start - right.start || left.end - right.end);\n\n\tconst protectedLines = new Set(region.protectedLineNumbers ?? []);\n\tconst split = mergeRanges(normalized).flatMap((range) => splitAroundProtected(range, protectedLines));\n\treturn Object.assign(split, { __brand: \"ValidatedRanges\" as const });\n}\n\nfunction rangesToDeletedLines(ranges: ValidatedRanges, lineCount: number): boolean[] {\n\tconst deleted = Array.from({ length: lineCount }, () => false);\n\tfor (const range of ranges) {\n\t\tfor (let line = range.start; line <= range.end; line++) deleted[line - 1] = true;\n\t}\n\treturn deleted;\n}\n\nfunction foldAdjacentMarkers(region: NumberedRegion, ranges: ValidatedRanges): LineRange[] {\n\tconst deleted = rangesToDeletedLines(ranges, region.lines.length);\n\tlet changed = true;\n\twhile (changed) {\n\t\tchanged = false;\n\t\tfor (const lineNumber of region.priorMarkerNs.keys()) {\n\t\t\tconst index = lineNumber - 1;\n\t\t\tif (deleted[index]) continue;\n\t\t\tconst previousDeleted = index > 0 ? (deleted[index - 1] ?? false) : false;\n\t\t\tconst nextDeleted = index + 1 < deleted.length ? (deleted[index + 1] ?? false) : false;\n\t\t\tif (previousDeleted || nextDeleted) {\n\t\t\t\tdeleted[index] = true;\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst folded: LineRange[] = [];\n\tlet start: number | undefined;\n\tfor (let index = 0; index <= deleted.length; index++) {\n\t\t// Sentinel iteration at index === deleted.length: treat as not deleted so a\n\t\t// trailing open range closes without reading past the array bounds.\n\t\tconst isDeleted = index < deleted.length ? (deleted[index] ?? false) : false;\n\t\tif (isDeleted && start === undefined) start = index + 1;\n\t\tif (!isDeleted && start !== undefined) {\n\t\t\tfolded.push({ start, end: index });\n\t\t\tstart = undefined;\n\t\t}\n\t}\n\treturn folded;\n}\n\nfunction cumulativeDeletedCount(region: NumberedRegion, range: LineRange): number {\n\tlet count = range.end - range.start + 1;\n\tfor (let line = range.start; line <= range.end; line++) {\n\t\tconst priorCount = region.priorMarkerNs.get(line);\n\t\tif (priorCount !== undefined) count += priorCount - 1;\n\t}\n\treturn count;\n}\n\n/** Rebuild a compacted transcript mechanically from validated ranges. */\nexport function reconstructCompactedTranscript(region: NumberedRegion, ranges: ValidatedRanges): CompactedTranscript {\n\tconst finalRanges = foldAdjacentMarkers(region, ranges);\n\tconst output: string[] = [];\n\tlet line = 1;\n\tfor (const range of finalRanges) {\n\t\twhile (line < range.start) output.push(region.lines[line++ - 1]);\n\t\toutput.push(filteredMarker(cumulativeDeletedCount(region, range)));\n\t\tline = range.end + 1;\n\t}\n\twhile (line <= region.lines.length) output.push(region.lines[line++ - 1]);\n\n\tconst text = output.join(\"\\n\");\n\tconst linesDeleted = finalRanges.reduce((total, range) => total + range.end - range.start + 1, 0);\n\tconst tokensAfter = Math.ceil(text.length / 4);\n\tconst percentReduction =\n\t\tregion.tokenEstimate === 0 ? 0 : Math.round((1 - tokensAfter / region.tokenEstimate) * 1000) / 10;\n\treturn {\n\t\ttext,\n\t\tranges: finalRanges,\n\t\tkeptRanges: contiguousRanges(region.protectedLineNumbers ?? new Set<number>()),\n\t\tstats: {\n\t\t\tlinesBefore: region.lines.length,\n\t\t\tlinesDeleted,\n\t\t\tlinesKept: region.lines.length - linesDeleted,\n\t\t\trangeCount: finalRanges.length,\n\t\t\ttokensBefore: region.tokenEstimate,\n\t\t\ttokensAfter,\n\t\t\tpercentReduction,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"deleted-ranges.js","sourceRoot":"","sources":["../../../src/core/compaction/deleted-ranges.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,SAAS,cAAc,CAAC,KAAkC;IACzD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC7B,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AAED,SAAS,WAAW,CAAC,MAAmB;IACvC,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC5B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC1C,IAAI,OAAO,IAAI,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,GAAG,GAAG,CAAC;YAAE,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;;YACzF,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,MAAM,CAA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,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACnG,OAAO;QACN,IAAI;QACJ,MAAM,EAAE,WAAW;QACnB,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,oBAAoB,IAAI,IAAI,GAAG,EAAU,CAAC;QAC9E,KAAK,EAAE;YACN,WAAW,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM;YAChC,YAAY;YACZ,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,YAAY;YAC7C,UAAU,EAAE,WAAW,CAAC,MAAM;YAC9B,YAAY,EAAE,MAAM,CAAC,aAAa;YAClC,WAAW;YACX,gBAAgB;SAChB;KACD,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tCompactedTranscript,\n\tLineRange,\n\tNumberedRegion,\n\tRawLineEndpoint,\n\tRawLineRange,\n\tValidatedRanges,\n} from \"./compaction-types.js\";\nimport { filteredMarker } from \"./transcript-serialization.js\";\nimport { contiguousRanges } from \"./utils.ts\";\n\nfunction coerceEndpoint(value: RawLineEndpoint | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tconst number = Number(value);\n\treturn Number.isFinite(number) ? Math.trunc(number) : undefined;\n}\n\nfunction mergeRanges(ranges: LineRange[]): LineRange[] {\n\tconst merged: LineRange[] = [];\n\tfor (const range of ranges) {\n\t\tconst current = merged[merged.length - 1];\n\t\tif (current && range.start <= current.end + 1) current.end = Math.max(current.end, range.end);\n\t\telse merged.push({ ...range });\n\t}\n\treturn merged;\n}\n\nfunction splitAroundProtected(range: LineRange, protectedLines: ReadonlySet<number>): LineRange[] {\n\tconst fragments: LineRange[] = [];\n\tlet start = range.start;\n\tfor (let line = range.start; line <= range.end; line++) {\n\t\tif (!protectedLines.has(line)) continue;\n\t\tif (start < line) fragments.push({ start, end: line - 1 });\n\t\tstart = line + 1;\n\t}\n\tif (start <= range.end) fragments.push({ start, end: range.end });\n\treturn fragments;\n}\n\n/** Extra share of the region the planner may delete beyond the keep target before records stop applying. */\nexport const KEEP_TARGET_TOLERANCE_RATIO = 0.05;\n\n/** Unprotected lines a plan may delete: the target delete count plus the named tolerance, at least one for a non-empty region. */\nexport function deleteBudget(totalLines: number, targetKeepLines: number): number {\n\treturn Math.max(0, totalLines - targetKeepLines) + Math.ceil(totalLines * KEEP_TARGET_TOLERANCE_RATIO);\n}\n\nexport interface ValidateDeletedRangesOptions {\n\t/**\n\t * Apply records in emitted order and stop once this many unprotected lines are\n\t * deleted, clipping the record that crosses the limit to its leading new lines.\n\t * Omitted, every record applies.\n\t */\n\tmaxDeletedLines?: number;\n}\n\nfunction normalizeRanges(raw: RawLineRange[], totalLines: number): LineRange[] {\n\tconst normalized: LineRange[] = [];\n\tfor (const candidate of raw) {\n\t\tlet start = coerceEndpoint(candidate.start);\n\t\tlet end = coerceEndpoint(candidate.end);\n\t\tif (start === undefined || end === undefined) continue;\n\t\tif (start > end) [start, end] = [end, start];\n\t\tstart = Math.max(1, start);\n\t\tend = Math.min(totalLines, end);\n\t\tif (start <= end) normalized.push({ start, end });\n\t}\n\treturn normalized;\n}\n\nfunction capInEmittedOrder(\n\trecords: readonly LineRange[],\n\tprotectedLines: ReadonlySet<number>,\n\ttotalLines: number,\n\tmaxDeletedLines: number,\n): LineRange[] {\n\tconst taken = new Uint8Array(totalLines + 1);\n\tconst accepted: LineRange[] = [];\n\tlet remaining = Math.max(0, Math.trunc(maxDeletedLines));\n\tfor (const record of records) {\n\t\tlet runStart: number | undefined;\n\t\tfor (let line = record.start; line <= record.end + 1 && remaining > 0; line++) {\n\t\t\tconst available = line <= record.end && !taken[line] && !protectedLines.has(line);\n\t\t\tif (available) {\n\t\t\t\ttaken[line] = 1;\n\t\t\t\tremaining--;\n\t\t\t\trunStart ??= line;\n\t\t\t}\n\t\t\tif ((!available || remaining === 0) && runStart !== undefined) {\n\t\t\t\taccepted.push({ start: runStart, end: available ? line : line - 1 });\n\t\t\t\trunStart = undefined;\n\t\t\t}\n\t\t}\n\t\tif (remaining === 0) break;\n\t}\n\treturn accepted;\n}\n\n/**\n * Normalize untrusted model ranges into the sole range type accepted by reconstruction.\n * The output is sorted and merged; `maxDeletedLines` limits it by emitted (priority) order first.\n */\nexport function validateDeletedRanges(\n\traw: RawLineRange[],\n\tregion: NumberedRegion,\n\toptions: ValidateDeletedRangesOptions = {},\n): ValidatedRanges {\n\tconst totalLines = region.lines.length;\n\tconst protectedLines = new Set(region.protectedLineNumbers ?? []);\n\tconst normalized = normalizeRanges(raw, totalLines);\n\tconst selected =\n\t\toptions.maxDeletedLines === undefined\n\t\t\t? normalized\n\t\t\t: capInEmittedOrder(normalized, protectedLines, totalLines, options.maxDeletedLines);\n\tselected.sort((left, right) => left.start - right.start || left.end - right.end);\n\tconst split = mergeRanges(selected).flatMap((range) => splitAroundProtected(range, protectedLines));\n\treturn Object.assign(split, { __brand: \"ValidatedRanges\" as const });\n}\n\nfunction rangesToDeletedLines(ranges: ValidatedRanges, lineCount: number): boolean[] {\n\tconst deleted = Array.from({ length: lineCount }, () => false);\n\tfor (const range of ranges) {\n\t\tfor (let line = range.start; line <= range.end; line++) deleted[line - 1] = true;\n\t}\n\treturn deleted;\n}\n\nfunction foldAdjacentMarkers(region: NumberedRegion, ranges: ValidatedRanges): LineRange[] {\n\tconst deleted = rangesToDeletedLines(ranges, region.lines.length);\n\tlet changed = true;\n\twhile (changed) {\n\t\tchanged = false;\n\t\tfor (const lineNumber of region.priorMarkerNs.keys()) {\n\t\t\tconst index = lineNumber - 1;\n\t\t\tif (deleted[index]) continue;\n\t\t\tconst previousDeleted = index > 0 ? (deleted[index - 1] ?? false) : false;\n\t\t\tconst nextDeleted = index + 1 < deleted.length ? (deleted[index + 1] ?? false) : false;\n\t\t\tif (previousDeleted || nextDeleted) {\n\t\t\t\tdeleted[index] = true;\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst folded: LineRange[] = [];\n\tlet start: number | undefined;\n\tfor (let index = 0; index <= deleted.length; index++) {\n\t\t// Sentinel iteration at index === deleted.length: treat as not deleted so a\n\t\t// trailing open range closes without reading past the array bounds.\n\t\tconst isDeleted = index < deleted.length ? (deleted[index] ?? false) : false;\n\t\tif (isDeleted && start === undefined) start = index + 1;\n\t\tif (!isDeleted && start !== undefined) {\n\t\t\tfolded.push({ start, end: index });\n\t\t\tstart = undefined;\n\t\t}\n\t}\n\treturn folded;\n}\n\nfunction cumulativeDeletedCount(region: NumberedRegion, range: LineRange): number {\n\tlet count = range.end - range.start + 1;\n\tfor (let line = range.start; line <= range.end; line++) {\n\t\tconst priorCount = region.priorMarkerNs.get(line);\n\t\tif (priorCount !== undefined) count += priorCount - 1;\n\t}\n\treturn count;\n}\n\n/** Rebuild a compacted transcript mechanically from validated ranges. */\nexport function reconstructCompactedTranscript(region: NumberedRegion, ranges: ValidatedRanges): CompactedTranscript {\n\tconst finalRanges = foldAdjacentMarkers(region, ranges);\n\tconst output: string[] = [];\n\tlet line = 1;\n\tfor (const range of finalRanges) {\n\t\twhile (line < range.start) output.push(region.lines[line++ - 1]);\n\t\toutput.push(filteredMarker(cumulativeDeletedCount(region, range)));\n\t\tline = range.end + 1;\n\t}\n\twhile (line <= region.lines.length) output.push(region.lines[line++ - 1]);\n\n\tconst text = output.join(\"\\n\");\n\tconst linesDeleted = finalRanges.reduce((total, range) => total + range.end - range.start + 1, 0);\n\tconst tokensAfter = Math.ceil(text.length / 4);\n\tconst percentReduction =\n\t\tregion.tokenEstimate === 0 ? 0 : Math.round((1 - tokensAfter / region.tokenEstimate) * 1000) / 10;\n\treturn {\n\t\ttext,\n\t\tranges: finalRanges,\n\t\tkeptRanges: contiguousRanges(region.protectedLineNumbers ?? new Set<number>()),\n\t\tstats: {\n\t\t\tlinesBefore: region.lines.length,\n\t\t\tlinesDeleted,\n\t\t\tlinesKept: region.lines.length - linesDeleted,\n\t\t\trangeCount: finalRanges.length,\n\t\t\ttokensBefore: region.tokenEstimate,\n\t\t\ttokensAfter,\n\t\t\tpercentReduction,\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,32 @@
1
+ import type { InternalResourceRouter } from "../tools/resource-selectors.ts";
2
+ /** Share of the kept context's tokens that recalled snippets may add. */
3
+ export declare const COMPACTION_RECALL_TOKEN_FRACTION = 0.1;
4
+ /** Most tokens recalled snippets may add, however large the kept context is. */
5
+ export declare const COMPACTION_RECALL_MAX_TOKENS = 1500;
6
+ /** Longest the whole recall step may take; past it compaction goes on without recalled context. */
7
+ export declare const COMPACTION_RECALL_TIME_LIMIT_MS = 3000;
8
+ export declare const COMPACTION_RECALL_HEADING = "Recalled context";
9
+ export interface HistoryRecallRequest {
10
+ readonly router: InternalResourceRouter;
11
+ readonly sessionId: string;
12
+ /** The current task: the latest user request and the compaction relevance query. */
13
+ readonly queries: readonly string[];
14
+ /** Every line the compacted context will still show, so recall never repeats one. */
15
+ readonly keptLines: readonly string[];
16
+ readonly keptTokens: number;
17
+ readonly signal?: AbortSignal;
18
+ readonly timeLimitMs?: number;
19
+ }
20
+ export declare function recallBudgetTokens(keptTokens: number): number;
21
+ /** The compacted text followed by the recalled section. */
22
+ export declare function withRecalledContext(compactedText: string, section: string): string;
23
+ /**
24
+ * Find lines of this session's history, other sessions and workflow runs that bear on the current task, and render
25
+ * them as a short `Recalled context` section. Resolves `undefined` when there is nothing to add, whatever the reason:
26
+ * no matches, an exhausted budget, a failed search, the time limit or cancellation. It never rejects.
27
+ *
28
+ * Every snippet line is quoted with `> `, so recalled text can never be read as compaction structure on the next pass:
29
+ * a role header, a `(filtered N lines)` marker or a `<keepContext>` tag.
30
+ */
31
+ export declare function recallHistory(request: HistoryRecallRequest): Promise<string | undefined>;
32
+ //# sourceMappingURL=history-recall.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history-recall.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/history-recall.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAyB,MAAM,gCAAgC,CAAC;AAIpG,yEAAyE;AACzE,eAAO,MAAM,gCAAgC,MAAM,CAAC;AACpD,gFAAgF;AAChF,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAClD,mGAAmG;AACnG,eAAO,MAAM,+BAA+B,OAAQ,CAAC;AACrD,eAAO,MAAM,yBAAyB,qBAAqB,CAAC;AAqC5D,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,MAAM,EAAE,sBAAsB,CAAC;IACxC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,oFAAoF;IACpF,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,qFAAqF;IACrF,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC9B;AAoBD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED,2DAA2D;AAC3D,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAwND;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAsB9F"}