open-multi-agent-kit 0.97.0 → 0.98.0

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 (261) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +41 -9
  3. package/dist/cli/args.d.ts +2 -3
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +13 -189
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/help.d.ts +3 -0
  8. package/dist/cli/help.d.ts.map +1 -0
  9. package/dist/cli/help.js +194 -0
  10. package/dist/cli/help.js.map +1 -0
  11. package/dist/cli/initial-message.d.ts.map +1 -1
  12. package/dist/cli/initial-message.js +2 -1
  13. package/dist/cli/initial-message.js.map +1 -1
  14. package/dist/cli/resource-paths.d.ts +4 -0
  15. package/dist/cli/resource-paths.d.ts.map +1 -0
  16. package/dist/cli/resource-paths.js +59 -0
  17. package/dist/cli/resource-paths.js.map +1 -0
  18. package/dist/commands/adaptorch-doctor-cli.d.ts +13 -0
  19. package/dist/commands/adaptorch-doctor-cli.d.ts.map +1 -0
  20. package/dist/commands/adaptorch-doctor-cli.js +115 -0
  21. package/dist/commands/adaptorch-doctor-cli.js.map +1 -0
  22. package/dist/commands/resource-doctor-cli.d.ts +4 -0
  23. package/dist/commands/resource-doctor-cli.d.ts.map +1 -1
  24. package/dist/commands/resource-doctor-cli.js +35 -5
  25. package/dist/commands/resource-doctor-cli.js.map +1 -1
  26. package/dist/core/adaptorch-bridge.d.ts +11 -13
  27. package/dist/core/adaptorch-bridge.d.ts.map +1 -1
  28. package/dist/core/adaptorch-bridge.js +11 -13
  29. package/dist/core/adaptorch-bridge.js.map +1 -1
  30. package/dist/core/agent-session-snapshot.d.ts +16 -0
  31. package/dist/core/agent-session-snapshot.d.ts.map +1 -0
  32. package/dist/core/agent-session-snapshot.js +111 -0
  33. package/dist/core/agent-session-snapshot.js.map +1 -0
  34. package/dist/core/agent-session.d.ts +5 -9
  35. package/dist/core/agent-session.d.ts.map +1 -1
  36. package/dist/core/agent-session.js +27 -219
  37. package/dist/core/agent-session.js.map +1 -1
  38. package/dist/core/agent-tool-settings.d.ts +10 -0
  39. package/dist/core/agent-tool-settings.d.ts.map +1 -1
  40. package/dist/core/agent-tool-settings.js +10 -1
  41. package/dist/core/agent-tool-settings.js.map +1 -1
  42. package/dist/core/compaction/compaction.d.ts +7 -0
  43. package/dist/core/compaction/compaction.d.ts.map +1 -1
  44. package/dist/core/compaction/compaction.js +25 -61
  45. package/dist/core/compaction/compaction.js.map +1 -1
  46. package/dist/core/compaction/index.d.ts +1 -0
  47. package/dist/core/compaction/index.d.ts.map +1 -1
  48. package/dist/core/compaction/index.js +1 -0
  49. package/dist/core/compaction/index.js.map +1 -1
  50. package/dist/core/compaction/knowledge-triage-format.d.ts +9 -0
  51. package/dist/core/compaction/knowledge-triage-format.d.ts.map +1 -0
  52. package/dist/core/compaction/knowledge-triage-format.js +71 -0
  53. package/dist/core/compaction/knowledge-triage-format.js.map +1 -0
  54. package/dist/core/compaction/knowledge-triage-types.d.ts +7 -0
  55. package/dist/core/compaction/knowledge-triage-types.d.ts.map +1 -0
  56. package/dist/core/compaction/knowledge-triage-types.js +2 -0
  57. package/dist/core/compaction/knowledge-triage-types.js.map +1 -0
  58. package/dist/core/compaction/knowledge-triage.d.ts +29 -0
  59. package/dist/core/compaction/knowledge-triage.d.ts.map +1 -0
  60. package/dist/core/compaction/knowledge-triage.js +189 -0
  61. package/dist/core/compaction/knowledge-triage.js.map +1 -0
  62. package/dist/core/compaction/transaction.d.ts.map +1 -1
  63. package/dist/core/compaction/transaction.js +1 -1
  64. package/dist/core/compaction/transaction.js.map +1 -1
  65. package/dist/core/compaction/utils.d.ts +4 -0
  66. package/dist/core/compaction/utils.d.ts.map +1 -1
  67. package/dist/core/compaction/utils.js +37 -0
  68. package/dist/core/compaction/utils.js.map +1 -1
  69. package/dist/core/completion-sound-io.d.ts +14 -0
  70. package/dist/core/completion-sound-io.d.ts.map +1 -0
  71. package/dist/core/completion-sound-io.js +64 -0
  72. package/dist/core/completion-sound-io.js.map +1 -0
  73. package/dist/core/completion-sound.d.ts +4 -10
  74. package/dist/core/completion-sound.d.ts.map +1 -1
  75. package/dist/core/completion-sound.js +28 -58
  76. package/dist/core/completion-sound.js.map +1 -1
  77. package/dist/core/context-budget-relevance.d.ts +15 -2
  78. package/dist/core/context-budget-relevance.d.ts.map +1 -1
  79. package/dist/core/context-budget-relevance.js +21 -9
  80. package/dist/core/context-budget-relevance.js.map +1 -1
  81. package/dist/core/context-budget-system-prompt-items.d.ts +1 -1
  82. package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
  83. package/dist/core/context-budget-system-prompt-items.js.map +1 -1
  84. package/dist/core/context-budget-system-prompt.d.ts +1 -1
  85. package/dist/core/context-budget-system-prompt.d.ts.map +1 -1
  86. package/dist/core/context-budget-system-prompt.js.map +1 -1
  87. package/dist/core/context-file.d.ts +23 -0
  88. package/dist/core/context-file.d.ts.map +1 -0
  89. package/dist/core/context-file.js +17 -0
  90. package/dist/core/context-file.js.map +1 -0
  91. package/dist/core/keybindings.d.ts +1 -1
  92. package/dist/core/keybindings.d.ts.map +1 -1
  93. package/dist/core/keybindings.js +6 -1
  94. package/dist/core/keybindings.js.map +1 -1
  95. package/dist/core/model-prompt-policy.d.ts +1 -1
  96. package/dist/core/model-prompt-policy.d.ts.map +1 -1
  97. package/dist/core/model-prompt-policy.js.map +1 -1
  98. package/dist/core/prompt-settlement.d.ts +6 -3
  99. package/dist/core/prompt-settlement.d.ts.map +1 -1
  100. package/dist/core/prompt-settlement.js +10 -14
  101. package/dist/core/prompt-settlement.js.map +1 -1
  102. package/dist/core/reasoning-router-promotion.d.ts +41 -1
  103. package/dist/core/reasoning-router-promotion.d.ts.map +1 -1
  104. package/dist/core/reasoning-router-promotion.js +31 -2
  105. package/dist/core/reasoning-router-promotion.js.map +1 -1
  106. package/dist/core/reasoning-router-replay-stability.d.ts +65 -0
  107. package/dist/core/reasoning-router-replay-stability.d.ts.map +1 -0
  108. package/dist/core/reasoning-router-replay-stability.js +67 -0
  109. package/dist/core/reasoning-router-replay-stability.js.map +1 -0
  110. package/dist/core/reasoning-router-v4-weights.d.ts +6 -6
  111. package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
  112. package/dist/core/reasoning-router-v4-weights.js +3 -3
  113. package/dist/core/reasoning-router-v4-weights.js.map +1 -1
  114. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  115. package/dist/core/reasoning-router-v4.js +6 -6
  116. package/dist/core/reasoning-router-v4.js.map +1 -1
  117. package/dist/core/redaction.d.ts.map +1 -1
  118. package/dist/core/redaction.js +1 -1
  119. package/dist/core/redaction.js.map +1 -1
  120. package/dist/core/resource-admission.d.ts +2 -1
  121. package/dist/core/resource-admission.d.ts.map +1 -1
  122. package/dist/core/resource-admission.js +11 -0
  123. package/dist/core/resource-admission.js.map +1 -1
  124. package/dist/core/resource-governor-format.d.ts +1 -1
  125. package/dist/core/resource-governor-format.d.ts.map +1 -1
  126. package/dist/core/resource-governor-format.js.map +1 -1
  127. package/dist/core/resource-governor-settings.d.ts +6 -12
  128. package/dist/core/resource-governor-settings.d.ts.map +1 -1
  129. package/dist/core/resource-governor-settings.js.map +1 -1
  130. package/dist/core/resource-governor-types.d.ts +24 -0
  131. package/dist/core/resource-governor-types.d.ts.map +1 -0
  132. package/dist/core/resource-governor-types.js +15 -0
  133. package/dist/core/resource-governor-types.js.map +1 -0
  134. package/dist/core/resource-loader.d.ts +1 -7
  135. package/dist/core/resource-loader.d.ts.map +1 -1
  136. package/dist/core/resource-loader.js.map +1 -1
  137. package/dist/core/resource-observation-journal.d.ts +2 -1
  138. package/dist/core/resource-observation-journal.d.ts.map +1 -1
  139. package/dist/core/resource-observation-journal.js +4 -3
  140. package/dist/core/resource-observation-journal.js.map +1 -1
  141. package/dist/core/resource-observation-report-reader.d.ts +7 -0
  142. package/dist/core/resource-observation-report-reader.d.ts.map +1 -0
  143. package/dist/core/resource-observation-report-reader.js +157 -0
  144. package/dist/core/resource-observation-report-reader.js.map +1 -0
  145. package/dist/core/resource-observation-report.d.ts +24 -0
  146. package/dist/core/resource-observation-report.d.ts.map +1 -0
  147. package/dist/core/resource-observation-report.js +101 -0
  148. package/dist/core/resource-observation-report.js.map +1 -0
  149. package/dist/core/router-feedback-collector.d.ts +1 -1
  150. package/dist/core/router-feedback-collector.d.ts.map +1 -1
  151. package/dist/core/router-feedback-collector.js.map +1 -1
  152. package/dist/core/session-failure-cause.d.ts +33 -0
  153. package/dist/core/session-failure-cause.d.ts.map +1 -0
  154. package/dist/core/session-failure-cause.js +141 -0
  155. package/dist/core/session-failure-cause.js.map +1 -0
  156. package/dist/core/session-system-prompt.d.ts +1 -1
  157. package/dist/core/session-system-prompt.d.ts.map +1 -1
  158. package/dist/core/session-system-prompt.js.map +1 -1
  159. package/dist/core/settings-manager.d.ts +1 -1
  160. package/dist/core/settings-manager.d.ts.map +1 -1
  161. package/dist/core/settings-manager.js.map +1 -1
  162. package/dist/core/system-prompt.d.ts +1 -1
  163. package/dist/core/system-prompt.d.ts.map +1 -1
  164. package/dist/core/system-prompt.js.map +1 -1
  165. package/dist/core/tools/bash.d.ts.map +1 -1
  166. package/dist/core/tools/bash.js +7 -7
  167. package/dist/core/tools/bash.js.map +1 -1
  168. package/dist/core/workload-classifier.d.ts +2 -10
  169. package/dist/core/workload-classifier.d.ts.map +1 -1
  170. package/dist/core/workload-classifier.js +17 -0
  171. package/dist/core/workload-classifier.js.map +1 -1
  172. package/dist/core/workload-family-matcher.d.ts +1 -1
  173. package/dist/core/workload-family-matcher.d.ts.map +1 -1
  174. package/dist/core/workload-family-matcher.js.map +1 -1
  175. package/dist/core/workload-shard-execution-types.d.ts +40 -0
  176. package/dist/core/workload-shard-execution-types.d.ts.map +1 -0
  177. package/dist/core/workload-shard-execution-types.js +14 -0
  178. package/dist/core/workload-shard-execution-types.js.map +1 -0
  179. package/dist/core/workload-shard-executor.d.ts +3 -27
  180. package/dist/core/workload-shard-executor.d.ts.map +1 -1
  181. package/dist/core/workload-shard-executor.js.map +1 -1
  182. package/dist/core/workload-shard-runner.d.ts +1 -1
  183. package/dist/core/workload-shard-runner.d.ts.map +1 -1
  184. package/dist/core/workload-shard-runner.js.map +1 -1
  185. package/dist/core/workload-types.d.ts +24 -0
  186. package/dist/core/workload-types.d.ts.map +1 -0
  187. package/dist/core/workload-types.js +15 -0
  188. package/dist/core/workload-types.js.map +1 -0
  189. package/dist/main.d.ts +2 -0
  190. package/dist/main.d.ts.map +1 -1
  191. package/dist/main.js +27 -47
  192. package/dist/main.js.map +1 -1
  193. package/dist/modes/interactive/theme/omk-control-panel.json +1 -1
  194. package/dist/utils/clipboard-image.d.ts.map +1 -1
  195. package/dist/utils/clipboard-image.js +42 -33
  196. package/dist/utils/clipboard-image.js.map +1 -1
  197. package/dist/utils/clipboard.d.ts.map +1 -1
  198. package/dist/utils/clipboard.js +14 -2
  199. package/dist/utils/clipboard.js.map +1 -1
  200. package/docs/adaptorch-preview-spec.md +20 -18
  201. package/docs/adaptorch-preview.md +9 -9
  202. package/docs/compaction.md +24 -3
  203. package/docs/correctness-wall.md +10 -10
  204. package/docs/docs.json +12 -0
  205. package/docs/environment-variables.md +9 -2
  206. package/docs/index.md +3 -0
  207. package/docs/runtime-algorithms.md +359 -0
  208. package/docs/sdk.md +2 -2
  209. package/docs/settings.md +11 -10
  210. package/docs/usage.md +18 -2
  211. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  212. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  213. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  214. package/examples/extensions/gondolin/package-lock.json +2 -2
  215. package/examples/extensions/gondolin/package.json +1 -1
  216. package/examples/extensions/sandbox/package-lock.json +2 -2
  217. package/examples/extensions/sandbox/package.json +1 -1
  218. package/examples/extensions/with-deps/package-lock.json +2 -2
  219. package/examples/extensions/with-deps/package.json +1 -1
  220. package/npm-shrinkwrap.json +18 -18
  221. package/package.json +6 -6
  222. package/dist/core/context-budget-governor.d.ts +0 -67
  223. package/dist/core/context-budget-governor.d.ts.map +0 -1
  224. package/dist/core/context-budget-governor.js +0 -224
  225. package/dist/core/context-budget-governor.js.map +0 -1
  226. package/dist/core/lean-ctx.d.ts +0 -99
  227. package/dist/core/lean-ctx.d.ts.map +0 -1
  228. package/dist/core/lean-ctx.js +0 -225
  229. package/dist/core/lean-ctx.js.map +0 -1
  230. package/dist/core/read-anchors.d.ts +0 -110
  231. package/dist/core/read-anchors.d.ts.map +0 -1
  232. package/dist/core/read-anchors.js +0 -193
  233. package/dist/core/read-anchors.js.map +0 -1
  234. package/dist/core/recovery-checkpoint.d.ts +0 -196
  235. package/dist/core/recovery-checkpoint.d.ts.map +0 -1
  236. package/dist/core/recovery-checkpoint.js +0 -382
  237. package/dist/core/recovery-checkpoint.js.map +0 -1
  238. package/dist/core/sandbox-policy-v2.d.ts +0 -49
  239. package/dist/core/sandbox-policy-v2.d.ts.map +0 -1
  240. package/dist/core/sandbox-policy-v2.js +0 -368
  241. package/dist/core/sandbox-policy-v2.js.map +0 -1
  242. package/dist/guardrails/audit-logger.d.ts +0 -4
  243. package/dist/guardrails/audit-logger.d.ts.map +0 -1
  244. package/dist/guardrails/audit-logger.js +0 -28
  245. package/dist/guardrails/audit-logger.js.map +0 -1
  246. package/dist/guardrails/freedomd-adapter.d.ts +0 -16
  247. package/dist/guardrails/freedomd-adapter.d.ts.map +0 -1
  248. package/dist/guardrails/freedomd-adapter.js +0 -87
  249. package/dist/guardrails/freedomd-adapter.js.map +0 -1
  250. package/dist/orchestration/lane-grant-auditor.d.ts +0 -4
  251. package/dist/orchestration/lane-grant-auditor.d.ts.map +0 -1
  252. package/dist/orchestration/lane-grant-auditor.js +0 -87
  253. package/dist/orchestration/lane-grant-auditor.js.map +0 -1
  254. package/dist/types/guardrails.d.ts +0 -61
  255. package/dist/types/guardrails.d.ts.map +0 -1
  256. package/dist/types/guardrails.js +0 -9
  257. package/dist/types/guardrails.js.map +0 -1
  258. package/dist/types/lane-grant.d.ts +0 -58
  259. package/dist/types/lane-grant.d.ts.map +0 -1
  260. package/dist/types/lane-grant.js +0 -9
  261. package/dist/types/lane-grant.js.map +0 -1
@@ -1,5 +1,15 @@
1
1
  import type { AgentOptions } from "omk-agent-core";
2
2
  import type { SettingsManager } from "./settings-manager.ts";
3
+ /**
4
+ * Built-in per-tool timeouts.
5
+ *
6
+ * Exported so a tool's own schema can state its real limit. The bash tool used
7
+ * to advertise "no default timeout" while this table bounded it at five
8
+ * minutes, so a model had no reason to ask for more on a dataset download or a
9
+ * training run and simply lost the work when the cap hit. A tool description
10
+ * that disagrees with the runtime is worse than none.
11
+ */
12
+ export declare const DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>>;
3
13
  /** §6.3 timeout categories. `undefined` category falls through to the global setting. */
4
14
  export type ToolTimeoutCategory = "read" | "write" | "mcp" | "process" | "browser";
5
15
  /** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tool-settings.d.ts","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAwB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAiBnF,0FAAyF;AACzF,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,GAAG,SAAS,GAAG,SAAS,CAAC;AAEnF,0IAAyI;AACzI,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAM/E,CAAC;AASH;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAO5F;AAED;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC3C,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,EAC3B,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACxC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAED,KAAK,aAAa,GAAG,WAAW,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAAC;AAEhE,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IAChD,QAAQ,CAAC,qBAAqB,EAAE,OAAO,CAAC;IACxC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAE7B,YAAY,WAAW,EAAE,MAAM,EAI9B;CACD;AAiFD,wBAAgB,wBAAwB,CACvC,eAAe,EAAE,eAAe,EAChC,GAAG,GAAE,MAAM,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,yBAAyB,CAc3B","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
1
+ {"version":3,"file":"agent-tool-settings.d.ts","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAwB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAOnF;;;;;;;;GAQG;AACH,eAAO,MAAM,6BAA6B,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ1E,CAAC;AAEF,0FAAyF;AACzF,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,GAAG,SAAS,GAAG,SAAS,CAAC;AAEnF,0IAAyI;AACzI,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAM/E,CAAC;AASH;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAO5F;AAED;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC3C,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,EAC3B,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACxC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAED,KAAK,aAAa,GAAG,WAAW,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAAC;AAEhE,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IAChD,QAAQ,CAAC,qBAAqB,EAAE,OAAO,CAAC;IACxC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAE7B,YAAY,WAAW,EAAE,MAAM,EAI9B;CACD;AAiFD,wBAAgB,wBAAwB,CACvC,eAAe,EAAE,eAAe,EAChC,GAAG,GAAE,MAAM,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,yBAAyB,CAc3B","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Built-in per-tool timeouts.\n *\n * Exported so a tool's own schema can state its real limit. The bash tool used\n * to advertise \"no default timeout\" while this table bounded it at five\n * minutes, so a model had no reason to ask for more on a dataset download or a\n * training run and simply lost the work when the cap hit. A tool description\n * that disagrees with the runtime is worse than none.\n */\nexport const DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
@@ -2,7 +2,16 @@ const DEFAULT_TOOL_SCHEDULER = "dag-v2";
2
2
  const DEFAULT_MAX_TOOL_CONCURRENCY = 4;
3
3
  const DEFAULT_TOOL_TIMEOUT_MS = 0;
4
4
  const MAX_TOOL_TIMEOUT_MS = 2_147_483_647;
5
- const DEFAULT_BUILTIN_TOOL_TIMEOUTS = {
5
+ /**
6
+ * Built-in per-tool timeouts.
7
+ *
8
+ * Exported so a tool's own schema can state its real limit. The bash tool used
9
+ * to advertise "no default timeout" while this table bounded it at five
10
+ * minutes, so a model had no reason to ask for more on a dataset download or a
11
+ * training run and simply lost the work when the cap hit. A tool description
12
+ * that disagrees with the runtime is worse than none.
13
+ */
14
+ export const DEFAULT_BUILTIN_TOOL_TIMEOUTS = {
6
15
  bash: 300_000,
7
16
  edit: 60_000,
8
17
  find: 30_000,
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tool-settings.js","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAGA,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AACxC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AACvC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAE1C,MAAM,6BAA6B,GAAqC;IACvE,IAAI,EAAE,OAAO;IACb,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,EAAE,EAAE,MAAM;IACV,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,MAAM;CACb,CAAC;AAKF,0IAAyI;AACzI,MAAM,CAAC,MAAM,sBAAsB,GAAkD,MAAM,CAAC,MAAM,CAAC;IAClG,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,MAAM;IACb,GAAG,EAAE,OAAO;IACZ,OAAO,EAAE,OAAO;IAChB,OAAO,EAAE,OAAO;CAChB,CAAC,CAAC;AAEH,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC9F,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AACxD,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AACjD,8EAA8E;AAC9E,uDAAuD;AACvD,MAAM,oBAAoB,GAAG,8CAA8C,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,QAAgB,EAAmC;IAC7F,IAAI,mBAAmB,CAAC,GAAG,C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["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
1
+ {"version":3,"file":"agent-tool-settings.js","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAGA,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AACxC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AACvC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAE1C;;;;;;;;GAQG;AACH,MAA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CAAC;AAAA,CAChB;AAED,MAAM,UAAU,wBAAwB,CACvC,eAAgC,EAChC,GAAG,GAAqE,OAAO,CAAC,GAAG,EACvD;IAC5B,MAAM,cAAc,GAAG,kBAAkB,CAAC,eAAe,CAAC,iBAAiB,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9F,MAAM,eAAe,GAAG,kBAAkB,CAAC,eAAe,CAAC,kBAAkB,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAChG,MAAM,QAAQ,GAAG,kBAAkB,CAAC,eAAe,CAAC,uBAAuB,EAAE,EAAE,OAAO,CAAC,CAAC;IACxF,MAAM,YAAY,GAAG,cAAc,CAAC,GAAG,CAAC,kBAAkB,EAAE,oBAAoB,CAAC,CAAC;IAClF,MAAM,iBAAiB,GAAG,cAAc,CAAC,QAAQ,CAAC,aAAa,EAAE,qBAAqB,CAAC,CAAC;IAExF,OAAO;QACN,aAAa,EAAE,YAAY,IAAI,iBAAiB,IAAI,sBAAsB;QAC1E,kBAAkB,EAAE,gBAAgB,CAAC,QAAQ,CAAC,kBAAkB,CAAC;QACjE,qBAAqB,EAAE,IAAI;QAC3B,aAAa,EAAE,YAAY,CAAC,QAAQ,CAAC,aAAa,EAAE,qBAAqB,EAAE,uBAAuB,CAAC;QACnG,YAAY,EAAE,mBAAmB,CAAC,cAAc,EAAE,eAAe,EAAE,QAAQ,CAAC;KAC5E,CAAC;AAAA,CACF","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Built-in per-tool timeouts.\n *\n * Exported so a tool's own schema can state its real limit. The bash tool used\n * to advertise \"no default timeout\" while this table bounded it at five\n * minutes, so a model had no reason to ask for more on a dataset download or a\n * training run and simply lost the work when the cap hit. A tool description\n * that disagrees with the runtime is worse than none.\n */\nexport const DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
@@ -8,11 +8,14 @@ import type { AgentMessage, StreamFn, ThinkingLevel } from "omk-agent-core";
8
8
  import type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from "omk-ai";
9
9
  import { type RetryCallbacks, type RetryPolicy } from "omk-ai";
10
10
  import { type SessionEntry } from "../session-manager.ts";
11
+ import { type CompactionRuleHistory, type PreservedRuleRecord } from "./knowledge-triage.ts";
11
12
  import { type FileOperations } from "./utils.ts";
12
13
  /** Details stored in CompactionEntry.details for file tracking */
13
14
  export interface CompactionDetails {
14
15
  readFiles: string[];
15
16
  modifiedFiles: string[];
17
+ /** Deterministically extracted, source-bound user rules carried outside LLM rewriting. */
18
+ preservedRules?: PreservedRuleRecord[];
16
19
  }
17
20
  /** Result from compact() - SessionManager adds uuid/parentUuid when saving */
18
21
  export interface CompactionResult<T = unknown> {
@@ -134,6 +137,10 @@ export interface CompactionPreparation {
134
137
  tokensBefore: number;
135
138
  /** Summary from previous compaction, for iterative update */
136
139
  previousSummary?: string;
140
+ /** Source-verified rule history from the prior default compaction. */
141
+ previousRuleHistory?: CompactionRuleHistory;
142
+ /** Exact session entries covered by this compaction's rule extraction. */
143
+ currentRuleEntries?: readonly SessionEntry[];
137
144
  /** File operations extracted from messagesToSummarize */
138
145
  fileOps: FileOperations;
139
146
  /** Compaction settions from settings.jsonl */
@@ -1 +1 @@
1
- {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC3F,OAAO,EAAkB,KAAK,cAAc,EAAE,KAAK,WAAW,EAAsB,MAAM,QAAQ,CAAC;AASnG,OAAO,EAA6C,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,kEAAkE;AAClE,MAAM,WAAW,iBAAiB;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,EAAE,MAAM,EAAE,CAAC;CACxB;AAiED,8EAA8E;AAC9E,MAAM,WAAW,gBAAgB,CAAC,CAAC,GAAG,OAAO;IAC5C,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,+FAA+F;IAC/F,OAAO,CAAC,EAAE,CAAC,CAAC;CACZ;A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AAQ,CAAC,EAAE,QAAQ,EACnB,KAAK,CAAC,EAAE,WAAW,EACnB,SAAS,CAAC,EAAE,cAAc,EAC1B,cAAc,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA0C3B","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport { uuidv7 } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple, type RetryCallbacks, type RetryPolicy, retryAssistantCall } from \"omk-ai\";\nimport { computeReservedTokenBudget } from \"../context-budget-reserved-tokens.ts\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { isQuotaExhaustionMessage } from \"../provider-resilience.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\treservedOutputTokens?: number;\n\treservedToolResultTokens?: number;\n\tsafetyMarginTokens?: number;\n\timageReserveTokens?: number;\n\tkeepRecentTokens: number;\n\t/** Maximum fraction of the context window to use before compaction. Default: 0.9. */\n\tmaxUsageRatio?: number;\n\trearmRatio?: number;\n\temergencyRatio?: number;\n}\n\nexport const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n\tmaxUsageRatio: DEFAULT_COMPACTION_MAX_USAGE_RATIO,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\nexport type CompactionHeadroomLimit = \"max_usage_ratio\" | \"reserve_tokens\";\n\nexport interface CompactionHeadroomThreshold {\n\ttriggerTokens: number;\n\theadroomTokens: number;\n\tmaxUsageRatioTokens: number;\n\treserveBoundaryTokens: number;\n\tlimitedBy: CompactionHeadroomLimit;\n}\n\n/** Return the earliest compaction threshold from ratio-based headroom and absolute reserve. */\nexport function getCompactionHeadroomThreshold(\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n): CompactionHeadroomThreshold | undefined {\n\tif (!settings.enabled || !Number.isFinite(contextWindow) || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst windowTokens = Math.floor(contextWindow);\n\tconst reserveTokens = Number.isFinite(settings.reserveTokens) ? Math.max(0, Math.floor(settings.reserveTokens)) : 0;\n\tconst configuredMaxUsageRatio = settings.maxUsageRatio ?? DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatio =\n\t\tNumber.isFinite(configuredMaxUsageRatio) && configuredMaxUsageRatio > 0 && configuredMaxUsageRatio < 1\n\t\t\t? configuredMaxUsageRatio\n\t\t\t: DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatioTokens = Math.max(1, Math.floor(windowTokens * maxUsageRatio));\n\tconst reservedBudget = computeReservedTokenBudget({\n\t\tmodelContextWindow: windowTokens,\n\t\tsystemPromptTokens: 0,\n\t\treservedOutputTokens: settings.reservedOutputTokens ?? reserveTokens,\n\t\treservedToolResultTokens: settings.reservedToolResultTokens ?? 0,\n\t\tsafetyMarginTokens: settings.safetyMarginTokens ?? 0,\n\t\timageReserveTokens: settings.imageReserveTokens ?? 0,\n\t});\n\tconst reserveBoundaryTokens =\n\t\treservedBudget.overflow || reservedBudget.effectiveBudget === 0\n\t\t\t? maxUsageRatioTokens\n\t\t\t: Math.max(1, reservedBudget.effectiveBudget);\n\tconst triggerTokens = Math.min(maxUsageRatioTokens, reserveBoundaryTokens);\n\n\treturn {\n\t\ttriggerTokens,\n\t\theadroomTokens: windowTokens - triggerTokens,\n\t\tmaxUsageRatioTokens,\n\t\treserveBoundaryTokens,\n\t\tlimitedBy: reserveBoundaryTokens <= maxUsageRatioTokens ? \"reserve_tokens\" : \"max_usage_ratio\",\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tconst threshold = getCompactionHeadroomThreshold(contextWindow, settings);\n\treturn threshold !== undefined && Number.isFinite(contextTokens) && contextTokens >= threshold.triggerTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Summaries are standalone requests, so isolate routing and avoid cache writes that cannot be reused.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn textContent;\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * When {@link failoverModels} is provided and the primary model fails with a\n * quota/billing exhaustion error (same-model retry is useless until reset),\n * the whole summarization is retried once with each candidate in order. Only\n * quota-class errors are absorbed; any other failure surfaces immediately.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tfailoverModels?: readonly Model<any>[],\n): Promise<CompactionResult> {\n\ttry {\n\t\treturn await compactWithModel(\n\t\t\tpreparation,\n\t\t\tmodel,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tcustomInstructions,\n\t\t\tsignal,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tif (!isQuotaExhaustionMessage(message) || !failoverModels || failoverModels.length === 0) throw error;\n\t\tfor (const candidate of failoverModels) {\n\t\t\tif (candidate.provider === model.provider && candidate.id === model.id) continue;\n\t\t\tif (signal?.aborted) throw error;\n\t\t\ttry {\n\t\t\t\treturn await compactWithModel(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tcandidate,\n\t\t\t\t\tapiKey,\n\t\t\t\t\theaders,\n\t\t\t\t\tcustomInstructions,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tstreamFn,\n\t\t\t\t\tretry,\n\t\t\t\t\tcallbacks,\n\t\t\t\t);\n\t\t\t} catch (candidateError) {\n\t\t\t\tconst candidateMessage = candidateError instanceof Error ? candidateError.message : String(candidateError);\n\t\t\t\tif (!isQuotaExhaustionMessage(candidateMessage)) throw candidateError;\n\t\t\t\t// Candidate is also quota-blocked — try the next one.\n\t\t\t}\n\t\t}\n\t\t// Every candidate is quota-blocked too: surface the primary failure.\n\t\tthrow error;\n\t}\n}\n\n/** Single-model compaction attempt (no failover). Implementation of {@link compact}. */\nasync function compactWithModel(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t\tretry,\n\t\t\t\t\t\tcallbacks,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t}\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\treturn response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAE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MAAM,CAAC,CAqDjB;AAMD,MAAM,WAAW,qBAAqB;IACrC,kCAAkC;IAClC,gBAAgB,EAAE,MAAM,CAAC;IACzB,qDAAqD;IACrD,mBAAmB,EAAE,YAAY,EAAE,CAAC;IACpC,2EAA2E;IAC3E,kBAAkB,EAAE,YAAY,EAAE,CAAC;IACnC,iEAAiE;IACjE,WAAW,EAAE,OAAO,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,6DAA6D;IAC7D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,qBAAqB,CAAC;IAC5C,0EAA0E;IAC1E,kBAAkB,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAC7C,yDAAyD;IACzD,OAAO,EAAE,cAAc,CAAC;IACxB,8CAA8C;IAC9C,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAChC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CAgFnC;AAqBD;;;;;;;;;;;GAWG;AACH,wBAAsB,OAAO,CAC5B,WAAW,EAAE,qBAAqB,EAClC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,kBAAkB,CAAC,EAAE,MAAM,EAC3B,MAAM,CAAC,EAAE,WAAW,EACpB,aAAa,CAAC,EAAE,aAAa,EAC7B,QAAQ,CAAC,EAAE,QAAQ,EACnB,KAAK,CAAC,EAAE,WAAW,EACnB,SAAS,CAAC,EAAE,cAAc,EAC1B,cAAc,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GACpC,OAAO,CAAC,gBAAgB,CAAC,CA0C3B","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport { uuidv7 } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple, type RetryCallbacks, type RetryPolicy, retryAssistantCall } from \"omk-ai\";\nimport { computeReservedTokenBudget } from \"../context-budget-reserved-tokens.ts\";\nimport { convertToLlm } from \"../messages.ts\";\nimport { isQuotaExhaustionMessage } from \"../provider-resilience.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tapplyCompactionKnowledgeTriage,\n\tbuildCompactionRuleHistory,\n\ttype CompactionRuleHistory,\n\ttype PreservedRuleRecord,\n} from \"./knowledge-triage.ts\";\nimport {\n\tcomputeFileLists,\n\textractCompactionFileOperations,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tgetMessageFromEntryForCompaction,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n\t/** Deterministically extracted, source-bound user rules carried outside LLM rewriting. */\n\tpreservedRules?: PreservedRuleRecord[];\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\treservedOutputTokens?: number;\n\treservedToolResultTokens?: number;\n\tsafetyMarginTokens?: number;\n\timageReserveTokens?: number;\n\tkeepRecentTokens: number;\n\t/** Maximum fraction of the context window to use before compaction. Default: 0.9. */\n\tmaxUsageRatio?: number;\n\trearmRatio?: number;\n\temergencyRatio?: number;\n}\n\nexport const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n\tmaxUsageRatio: DEFAULT_COMPACTION_MAX_USAGE_RATIO,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\nexport type CompactionHeadroomLimit = \"max_usage_ratio\" | \"reserve_tokens\";\n\nexport interface CompactionHeadroomThreshold {\n\ttriggerTokens: number;\n\theadroomTokens: number;\n\tmaxUsageRatioTokens: number;\n\treserveBoundaryTokens: number;\n\tlimitedBy: CompactionHeadroomLimit;\n}\n\n/** Return the earliest compaction threshold from ratio-based headroom and absolute reserve. */\nexport function getCompactionHeadroomThreshold(\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n): CompactionHeadroomThreshold | undefined {\n\tif (!settings.enabled || !Number.isFinite(contextWindow) || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst windowTokens = Math.floor(contextWindow);\n\tconst reserveTokens = Number.isFinite(settings.reserveTokens) ? Math.max(0, Math.floor(settings.reserveTokens)) : 0;\n\tconst configuredMaxUsageRatio = settings.maxUsageRatio ?? DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatio =\n\t\tNumber.isFinite(configuredMaxUsageRatio) && configuredMaxUsageRatio > 0 && configuredMaxUsageRatio < 1\n\t\t\t? configuredMaxUsageRatio\n\t\t\t: DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatioTokens = Math.max(1, Math.floor(windowTokens * maxUsageRatio));\n\tconst reservedBudget = computeReservedTokenBudget({\n\t\tmodelContextWindow: windowTokens,\n\t\tsystemPromptTokens: 0,\n\t\treservedOutputTokens: settings.reservedOutputTokens ?? reserveTokens,\n\t\treservedToolResultTokens: settings.reservedToolResultTokens ?? 0,\n\t\tsafetyMarginTokens: settings.safetyMarginTokens ?? 0,\n\t\timageReserveTokens: settings.imageReserveTokens ?? 0,\n\t});\n\tconst reserveBoundaryTokens =\n\t\treservedBudget.overflow || reservedBudget.effectiveBudget === 0\n\t\t\t? maxUsageRatioTokens\n\t\t\t: Math.max(1, reservedBudget.effectiveBudget);\n\tconst triggerTokens = Math.min(maxUsageRatioTokens, reserveBoundaryTokens);\n\n\treturn {\n\t\ttriggerTokens,\n\t\theadroomTokens: windowTokens - triggerTokens,\n\t\tmaxUsageRatioTokens,\n\t\treserveBoundaryTokens,\n\t\tlimitedBy: reserveBoundaryTokens <= maxUsageRatioTokens ? \"reserve_tokens\" : \"max_usage_ratio\",\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tconst threshold = getCompactionHeadroomThreshold(contextWindow, settings);\n\treturn threshold !== undefined && Number.isFinite(contextTokens) && contextTokens >= threshold.triggerTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\n/**\n * Shared choke point for every compaction/branch-summary summarization call. Wraps the\n * single LLM call in {@link retryAssistantCall} so transient stream drops (e.g.\n * `terminated`, socket close) honor the configured retry policy instead of failing\n * the whole compaction on the first attempt. Deterministic errors and aborts return\n * immediately (see {@link retryAssistantCall}).\n */\nexport async function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<AssistantMessage> {\n\t// Summaries are standalone requests, so isolate routing and avoid cache writes that cannot be reused.\n\tconst requestOptions: SimpleStreamOptions = {\n\t\t...options,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t};\n\tconst produce = async (): Promise<AssistantMessage> =>\n\t\tstreamFn\n\t\t\t? (await streamFn(model, context, requestOptions)).result()\n\t\t\t: completeSimple(model, context, requestOptions);\n\treturn retryAssistantCall(produce, retry, requestOptions.signal, callbacks);\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn textContent;\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** Source-verified rule history from the prior default compaction. */\n\tpreviousRuleHistory?: CompactionRuleHistory;\n\t/** Exact session entries covered by this compaction's rule extraction. */\n\tcurrentRuleEntries?: readonly SessionEntry[];\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet previousRuleHistory: CompactionRuleHistory | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tpreviousRuleHistory = buildCompactionRuleHistory(prevCompaction, pathEntries);\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractCompactionFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\tconst currentRuleEntries = [\n\t\t...pathEntries.slice(boundaryStart, historyEnd),\n\t\t...(cutPoint.isSplitTurn ? pathEntries.slice(cutPoint.turnStartIndex, cutPoint.firstKeptEntryIndex) : []),\n\t];\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * When {@link failoverModels} is provided and the primary model fails with a\n * quota/billing exhaustion error (same-model retry is useless until reset),\n * the whole summarization is retried once with each candidate in order. Only\n * quota-class errors are absorbed; any other failure surfaces immediately.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n\tfailoverModels?: readonly Model<any>[],\n): Promise<CompactionResult> {\n\ttry {\n\t\treturn await compactWithModel(\n\t\t\tpreparation,\n\t\t\tmodel,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tcustomInstructions,\n\t\t\tsignal,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tif (!isQuotaExhaustionMessage(message) || !failoverModels || failoverModels.length === 0) throw error;\n\t\tfor (const candidate of failoverModels) {\n\t\t\tif (candidate.provider === model.provider && candidate.id === model.id) continue;\n\t\t\tif (signal?.aborted) throw error;\n\t\t\ttry {\n\t\t\t\treturn await compactWithModel(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tcandidate,\n\t\t\t\t\tapiKey,\n\t\t\t\t\theaders,\n\t\t\t\t\tcustomInstructions,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tstreamFn,\n\t\t\t\t\tretry,\n\t\t\t\t\tcallbacks,\n\t\t\t\t);\n\t\t\t} catch (candidateError) {\n\t\t\t\tconst candidateMessage = candidateError instanceof Error ? candidateError.message : String(candidateError);\n\t\t\t\tif (!isQuotaExhaustionMessage(candidateMessage)) throw candidateError;\n\t\t\t\t// Candidate is also quota-blocked — try the next one.\n\t\t\t}\n\t\t}\n\t\t// Every candidate is quota-blocked too: surface the primary failure.\n\t\tthrow error;\n\t}\n}\n\n/** Single-model compaction attempt (no failover). Implementation of {@link compact}. */\nasync function compactWithModel(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tpreviousRuleHistory,\n\t\tcurrentRuleEntries,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t\tretry,\n\t\t\t\t\t\tcallbacks,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t\tretry,\n\t\t\t\tcallbacks,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t\tretry,\n\t\t\tcallbacks,\n\t\t);\n\t}\n\n\tconst triage = applyCompactionKnowledgeTriage({\n\t\tgeneratedSummary: summary,\n\t\tcurrentMessages: [...messagesToSummarize, ...turnPrefixMessages],\n\t\tcurrentEntries: currentRuleEntries,\n\t\tpreviousRules: previousRuleHistory?.rules,\n\t\tpreviousSummary,\n\t\tpreviousEntries: previousRuleHistory?.entries,\n\t});\n\tsummary = triage.summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles, preservedRules: [...triage.preservedRules] } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n\tretry?: RetryPolicy,\n\tcallbacks?: RetryCallbacks,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\treturn response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n}\n"]}
@@ -7,64 +7,11 @@
7
7
  import { uuidv7 } from "omk-agent-core";
8
8
  import { completeSimple, retryAssistantCall } from "omk-ai";
9
9
  import { computeReservedTokenBudget } from "../context-budget-reserved-tokens.js";
10
- import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
10
+ import { convertToLlm } from "../messages.js";
11
11
  import { isQuotaExhaustionMessage } from "../provider-resilience.js";
12
12
  import { buildSessionContext } from "../session-manager.js";
13
- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
14
- /**
15
- * Extract file operations from messages and previous compaction entries.
16
- */
17
- function extractFileOperations(messages, entries, prevCompactionIndex) {
18
- const fileOps = createFileOps();
19
- if (prevCompactionIndex >= 0) {
20
- const prevCompaction = entries[prevCompactionIndex];
21
- if (!prevCompaction.fromHook && prevCompaction.details) {
22
- // fromHook field kept for session file compatibility
23
- const details = prevCompaction.details;
24
- if (Array.isArray(details.readFiles)) {
25
- for (const f of details.readFiles)
26
- fileOps.read.add(f);
27
- }
28
- if (Array.isArray(details.modifiedFiles)) {
29
- for (const f of details.modifiedFiles)
30
- fileOps.edited.add(f);
31
- }
32
- }
33
- }
34
- // Extract from tool calls in messages
35
- for (const msg of messages) {
36
- extractFileOpsFromMessage(msg, fileOps);
37
- }
38
- return fileOps;
39
- }
40
- // ============================================================================
41
- // Message Extraction
42
- // ============================================================================
43
- /**
44
- * Extract AgentMessage from an entry if it produces one.
45
- * Returns undefined for entries that don't contribute to LLM context.
46
- */
47
- function getMessageFromEntry(entry) {
48
- if (entry.type === "message") {
49
- return entry.message;
50
- }
51
- if (entry.type === "custom_message") {
52
- return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);
53
- }
54
- if (entry.type === "branch_summary") {
55
- return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
56
- }
57
- if (entry.type === "compaction") {
58
- return createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
59
- }
60
- return undefined;
61
- }
62
- function getMessageFromEntryForCompaction(entry) {
63
- if (entry.type === "compaction") {
64
- return undefined;
65
- }
66
- return getMessageFromEntry(entry);
67
- }
13
+ import { applyCompactionKnowledgeTriage, buildCompactionRuleHistory, } from "./knowledge-triage.js";
14
+ import { computeFileLists, extractCompactionFileOperations, extractFileOpsFromMessage, formatFileOperations, getMessageFromEntryForCompaction, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
68
15
  export const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;
69
16
  export const DEFAULT_COMPACTION_SETTINGS = {
70
17
  enabled: true,
@@ -419,7 +366,7 @@ Use this EXACT format:
419
366
  - [Any data, examples, or references needed to continue]
420
367
  - [Or "(none)" if not applicable]
421
368
 
422
- Keep each section concise. Preserve exact file paths, function names, and error messages.`;
369
+ Keep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;
423
370
  const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
424
371
 
425
372
  Update the existing structured summary with new information. RULES:
@@ -457,7 +404,7 @@ Use this EXACT format:
457
404
  ## Critical Context
458
405
  - [Preserve important context, add new if needed]
459
406
 
460
- Keep each section concise. Preserve exact file paths, function names, and error messages.`;
407
+ Keep each section concise. Preserve exact file paths, function names, and error messages. Do not create a Preserved Rules & Invariants section; OMK injects it deterministically after generation.`;
461
408
  function createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel) {
462
409
  const options = { maxTokens, signal, apiKey, headers };
463
410
  if (model.reasoning && thinkingLevel && thinkingLevel !== "off") {
@@ -535,10 +482,12 @@ export function prepareCompaction(pathEntries, settings) {
535
482
  }
536
483
  }
537
484
  let previousSummary;
485
+ let previousRuleHistory;
538
486
  let boundaryStart = 0;
539
487
  if (prevCompactionIndex >= 0) {
540
488
  const prevCompaction = pathEntries[prevCompactionIndex];
541
489
  previousSummary = prevCompaction.summary;
490
+ previousRuleHistory = buildCompactionRuleHistory(prevCompaction, pathEntries);
542
491
  const firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);
543
492
  boundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;
544
493
  }
@@ -569,7 +518,11 @@ export function prepareCompaction(pathEntries, settings) {
569
518
  }
570
519
  }
571
520
  // Extract file operations from messages and previous compaction
572
- const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
521
+ const fileOps = extractCompactionFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
522
+ const currentRuleEntries = [
523
+ ...pathEntries.slice(boundaryStart, historyEnd),
524
+ ...(cutPoint.isSplitTurn ? pathEntries.slice(cutPoint.turnStartIndex, cutPoint.firstKeptEntryIndex) : []),
525
+ ];
573
526
  // Also extract file ops from turn prefix if splitting
574
527
  if (cutPoint.isSplitTurn) {
575
528
  for (const msg of turnPrefixMessages) {
@@ -583,6 +536,8 @@ export function prepareCompaction(pathEntries, settings) {
583
536
  isSplitTurn: cutPoint.isSplitTurn,
584
537
  tokensBefore,
585
538
  previousSummary,
539
+ previousRuleHistory,
540
+ currentRuleEntries,
586
541
  fileOps,
587
542
  settings,
588
543
  };
@@ -645,7 +600,7 @@ export async function compact(preparation, model, apiKey, headers, customInstruc
645
600
  }
646
601
  /** Single-model compaction attempt (no failover). Implementation of {@link compact}. */
647
602
  async function compactWithModel(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, retry, callbacks) {
648
- const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, } = preparation;
603
+ const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, previousRuleHistory, currentRuleEntries, fileOps, settings, } = preparation;
649
604
  // Generate summaries (can be parallel if both needed) and merge into one
650
605
  let summary;
651
606
  if (isSplitTurn && turnPrefixMessages.length > 0) {
@@ -663,6 +618,15 @@ async function compactWithModel(preparation, model, apiKey, headers, customInstr
663
618
  // Just generate history summary
664
619
  summary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, retry, callbacks);
665
620
  }
621
+ const triage = applyCompactionKnowledgeTriage({
622
+ generatedSummary: summary,
623
+ currentMessages: [...messagesToSummarize, ...turnPrefixMessages],
624
+ currentEntries: currentRuleEntries,
625
+ previousRules: previousRuleHistory?.rules,
626
+ previousSummary,
627
+ previousEntries: previousRuleHistory?.entries,
628
+ });
629
+ summary = triage.summary;
666
630
  // Compute file lists and append to summary
667
631
  const { readFiles, modifiedFiles } = computeFileLists(fileOps);
668
632
  summary += formatFileOperations(readFiles, modifiedFiles);
@@ -673,7 +637,7 @@ async function compactWithModel(preparation, model, apiKey, headers, customInstr
673
637
  summary,
674
638
  firstKeptEntryId,
675
639
  tokensBefore,
676
- details: { readFiles, modifiedFiles },
640
+ details: { readFiles, modifiedFiles, preservedRules: [...triage.preservedRules] },
677
641
  };
678
642
  }
679
643
  /**