@code-yeongyu/senpi 2026.5.13 → 2026.5.15-2

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 (274) hide show
  1. package/CHANGELOG.md +1109 -1150
  2. package/README.md +1 -2
  3. package/dist/core/agent-session.d.ts +9 -0
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +121 -12
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/bash-executor.d.ts.map +1 -1
  8. package/dist/core/bash-executor.js +1 -1
  9. package/dist/core/bash-executor.js.map +1 -1
  10. package/dist/core/compaction/compaction.d.ts.map +1 -1
  11. package/dist/core/compaction/compaction.js +2 -2
  12. package/dist/core/compaction/compaction.js.map +1 -1
  13. package/dist/core/dynamic-prompt/verification.d.ts +31 -0
  14. package/dist/core/dynamic-prompt/verification.d.ts.map +1 -1
  15. package/dist/core/dynamic-prompt/verification.js +41 -0
  16. package/dist/core/dynamic-prompt/verification.js.map +1 -1
  17. package/dist/core/export-html/index.d.ts.map +1 -1
  18. package/dist/core/export-html/index.js +8 -1
  19. package/dist/core/export-html/index.js.map +1 -1
  20. package/dist/core/extensions/builtin/anthropic-web-search/index.d.ts.map +1 -1
  21. package/dist/core/extensions/builtin/anthropic-web-search/index.js +20 -0
  22. package/dist/core/extensions/builtin/anthropic-web-search/index.js.map +1 -1
  23. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  24. package/dist/core/extensions/builtin/compaction/index.js +157 -29
  25. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  26. package/dist/core/extensions/builtin/compaction/openai-remote.d.ts +197 -0
  27. package/dist/core/extensions/builtin/compaction/openai-remote.d.ts.map +1 -0
  28. package/dist/core/extensions/builtin/compaction/openai-remote.js +690 -0
  29. package/dist/core/extensions/builtin/compaction/openai-remote.js.map +1 -0
  30. package/dist/core/extensions/builtin/compaction/prompts.d.ts +3 -3
  31. package/dist/core/extensions/builtin/compaction/prompts.d.ts.map +1 -1
  32. package/dist/core/extensions/builtin/compaction/prompts.js +0 -22
  33. package/dist/core/extensions/builtin/compaction/prompts.js.map +1 -1
  34. package/dist/core/extensions/builtin/compaction/repair-tool-pairs.d.ts +4 -0
  35. package/dist/core/extensions/builtin/compaction/repair-tool-pairs.d.ts.map +1 -0
  36. package/dist/core/extensions/builtin/compaction/repair-tool-pairs.js +48 -0
  37. package/dist/core/extensions/builtin/compaction/repair-tool-pairs.js.map +1 -0
  38. package/dist/core/extensions/builtin/compaction/speculative.d.ts +3 -1
  39. package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
  40. package/dist/core/extensions/builtin/compaction/speculative.js +82 -33
  41. package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
  42. package/dist/core/extensions/builtin/compaction/todo-bridge.d.ts +8 -0
  43. package/dist/core/extensions/builtin/compaction/todo-bridge.d.ts.map +1 -1
  44. package/dist/core/extensions/builtin/compaction/todo-bridge.js +12 -6
  45. package/dist/core/extensions/builtin/compaction/todo-bridge.js.map +1 -1
  46. package/dist/core/extensions/builtin/index.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/index.js +0 -20
  48. package/dist/core/extensions/builtin/index.js.map +1 -1
  49. package/dist/core/extensions/builtin/openai-web-search/index.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/openai-web-search/index.js +28 -0
  51. package/dist/core/extensions/builtin/openai-web-search/index.js.map +1 -1
  52. package/dist/core/extensions/builtin/permission-system/prompt.d.ts.map +1 -1
  53. package/dist/core/extensions/builtin/permission-system/prompt.js +0 -5
  54. package/dist/core/extensions/builtin/permission-system/prompt.js.map +1 -1
  55. package/dist/core/extensions/builtin/system-messages.d.ts +7 -7
  56. package/dist/core/extensions/builtin/system-messages.d.ts.map +1 -1
  57. package/dist/core/extensions/builtin/system-messages.js +10 -10
  58. package/dist/core/extensions/builtin/system-messages.js.map +1 -1
  59. package/dist/core/extensions/builtin/todotools/continuation/prompt.d.ts +1 -1
  60. package/dist/core/extensions/builtin/todotools/continuation/prompt.d.ts.map +1 -1
  61. package/dist/core/extensions/builtin/todotools/continuation/prompt.js +1 -1
  62. package/dist/core/extensions/builtin/todotools/continuation/prompt.js.map +1 -1
  63. package/dist/core/extensions/builtin/todotools/state.d.ts +1 -1
  64. package/dist/core/extensions/builtin/todotools/state.d.ts.map +1 -1
  65. package/dist/core/extensions/builtin/todotools/state.js +2 -2
  66. package/dist/core/extensions/builtin/todotools/state.js.map +1 -1
  67. package/dist/core/extensions/builtin/todotools/system-messages.d.ts +3 -3
  68. package/dist/core/extensions/builtin/todotools/system-messages.d.ts.map +1 -1
  69. package/dist/core/extensions/builtin/todotools/system-messages.js +6 -6
  70. package/dist/core/extensions/builtin/todotools/system-messages.js.map +1 -1
  71. package/dist/core/extensions/builtin/tool-pair-guard/index.d.ts +1 -1
  72. package/dist/core/extensions/builtin/tool-pair-guard/index.d.ts.map +1 -1
  73. package/dist/core/extensions/builtin/tool-pair-guard/index.js +8 -4
  74. package/dist/core/extensions/builtin/tool-pair-guard/index.js.map +1 -1
  75. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-chat-completions-payload.d.ts +3 -0
  76. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-chat-completions-payload.d.ts.map +1 -0
  77. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-chat-completions-payload.js +89 -0
  78. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-chat-completions-payload.js.map +1 -0
  79. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-responses-payload.d.ts +3 -0
  80. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-responses-payload.d.ts.map +1 -0
  81. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-responses-payload.js +122 -0
  82. package/dist/core/extensions/builtin/tool-pair-guard/sanitize-openai-responses-payload.js.map +1 -0
  83. package/dist/core/extensions/loader.d.ts.map +1 -1
  84. package/dist/core/extensions/loader.js +2 -0
  85. package/dist/core/extensions/loader.js.map +1 -1
  86. package/dist/core/extensions/runner.d.ts +3 -0
  87. package/dist/core/extensions/runner.d.ts.map +1 -1
  88. package/dist/core/extensions/runner.js +18 -0
  89. package/dist/core/extensions/runner.js.map +1 -1
  90. package/dist/core/extensions/types.d.ts +22 -0
  91. package/dist/core/extensions/types.d.ts.map +1 -1
  92. package/dist/core/extensions/types.js.map +1 -1
  93. package/dist/core/messages.d.ts +3 -3
  94. package/dist/core/messages.d.ts.map +1 -1
  95. package/dist/core/messages.js +5 -10
  96. package/dist/core/messages.js.map +1 -1
  97. package/dist/core/resource-loader.d.ts.map +1 -1
  98. package/dist/core/resource-loader.js +0 -9
  99. package/dist/core/resource-loader.js.map +1 -1
  100. package/dist/core/sdk.d.ts +2 -2
  101. package/dist/core/sdk.d.ts.map +1 -1
  102. package/dist/core/sdk.js +8 -23
  103. package/dist/core/sdk.js.map +1 -1
  104. package/dist/core/session-manager.d.ts.map +1 -1
  105. package/dist/core/session-manager.js +1 -1
  106. package/dist/core/session-manager.js.map +1 -1
  107. package/dist/core/settings-manager.d.ts +0 -5
  108. package/dist/core/settings-manager.d.ts.map +1 -1
  109. package/dist/core/settings-manager.js.map +1 -1
  110. package/dist/core/thinking-levels.d.ts +6 -0
  111. package/dist/core/thinking-levels.d.ts.map +1 -0
  112. package/dist/core/thinking-levels.js +36 -0
  113. package/dist/core/thinking-levels.js.map +1 -0
  114. package/dist/core/tools/bash.d.ts.map +1 -1
  115. package/dist/core/tools/bash.js +15 -1
  116. package/dist/core/tools/bash.js.map +1 -1
  117. package/dist/core/tools/render-utils.d.ts.map +1 -1
  118. package/dist/core/tools/render-utils.js +1 -1
  119. package/dist/core/tools/render-utils.js.map +1 -1
  120. package/dist/main.d.ts.map +1 -1
  121. package/dist/main.js +3 -2
  122. package/dist/main.js.map +1 -1
  123. package/dist/modes/interactive/components/assistant-message.d.ts +0 -3
  124. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  125. package/dist/modes/interactive/components/assistant-message.js +3 -22
  126. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  127. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  128. package/dist/modes/interactive/components/bash-execution.js +1 -1
  129. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  130. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  131. package/dist/modes/interactive/components/compaction-summary-message.js +20 -2
  132. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  133. package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
  134. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  135. package/dist/modes/interactive/components/extension-selector.js +6 -1
  136. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  137. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/keybinding-hints.js +3 -1
  139. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  140. package/dist/modes/interactive/interactive-mode.d.ts +23 -0
  141. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  142. package/dist/modes/interactive/interactive-mode.js +139 -54
  143. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  144. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  145. package/dist/modes/interactive/theme/theme.js +2 -2
  146. package/dist/modes/interactive/theme/theme.js.map +1 -1
  147. package/dist/modes/print-mode.d.ts.map +1 -1
  148. package/dist/modes/print-mode.js +3 -11
  149. package/dist/modes/print-mode.js.map +1 -1
  150. package/dist/modes/provider-native-rendering.d.ts +5 -0
  151. package/dist/modes/provider-native-rendering.d.ts.map +1 -0
  152. package/dist/modes/provider-native-rendering.js +247 -0
  153. package/dist/modes/provider-native-rendering.js.map +1 -0
  154. package/dist/utils/ansi.d.ts +2 -0
  155. package/dist/utils/ansi.d.ts.map +1 -0
  156. package/dist/utils/ansi.js +52 -0
  157. package/dist/utils/ansi.js.map +1 -0
  158. package/dist/utils/html.d.ts +7 -0
  159. package/dist/utils/html.d.ts.map +1 -0
  160. package/dist/utils/html.js +40 -0
  161. package/dist/utils/html.js.map +1 -0
  162. package/dist/utils/mime.d.ts +1 -0
  163. package/dist/utils/mime.d.ts.map +1 -1
  164. package/dist/utils/mime.js +59 -16
  165. package/dist/utils/mime.js.map +1 -1
  166. package/dist/utils/syntax-highlight.d.ts +12 -0
  167. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  168. package/dist/utils/syntax-highlight.js +118 -0
  169. package/dist/utils/syntax-highlight.js.map +1 -0
  170. package/dist/utils/tools-manager.d.ts.map +1 -1
  171. package/dist/utils/tools-manager.js +76 -7
  172. package/dist/utils/tools-manager.js.map +1 -1
  173. package/docs/extensions.md +0 -1
  174. package/docs/index.md +0 -1
  175. package/docs/sdk.md +25 -44
  176. package/docs/settings.md +1 -29
  177. package/docs/termux.md +2 -2
  178. package/docs/usage.md +1 -1
  179. package/examples/README.md +1 -1
  180. package/examples/extensions/README.md +0 -1
  181. package/examples/extensions/overlay-qa-tests.ts +1 -1
  182. package/examples/sdk/01-minimal.ts +14 -10
  183. package/examples/sdk/02-custom-model.ts +12 -8
  184. package/examples/sdk/03-custom-prompt.ts +24 -16
  185. package/examples/sdk/04-skills.ts +2 -2
  186. package/examples/sdk/05-tools.ts +8 -4
  187. package/examples/sdk/06-extensions.ts +11 -7
  188. package/examples/sdk/07-context-files.ts +2 -2
  189. package/examples/sdk/08-prompt-templates.ts +2 -2
  190. package/examples/sdk/09-api-keys-and-oauth.ts +8 -4
  191. package/examples/sdk/10-settings.ts +4 -4
  192. package/examples/sdk/11-sessions.ts +4 -0
  193. package/examples/sdk/12-full-control.ts +11 -7
  194. package/examples/sdk/README.md +6 -9
  195. package/package.json +7 -12
  196. package/dist/core/extensions/builtin/anthropic-code-execution/index.d.ts +0 -7
  197. package/dist/core/extensions/builtin/anthropic-code-execution/index.d.ts.map +0 -1
  198. package/dist/core/extensions/builtin/anthropic-code-execution/index.js +0 -79
  199. package/dist/core/extensions/builtin/anthropic-code-execution/index.js.map +0 -1
  200. package/dist/core/extensions/builtin/anthropic-computer-use/index.d.ts +0 -53
  201. package/dist/core/extensions/builtin/anthropic-computer-use/index.d.ts.map +0 -1
  202. package/dist/core/extensions/builtin/anthropic-computer-use/index.js +0 -676
  203. package/dist/core/extensions/builtin/anthropic-computer-use/index.js.map +0 -1
  204. package/dist/core/extensions/builtin/anthropic-text-editor/index.d.ts +0 -25
  205. package/dist/core/extensions/builtin/anthropic-text-editor/index.d.ts.map +0 -1
  206. package/dist/core/extensions/builtin/anthropic-text-editor/index.js +0 -244
  207. package/dist/core/extensions/builtin/anthropic-text-editor/index.js.map +0 -1
  208. package/dist/core/extensions/builtin/anthropic-tool-search/index.d.ts +0 -6
  209. package/dist/core/extensions/builtin/anthropic-tool-search/index.d.ts.map +0 -1
  210. package/dist/core/extensions/builtin/anthropic-tool-search/index.js +0 -112
  211. package/dist/core/extensions/builtin/anthropic-tool-search/index.js.map +0 -1
  212. package/dist/core/extensions/builtin/background-task/cancel-tool.d.ts +0 -10
  213. package/dist/core/extensions/builtin/background-task/cancel-tool.d.ts.map +0 -1
  214. package/dist/core/extensions/builtin/background-task/cancel-tool.js +0 -109
  215. package/dist/core/extensions/builtin/background-task/cancel-tool.js.map +0 -1
  216. package/dist/core/extensions/builtin/background-task/index.d.ts +0 -3
  217. package/dist/core/extensions/builtin/background-task/index.d.ts.map +0 -1
  218. package/dist/core/extensions/builtin/background-task/index.js +0 -207
  219. package/dist/core/extensions/builtin/background-task/index.js.map +0 -1
  220. package/dist/core/extensions/builtin/background-task/manager.d.ts +0 -17
  221. package/dist/core/extensions/builtin/background-task/manager.d.ts.map +0 -1
  222. package/dist/core/extensions/builtin/background-task/manager.js +0 -114
  223. package/dist/core/extensions/builtin/background-task/manager.js.map +0 -1
  224. package/dist/core/extensions/builtin/background-task/notification.d.ts +0 -22
  225. package/dist/core/extensions/builtin/background-task/notification.d.ts.map +0 -1
  226. package/dist/core/extensions/builtin/background-task/notification.js +0 -105
  227. package/dist/core/extensions/builtin/background-task/notification.js.map +0 -1
  228. package/dist/core/extensions/builtin/background-task/output-tool.d.ts +0 -11
  229. package/dist/core/extensions/builtin/background-task/output-tool.d.ts.map +0 -1
  230. package/dist/core/extensions/builtin/background-task/output-tool.js +0 -127
  231. package/dist/core/extensions/builtin/background-task/output-tool.js.map +0 -1
  232. package/dist/core/extensions/builtin/background-task/spawner.d.ts +0 -8
  233. package/dist/core/extensions/builtin/background-task/spawner.d.ts.map +0 -1
  234. package/dist/core/extensions/builtin/background-task/spawner.js +0 -207
  235. package/dist/core/extensions/builtin/background-task/spawner.js.map +0 -1
  236. package/dist/core/extensions/builtin/background-task/task-tool.d.ts +0 -20
  237. package/dist/core/extensions/builtin/background-task/task-tool.d.ts.map +0 -1
  238. package/dist/core/extensions/builtin/background-task/task-tool.js +0 -302
  239. package/dist/core/extensions/builtin/background-task/task-tool.js.map +0 -1
  240. package/dist/core/extensions/builtin/background-task/types.d.ts +0 -72
  241. package/dist/core/extensions/builtin/background-task/types.d.ts.map +0 -1
  242. package/dist/core/extensions/builtin/background-task/types.js +0 -32
  243. package/dist/core/extensions/builtin/background-task/types.js.map +0 -1
  244. package/dist/core/extensions/builtin/google-code-execution/index.d.ts +0 -7
  245. package/dist/core/extensions/builtin/google-code-execution/index.d.ts.map +0 -1
  246. package/dist/core/extensions/builtin/google-code-execution/index.js +0 -73
  247. package/dist/core/extensions/builtin/google-code-execution/index.js.map +0 -1
  248. package/dist/core/extensions/builtin/google-google-search/index.d.ts +0 -7
  249. package/dist/core/extensions/builtin/google-google-search/index.d.ts.map +0 -1
  250. package/dist/core/extensions/builtin/google-google-search/index.js +0 -83
  251. package/dist/core/extensions/builtin/google-google-search/index.js.map +0 -1
  252. package/dist/core/extensions/builtin/google-url-context/index.d.ts +0 -7
  253. package/dist/core/extensions/builtin/google-url-context/index.d.ts.map +0 -1
  254. package/dist/core/extensions/builtin/google-url-context/index.js +0 -82
  255. package/dist/core/extensions/builtin/google-url-context/index.js.map +0 -1
  256. package/dist/core/extensions/builtin/openai-api-parallel-tool-calls/index.d.ts +0 -6
  257. package/dist/core/extensions/builtin/openai-api-parallel-tool-calls/index.d.ts.map +0 -1
  258. package/dist/core/extensions/builtin/openai-api-parallel-tool-calls/index.js +0 -57
  259. package/dist/core/extensions/builtin/openai-api-parallel-tool-calls/index.js.map +0 -1
  260. package/dist/core/extensions/builtin/openai-code-interpreter/index.d.ts +0 -10
  261. package/dist/core/extensions/builtin/openai-code-interpreter/index.d.ts.map +0 -1
  262. package/dist/core/extensions/builtin/openai-code-interpreter/index.js +0 -95
  263. package/dist/core/extensions/builtin/openai-code-interpreter/index.js.map +0 -1
  264. package/docs/agents.md +0 -348
  265. package/examples/extensions/subagent/README.md +0 -172
  266. package/examples/extensions/subagent/agents/planner.md +0 -37
  267. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  268. package/examples/extensions/subagent/agents/scout.md +0 -50
  269. package/examples/extensions/subagent/agents/worker.md +0 -24
  270. package/examples/extensions/subagent/agents.ts +0 -126
  271. package/examples/extensions/subagent/index.ts +0 -987
  272. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  273. package/examples/extensions/subagent/prompts/implement.md +0 -10
  274. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-remote.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/openai-remote.ts"],"names":[],"mappings":"AACA,OAAO,EAON,YAAY,GAGZ,MAAM,uBAAuB,CAAC;AAK/B,MAAM,CAAC,MAAM,+BAA+B,GAAG,mCAAmC,CAAC;AACnF,MAAM,CAAC,MAAM,sBAAsB,GAAG,kBAAkB,CAAC;AAqLzD,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS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;IAC7D,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAE9B,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;IAChG,IAAI,CAAC,mBAAmB;QAAE,OAAO,SAAS,CAAC;IAE3C,MAAM,KAAK,GAAG,CAAC,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,gBAAgB,EAAE,GAAG,mBAAmB,CAAC,CAAC;IACpH,IAAI,EAAE,CAAC;QACN,OAAO,EAAE,CAAC;QACV,MAAM,EAAE,0BAA0B;QAClC,KAAK,EAAE,kCAAkC;QACzC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE;QACzB,iBAAiB,EAAE,MAAM,CAAC,OAAO;QACjC,cAAc,EAAE,KAAK,CAAC,MAAM;KAC5B,CAAC,CAAC;IACH,OAAO,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,CAC7B","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype Context,\n\ttype ImageContent,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ToolCall,\n} from \"@earendil-works/pi-ai\";\nimport type { CompactionResult } from \"../../../compaction/index.js\";\nimport type { SessionEntry } from \"../../../session-manager.js\";\nimport type { ServiceTier, SessionBeforeCompactEvent } from \"../../types.js\";\n\nexport const OPENAI_REMOTE_COMPACTION_SCHEMA = \"senpi.compaction.openai-remote.v1\";\nexport const SENPI_COMPACTION_EVENT = \"senpi:compaction\";\n\ntype OpenAiInputText = { type: \"input_text\"; text: string };\ntype OpenAiInputImage = { type: \"input_image\"; detail: \"auto\"; image_url: string };\ntype OpenAiInputContent = OpenAiInputText | OpenAiInputImage;\ntype OpenAiOutputText = { type: \"output_text\"; text: string; annotations: [] };\ntype OpenAiMessageInputItem = {\n\ttype?: \"message\";\n\tid?: string;\n\trole: \"user\" | \"system\" | \"developer\";\n\tcontent: string | OpenAiInputContent[];\n\tstatus?: \"in_progress\" | \"completed\" | \"incomplete\";\n};\ntype OpenAiAssistantMessageItem = {\n\ttype: \"message\";\n\tid: string;\n\trole: \"assistant\";\n\tstatus: \"completed\";\n\tcontent: OpenAiOutputText[];\n\tphase?: \"commentary\" | \"final_answer\";\n};\ntype OpenAiFunctionCallItem = {\n\ttype: \"function_call\";\n\tid?: string;\n\tcall_id: string;\n\tname: string;\n\targuments: string;\n};\ntype OpenAiFunctionCallOutputItem = {\n\ttype: \"function_call_output\";\n\tcall_id: string;\n\toutput: string;\n};\ntype OpenAiRemoteTransport = \"websocket\" | \"compact-endpoint\";\ntype OpenAiCompactionItem = {\n\ttype: \"compaction\";\n\tencrypted_content: string;\n\tid?: string | null;\n\tcreated_by?: string;\n};\ntype OpenAiContextCompactionItem = {\n\ttype: \"context_compaction\";\n\tencrypted_content: string;\n\tid?: string | null;\n\tcreated_by?: string;\n};\ntype OpenAiContextCompactionTriggerItem = {\n\ttype: \"context_compaction\";\n};\ntype OpenAiProviderNativeItem = Record<string, unknown> & { type: string };\nexport type OpenAiRemoteInputItem =\n\t| OpenAiMessageInputItem\n\t| OpenAiAssistantMessageItem\n\t| OpenAiFunctionCallItem\n\t| OpenAiFunctionCallOutputItem\n\t| OpenAiCompactionItem\n\t| OpenAiContextCompactionItem\n\t| OpenAiProviderNativeItem;\n\ntype OpenAiCompactBody = {\n\tmodel: string;\n\tinput: OpenAiRemoteInputItem[];\n\tinstructions?: string;\n\tprompt_cache_key?: string;\n\tservice_tier?: ServiceTier;\n};\n\nexport type OpenAiRemoteCompactionDetails = {\n\tschema: typeof OPENAI_REMOTE_COMPACTION_SCHEMA;\n\tmode: \"openai-remote\";\n\tprovider: \"openai\";\n\tapi: \"openai-responses\";\n\ttransport: OpenAiRemoteTransport;\n\tmodelId: string;\n\tresponseId: string;\n\tcreatedAt: number;\n\trequestInputItemCount: number;\n\tretainedInputItemCount: number;\n\treplacementInput: OpenAiRemoteInputItem[];\n\tusage?: Record<string, unknown>;\n};\n\nexport type OpenAiRemoteCompactionRequest = {\n\tbody: OpenAiCompactBody;\n\tinputItemCount: number;\n\ttokensBefore: number;\n};\n\nexport type OpenAiRemoteCompactionResult = CompactionResult<OpenAiRemoteCompactionDetails> & {\n\tdetails: OpenAiRemoteCompactionDetails;\n};\n\ntype OpenAiCompactedResponse = {\n\tid: string;\n\tcreated_at: number;\n\tobject: \"response.compaction\";\n\toutput: OpenAiRemoteInputItem[];\n\tusage?: Record<string, unknown>;\n};\n\ntype OpenAiResponsesStream = {\n\tresult(): Promise<AssistantMessage>;\n};\n\ntype OpenAiResponsesStreamRunner = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n) => OpenAiResponsesStream;\n\ntype OpenAiRemoteCompactionDependencies = {\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n\tstreamRunner?: OpenAiResponsesStreamRunner;\n};\n\ntype OpenAiRemoteCompactionContext = {\n\tgetSystemPrompt(): string;\n\tmodel: Model<Api> | undefined;\n\tmodelRegistry: {\n\t\tgetApiKeyAndHeaders(model: Model<Api>): Promise<\n\t\t\t| {\n\t\t\t\t\tok: true;\n\t\t\t\t\tapiKey?: string;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\textraBody?: Record<string, unknown>;\n\t\t\t\t\tupstreamModelId?: string;\n\t\t\t\t\tserviceTier?: ServiceTier;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\tok: false;\n\t\t\t\t\terror: string;\n\t\t\t }\n\t\t>;\n\t};\n\tserviceTier: ServiceTier | undefined;\n\tsessionManager: {\n\t\tgetSessionId(): string;\n\t};\n};\n\ntype OpenAiRemoteCompactionEvent =\n\t| {\n\t\t\tversion: 1;\n\t\t\taction: \"remote_started\";\n\t\t\troute: \"builtin.compaction.openai_remote\";\n\t\t\trequestId: string;\n\t\t\tmodelId: string;\n\t\t\tinputItemCount: number;\n\t\t\ttransport: OpenAiRemoteTransport;\n\t }\n\t| {\n\t\t\tversion: 1;\n\t\t\taction: \"remote_completed\";\n\t\t\troute: \"builtin.compaction.openai_remote\";\n\t\t\trequestId: string;\n\t\t\tmodelId: string;\n\t\t\tresponseId: string;\n\t\t\tretainedInputItemCount: number;\n\t\t\ttransport: OpenAiRemoteTransport;\n\t }\n\t| {\n\t\t\tversion: 1;\n\t\t\taction: \"remote_fallback\";\n\t\t\troute: \"builtin.compaction.openai_remote\";\n\t\t\trequestId: string;\n\t\t\tmodelId?: string;\n\t\t\treason: string;\n\t\t\ttransport?: OpenAiRemoteTransport;\n\t }\n\t| {\n\t\t\tversion: 1;\n\t\t\taction: \"remote_payload_rewritten\";\n\t\t\troute: \"builtin.compaction.openai_remote\";\n\t\t\tmodelId: string;\n\t\t\tcompactionEntryId: string;\n\t\t\tinputItemCount: number;\n\t };\n\ntype EmitCompactionEvent = (event: OpenAiRemoteCompactionEvent) => void;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonRecord(value: string | undefined): Record<string, unknown> | undefined {\n\tif (!value?.startsWith(\"{\")) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: \"commentary\" | \"final_answer\" } | undefined {\n\tif (!signature) return undefined;\n\tconst parsed = parseJsonRecord(signature);\n\tif (parsed?.v === 1 && typeof parsed.id === \"string\") {\n\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t}\n\t\treturn { id: parsed.id };\n\t}\n\treturn { id: signature };\n}\n\nfunction isOpenAiResponsesModel(model: Model<Api> | undefined): model is Model<\"openai-responses\"> {\n\treturn model?.provider === \"openai\" && model.api === \"openai-responses\";\n}\n\nfunction supportsOpenAiResponsesWebSocket(model: Model<\"openai-responses\">): boolean {\n\tif (model.compat?.supportsWebSocket !== undefined) return model.compat.supportsWebSocket;\n\ttry {\n\t\treturn new URL(model.baseUrl || \"https://api.openai.com/v1\").hostname === \"api.openai.com\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction toolResultText(content: string | TextContent[] | (TextContent | ImageContent)[]): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts: string[] = [];\n\tfor (const block of content) {\n\t\tif (block.type !== \"text\") return undefined;\n\t\tparts.push(block.text);\n\t}\n\treturn parts.join(\"\\n\");\n}\n\nfunction convertUserContent(content: string | (TextContent | ImageContent)[]): OpenAiInputContent[] {\n\tif (typeof content === \"string\") return [{ type: \"input_text\", text: content }];\n\treturn content.map((block): OpenAiInputContent => {\n\t\tif (block.type === \"text\") return { type: \"input_text\", text: block.text };\n\t\treturn {\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t};\n\t});\n}\n\nfunction providerNativeItem(raw: unknown): OpenAiProviderNativeItem | undefined {\n\tif (!isRecord(raw) || typeof raw.type !== \"string\") return undefined;\n\treturn { ...raw, type: raw.type };\n}\n\nfunction convertThinking(block: { thinkingSignature?: string }): OpenAiProviderNativeItem | undefined {\n\tconst parsed = parseJsonRecord(block.thinkingSignature);\n\tif (parsed?.type !== \"reasoning\") return undefined;\n\treturn { ...parsed, type: \"reasoning\" };\n}\n\nfunction convertTextBlock(block: TextContent, messageIndex: number): OpenAiAssistantMessageItem {\n\tconst signature = parseTextSignature(block.textSignature);\n\tconst item = {\n\t\ttype: \"message\",\n\t\trole: \"assistant\",\n\t\tstatus: \"completed\",\n\t\tid: signature?.id ?? `msg_${messageIndex}`,\n\t\tcontent: [{ type: \"output_text\", text: block.text, annotations: [] }],\n\t\t...(signature?.phase ? { phase: signature.phase } : {}),\n\t} satisfies OpenAiAssistantMessageItem;\n\treturn item;\n}\n\nfunction convertToolCall(block: ToolCall): OpenAiFunctionCallItem {\n\tconst [callId = block.id, itemId] = block.id.split(\"|\");\n\treturn {\n\t\ttype: \"function_call\",\n\t\t...(itemId ? { id: itemId } : {}),\n\t\tcall_id: callId,\n\t\tname: block.name,\n\t\targuments: JSON.stringify(block.arguments ?? {}),\n\t};\n}\n\nfunction isSameOpenAiResponsesAssistant(message: AssistantMessage): boolean {\n\treturn message.provider === \"openai\" && message.api === \"openai-responses\";\n}\n\nfunction convertAssistantMessage(message: AssistantMessage, messageIndex: number): OpenAiRemoteInputItem[] | undefined {\n\tif (!isSameOpenAiResponsesAssistant(message)) return undefined;\n\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tfor (const block of message.content) {\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\titems.push(convertTextBlock(block, messageIndex));\n\t\t\t\tbreak;\n\t\t\tcase \"thinking\": {\n\t\t\t\tconst reasoning = convertThinking(block);\n\t\t\t\tif (!reasoning) return undefined;\n\t\t\t\titems.push(reasoning);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolCall\":\n\t\t\t\titems.push(convertToolCall(block));\n\t\t\t\tbreak;\n\t\t\tcase \"providerNative\": {\n\t\t\t\tconst item = providerNativeItem(block.raw);\n\t\t\t\tif (!item) return undefined;\n\t\t\t\titems.push(item);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn items.length > 0 ? items : undefined;\n}\n\nfunction convertAgentMessage(message: AgentMessage, messageIndex: number): OpenAiRemoteInputItem[] | undefined {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn [{ role: \"user\", content: convertUserContent(message.content) }];\n\t\tcase \"assistant\":\n\t\t\treturn convertAssistantMessage(message, messageIndex);\n\t\tcase \"toolResult\": {\n\t\t\tconst [callId = message.toolCallId] = message.toolCallId.split(\"|\");\n\t\t\tconst output = toolResultText(message.content);\n\t\t\tif (output === undefined) return undefined;\n\t\t\treturn [{ type: \"function_call_output\", call_id: callId, output }];\n\t\t}\n\t\tcase \"bashExecution\":\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\tcase \"custom\":\n\t\t\treturn undefined;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = message;\n\t\t\treturn exhaustive;\n\t\t}\n\t}\n}\n\nfunction detailsFromEntry(entry: SessionEntry): OpenAiRemoteCompactionDetails | undefined {\n\tif (entry.type !== \"compaction\") return undefined;\n\treturn getOpenAiRemoteCompactionDetails(entry.details);\n}\n\nexport function getOpenAiRemoteCompactionDetails(value: unknown): OpenAiRemoteCompactionDetails | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (value.schema !== OPENAI_REMOTE_COMPACTION_SCHEMA || value.mode !== \"openai-remote\") return undefined;\n\tif (value.provider !== \"openai\" || value.api !== \"openai-responses\") return undefined;\n\tif (typeof value.modelId !== \"string\" || typeof value.responseId !== \"string\") return undefined;\n\tif (typeof value.createdAt !== \"number\") return undefined;\n\tif (typeof value.requestInputItemCount !== \"number\" || typeof value.retainedInputItemCount !== \"number\") {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(value.replacementInput)) return undefined;\n\treturn {\n\t\tschema: OPENAI_REMOTE_COMPACTION_SCHEMA,\n\t\tmode: \"openai-remote\",\n\t\tprovider: \"openai\",\n\t\tapi: \"openai-responses\",\n\t\ttransport: value.transport === \"websocket\" ? \"websocket\" : \"compact-endpoint\",\n\t\tmodelId: value.modelId,\n\t\tresponseId: value.responseId,\n\t\tcreatedAt: value.createdAt,\n\t\trequestInputItemCount: value.requestInputItemCount,\n\t\tretainedInputItemCount: value.retainedInputItemCount,\n\t\treplacementInput: value.replacementInput.filter((item): item is OpenAiRemoteInputItem => isRecord(item)),\n\t\t...(isRecord(value.usage) ? { usage: value.usage } : {}),\n\t};\n}\n\nfunction convertBranchEntries(entries: SessionEntry[]): OpenAiRemoteInputItem[] | undefined {\n\tconst items: OpenAiRemoteInputItem[] = [];\n\tlet messageIndex = 0;\n\tfor (const entry of entries) {\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst converted = convertAgentMessage(entry.message, messageIndex);\n\t\t\t\tif (!converted) return undefined;\n\t\t\t\titems.push(...converted);\n\t\t\t\tmessageIndex++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\": {\n\t\t\t\tconst details = detailsFromEntry(entry);\n\t\t\t\tif (!details) return undefined;\n\t\t\t\titems.push(...details.replacementInput);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom_message\":\n\t\t\t\treturn undefined;\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn items;\n}\n\nexport function createOpenAiRemoteCompactionRequest(options: {\n\tmodel: Model<Api> | undefined;\n\tsystemPrompt: string;\n\tbranchEntries: SessionEntry[];\n\ttokensBefore: number;\n\tpromptCacheKey?: string;\n\tserviceTier?: ServiceTier;\n}): OpenAiRemoteCompactionRequest | undefined {\n\tif (!isOpenAiResponsesModel(options.model)) return undefined;\n\tconst input = convertBranchEntries(options.branchEntries);\n\tif (!input || input.length === 0) return undefined;\n\treturn {\n\t\tbody: {\n\t\t\tmodel: options.model.id,\n\t\t\tinput,\n\t\t\t...(options.systemPrompt ? { instructions: options.systemPrompt } : {}),\n\t\t\t...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n\t\t\t...(options.serviceTier ? { service_tier: options.serviceTier } : {}),\n\t\t},\n\t\tinputItemCount: input.length,\n\t\ttokensBefore: options.tokensBefore,\n\t};\n}\n\nfunction isOpenAiCompactionItem(item: OpenAiRemoteInputItem): item is OpenAiCompactionItem {\n\treturn item.type === \"compaction\" && typeof item.encrypted_content === \"string\";\n}\n\nfunction isOpenAiContextCompactionItem(item: OpenAiRemoteInputItem): item is OpenAiContextCompactionItem {\n\treturn item.type === \"context_compaction\" && typeof item.encrypted_content === \"string\";\n}\n\nfunction isOpenAiRemoteCompactionOutputItem(\n\titem: OpenAiRemoteInputItem,\n): item is OpenAiCompactionItem | OpenAiContextCompactionItem {\n\treturn isOpenAiCompactionItem(item) || isOpenAiContextCompactionItem(item);\n}\n\nfunction isRetainedRemoteOutputItem(item: OpenAiRemoteInputItem): boolean {\n\tif (isOpenAiRemoteCompactionOutputItem(item)) return true;\n\treturn item.type === \"message\" && (item.role === \"user\" || item.role === \"system\" || item.role === \"developer\");\n}\n\nfunction isRetainedResponsesStreamInputItem(item: OpenAiRemoteInputItem): boolean {\n\tif (item.type === \"message\") return item.role === \"user\";\n\treturn \"role\" in item && item.role === \"user\";\n}\n\nfunction isOpenAiCompactedResponse(value: unknown): value is OpenAiCompactedResponse {\n\tif (!isRecord(value)) return false;\n\tif (value.object !== \"response.compaction\" || typeof value.id !== \"string\" || typeof value.created_at !== \"number\") {\n\t\treturn false;\n\t}\n\treturn Array.isArray(value.output);\n}\n\nexport function buildOpenAiRemoteCompactionResult(options: {\n\tmodel: Model<\"openai-responses\">;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\trequestInputItemCount: number;\n\tresponse: OpenAiCompactedResponse;\n}): OpenAiRemoteCompactionResult {\n\tconst replacementInput = options.response.output.filter(isRetainedRemoteOutputItem);\n\tconst compactionItem = replacementInput.find(isOpenAiRemoteCompactionOutputItem);\n\tif (!compactionItem) {\n\t\tthrow new Error(\"OpenAI remote compaction did not return a compaction item\");\n\t}\n\n\tconst details = {\n\t\tschema: OPENAI_REMOTE_COMPACTION_SCHEMA,\n\t\tmode: \"openai-remote\",\n\t\tprovider: \"openai\",\n\t\tapi: \"openai-responses\",\n\t\ttransport: \"compact-endpoint\",\n\t\tmodelId: options.model.id,\n\t\tresponseId: options.response.id,\n\t\tcreatedAt: options.response.created_at,\n\t\trequestInputItemCount: options.requestInputItemCount,\n\t\tretainedInputItemCount: replacementInput.length,\n\t\treplacementInput,\n\t\t...(options.response.usage ? { usage: options.response.usage } : {}),\n\t} satisfies OpenAiRemoteCompactionDetails;\n\n\treturn {\n\t\tsummary: [\n\t\t\t\"OpenAI remote compaction checkpoint.\",\n\t\t\t`Native /v1/responses/compact replay is active for ${replacementInput.length.toLocaleString()} retained item(s).`,\n\t\t\t`Original OpenAI input items compacted: ${options.requestInputItemCount.toLocaleString()}.`,\n\t\t].join(\"\\n\"),\n\t\tfirstKeptEntryId: options.firstKeptEntryId,\n\t\ttokensBefore: options.tokensBefore,\n\t\tdetails,\n\t};\n}\n\nfunction compactEndpointUrl(model: Model<\"openai-responses\">): string {\n\tconst baseUrl = model.baseUrl || \"https://api.openai.com/v1\";\n\treturn new URL(\"responses/compact\", baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`).toString();\n}\n\nfunction createHeaders(auth: { apiKey?: string; headers?: Record<string, string> }): Headers | undefined {\n\tconst headers = new Headers(auth.headers);\n\theaders.set(\"content-type\", \"application/json\");\n\tif (!headers.has(\"authorization\") && auth.apiKey) {\n\t\theaders.set(\"authorization\", `Bearer ${auth.apiKey}`);\n\t}\n\treturn headers.has(\"authorization\") ? headers : undefined;\n}\n\nfunction createOpenAiResponsesStreamCompactionInput(request: OpenAiRemoteCompactionRequest): OpenAiRemoteInputItem[] {\n\treturn [...request.body.input, { type: \"context_compaction\" } satisfies OpenAiContextCompactionTriggerItem];\n}\n\nexport function createOpenAiResponsesStreamCompactionPayload(\n\tpayload: unknown,\n\trequest: OpenAiRemoteCompactionRequest,\n): unknown | undefined {\n\tif (!isRecord(payload)) return undefined;\n\treturn {\n\t\t...payload,\n\t\tmodel: request.body.model,\n\t\tinput: [...leadingPromptMessages(payload.input), ...createOpenAiResponsesStreamCompactionInput(request)],\n\t\t...(request.body.prompt_cache_key ? { prompt_cache_key: request.body.prompt_cache_key } : {}),\n\t\t...(request.body.service_tier ? { service_tier: request.body.service_tier } : {}),\n\t};\n}\n\nfunction findResponsesStreamCompactionOutput(message: AssistantMessage): OpenAiContextCompactionItem | undefined {\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"providerNative\") continue;\n\t\tconst item = providerNativeItem(block.raw);\n\t\tif (item && isOpenAiContextCompactionItem(item)) return item;\n\t}\n\treturn undefined;\n}\n\nfunction usageRecordFromAssistant(message: AssistantMessage): Record<string, unknown> {\n\treturn {\n\t\tinput: message.usage.input,\n\t\toutput: message.usage.output,\n\t\tcacheRead: message.usage.cacheRead,\n\t\tcacheWrite: message.usage.cacheWrite,\n\t\ttotalTokens: message.usage.totalTokens,\n\t};\n}\n\nexport function buildOpenAiResponsesStreamCompactionResult(options: {\n\tmodel: Model<\"openai-responses\">;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\trequestInput: OpenAiRemoteInputItem[];\n\tresponse: AssistantMessage;\n\tnow: () => number;\n}): OpenAiRemoteCompactionResult {\n\tconst compactionItem = findResponsesStreamCompactionOutput(options.response);\n\tif (!compactionItem) {\n\t\tthrow new Error(\"OpenAI Responses stream compaction did not return a context_compaction item\");\n\t}\n\n\tconst retainedInput = options.requestInput.filter(isRetainedResponsesStreamInputItem);\n\tconst replacementInput = [...retainedInput, compactionItem];\n\tconst details = {\n\t\tschema: OPENAI_REMOTE_COMPACTION_SCHEMA,\n\t\tmode: \"openai-remote\",\n\t\tprovider: \"openai\",\n\t\tapi: \"openai-responses\",\n\t\ttransport: \"websocket\",\n\t\tmodelId: options.model.id,\n\t\tresponseId: options.response.responseId ?? `response-${options.now()}`,\n\t\tcreatedAt: Math.floor(options.response.timestamp / 1000),\n\t\trequestInputItemCount: options.requestInput.length,\n\t\tretainedInputItemCount: replacementInput.length,\n\t\treplacementInput,\n\t\tusage: usageRecordFromAssistant(options.response),\n\t} satisfies OpenAiRemoteCompactionDetails;\n\n\treturn {\n\t\tsummary: [\n\t\t\t\"OpenAI remote compaction checkpoint.\",\n\t\t\t`Native Responses WebSocket replay is active for ${replacementInput.length.toLocaleString()} retained item(s).`,\n\t\t\t`Original OpenAI input items compacted: ${options.requestInput.length.toLocaleString()}.`,\n\t\t].join(\"\\n\"),\n\t\tfirstKeptEntryId: options.firstKeptEntryId,\n\t\ttokensBefore: options.tokensBefore,\n\t\tdetails,\n\t};\n}\n\nasync function runOpenAiResponsesStreamCompaction(options: {\n\tmodel: Model<\"openai-responses\">;\n\tauth: { apiKey?: string; headers?: Record<string, string>; extraBody?: Record<string, unknown> };\n\tfirstKeptEntryId: string;\n\tnow: () => number;\n\trequest: OpenAiRemoteCompactionRequest;\n\tsignal: AbortSignal;\n\tstreamRunner: OpenAiResponsesStreamRunner;\n\tsystemPrompt: string;\n}): Promise<OpenAiRemoteCompactionResult | undefined> {\n\tconst stream = options.streamRunner(\n\t\toptions.model,\n\t\t{ systemPrompt: options.systemPrompt, messages: [] },\n\t\t{\n\t\t\tapiKey: options.auth.apiKey,\n\t\t\tcacheRetention: \"short\",\n\t\t\textraBody: options.auth.extraBody,\n\t\t\theaders: options.auth.headers,\n\t\t\tonPayload: (payload) => {\n\t\t\t\tconst rewritten = createOpenAiResponsesStreamCompactionPayload(payload, options.request);\n\t\t\t\tif (!isRecord(rewritten) || !Array.isArray(rewritten.input)) {\n\t\t\t\t\tthrow new Error(\"Unable to build OpenAI Responses stream compaction payload\");\n\t\t\t\t}\n\t\t\t\treturn rewritten;\n\t\t\t},\n\t\t\tsessionId: options.request.body.prompt_cache_key,\n\t\t\tsignal: options.signal,\n\t\t\ttransport: \"websocket\",\n\t\t},\n\t);\n\tconst response = await stream.result();\n\tif (response.stopReason === \"error\" || response.stopReason === \"aborted\") {\n\t\treturn undefined;\n\t}\n\treturn buildOpenAiResponsesStreamCompactionResult({\n\t\tmodel: options.model,\n\t\tfirstKeptEntryId: options.firstKeptEntryId,\n\t\ttokensBefore: options.request.tokensBefore,\n\t\trequestInput: options.request.body.input,\n\t\tresponse,\n\t\tnow: options.now,\n\t});\n}\n\nasync function runOpenAiCompactEndpointCompaction(options: {\n\tfetchImpl: typeof fetch;\n\theaders: Headers;\n\tmodel: Model<\"openai-responses\">;\n\trequest: OpenAiRemoteCompactionRequest;\n\trequestId: string;\n\tsignal: AbortSignal;\n\tfirstKeptEntryId: string;\n\temit?: EmitCompactionEvent;\n}): Promise<OpenAiRemoteCompactionResult | undefined> {\n\toptions.emit?.({\n\t\tversion: 1,\n\t\taction: \"remote_started\",\n\t\troute: \"builtin.compaction.openai_remote\",\n\t\trequestId: options.requestId,\n\t\tmodelId: options.model.id,\n\t\tinputItemCount: options.request.inputItemCount,\n\t\ttransport: \"compact-endpoint\",\n\t});\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await options.fetchImpl(compactEndpointUrl(options.model), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: options.headers,\n\t\t\tbody: JSON.stringify(options.request.body),\n\t\t\tsignal: options.signal,\n\t\t});\n\t} catch (error) {\n\t\tif (options.signal.aborted) throw error;\n\t\toptions.emit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: options.requestId,\n\t\t\tmodelId: options.model.id,\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\ttransport: \"compact-endpoint\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tif (!response.ok) {\n\t\toptions.emit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: options.requestId,\n\t\t\tmodelId: options.model.id,\n\t\t\treason: `HTTP ${response.status}`,\n\t\t\ttransport: \"compact-endpoint\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = await response.json();\n\t} catch (error) {\n\t\toptions.emit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: options.requestId,\n\t\t\tmodelId: options.model.id,\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\ttransport: \"compact-endpoint\",\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (!isOpenAiCompactedResponse(payload)) {\n\t\toptions.emit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: options.requestId,\n\t\t\tmodelId: options.model.id,\n\t\t\treason: \"invalid-compact-response\",\n\t\t\ttransport: \"compact-endpoint\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tlet result: OpenAiRemoteCompactionResult;\n\ttry {\n\t\tresult = buildOpenAiRemoteCompactionResult({\n\t\t\tmodel: options.model,\n\t\t\tfirstKeptEntryId: options.firstKeptEntryId,\n\t\t\ttokensBefore: options.request.tokensBefore,\n\t\t\trequestInputItemCount: options.request.inputItemCount,\n\t\t\tresponse: payload,\n\t\t});\n\t} catch (error) {\n\t\toptions.emit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: options.requestId,\n\t\t\tmodelId: options.model.id,\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\ttransport: \"compact-endpoint\",\n\t\t});\n\t\treturn undefined;\n\t}\n\toptions.emit?.({\n\t\tversion: 1,\n\t\taction: \"remote_completed\",\n\t\troute: \"builtin.compaction.openai_remote\",\n\t\trequestId: options.requestId,\n\t\tmodelId: options.model.id,\n\t\tresponseId: payload.id,\n\t\tretainedInputItemCount: result.details.retainedInputItemCount,\n\t\ttransport: \"compact-endpoint\",\n\t});\n\treturn result;\n}\n\nexport async function runOpenAiRemoteCompaction(\n\tctx: OpenAiRemoteCompactionContext,\n\tevent: SessionBeforeCompactEvent,\n\temit?: EmitCompactionEvent,\n\tdependencies: OpenAiRemoteCompactionDependencies = {},\n): Promise<OpenAiRemoteCompactionResult | undefined> {\n\tconst model = ctx.model;\n\tif (!isOpenAiResponsesModel(model) || event.reason === \"branch\") {\n\t\temit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: event.requestId,\n\t\t\tmodelId: model?.id,\n\t\t\treason: event.reason === \"branch\" ? \"branch-compaction\" : \"not-openai-responses\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tconst auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\tif (!auth.ok) {\n\t\temit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: event.requestId,\n\t\t\tmodelId: model.id,\n\t\t\treason: auth.error,\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tconst requestModel = auth.upstreamModelId ? { ...model, id: auth.upstreamModelId } : model;\n\tconst serviceTier = ctx.serviceTier ?? auth.serviceTier;\n\tconst request = createOpenAiRemoteCompactionRequest({\n\t\tmodel: requestModel,\n\t\tsystemPrompt: ctx.getSystemPrompt(),\n\t\tbranchEntries: event.branchEntries,\n\t\ttokensBefore: event.preparation.tokensBefore,\n\t\tpromptCacheKey: ctx.sessionManager.getSessionId(),\n\t\tserviceTier,\n\t});\n\tif (!request) {\n\t\temit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: event.requestId,\n\t\t\tmodelId: model.id,\n\t\t\treason: \"session-not-openai-native\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\tif (supportsOpenAiResponsesWebSocket(requestModel)) {\n\t\temit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_started\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: event.requestId,\n\t\t\tmodelId: requestModel.id,\n\t\t\tinputItemCount: request.inputItemCount,\n\t\t\ttransport: \"websocket\",\n\t\t});\n\t\ttry {\n\t\t\tconst result = await runOpenAiResponsesStreamCompaction({\n\t\t\t\tmodel: requestModel,\n\t\t\t\tauth,\n\t\t\t\tfirstKeptEntryId: event.preparation.firstKeptEntryId,\n\t\t\t\tnow: dependencies.now ?? Date.now,\n\t\t\t\trequest,\n\t\t\t\tsignal: event.signal,\n\t\t\t\tstreamRunner:\n\t\t\t\t\tdependencies.streamRunner ??\n\t\t\t\t\t((streamModel, context, options) => streamSimple(streamModel, context, options)),\n\t\t\t\tsystemPrompt: ctx.getSystemPrompt(),\n\t\t\t});\n\t\t\tif (result) {\n\t\t\t\temit?.({\n\t\t\t\t\tversion: 1,\n\t\t\t\t\taction: \"remote_completed\",\n\t\t\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\t\t\trequestId: event.requestId,\n\t\t\t\t\tmodelId: requestModel.id,\n\t\t\t\t\tresponseId: result.details.responseId,\n\t\t\t\t\tretainedInputItemCount: result.details.retainedInputItemCount,\n\t\t\t\t\ttransport: \"websocket\",\n\t\t\t\t});\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\temit?.({\n\t\t\t\tversion: 1,\n\t\t\t\taction: \"remote_fallback\",\n\t\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\t\trequestId: event.requestId,\n\t\t\t\tmodelId: requestModel.id,\n\t\t\t\treason: \"websocket-compaction-no-result\",\n\t\t\t\ttransport: \"websocket\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (event.signal.aborted) throw error;\n\t\t\temit?.({\n\t\t\t\tversion: 1,\n\t\t\t\taction: \"remote_fallback\",\n\t\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\t\trequestId: event.requestId,\n\t\t\t\tmodelId: requestModel.id,\n\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\ttransport: \"websocket\",\n\t\t\t});\n\t\t}\n\t}\n\n\tconst headers = createHeaders(auth);\n\tif (!headers) {\n\t\temit?.({\n\t\t\tversion: 1,\n\t\t\taction: \"remote_fallback\",\n\t\t\troute: \"builtin.compaction.openai_remote\",\n\t\t\trequestId: event.requestId,\n\t\t\tmodelId: model.id,\n\t\t\treason: \"missing-openai-auth\",\n\t\t});\n\t\treturn undefined;\n\t}\n\n\treturn runOpenAiCompactEndpointCompaction({\n\t\tfetchImpl: dependencies.fetch ?? fetch,\n\t\theaders,\n\t\tmodel: requestModel,\n\t\trequest,\n\t\trequestId: event.requestId,\n\t\tsignal: event.signal,\n\t\tfirstKeptEntryId: event.preparation.firstKeptEntryId,\n\t\temit,\n\t});\n}\n\nfunction latestRemoteCompaction(\n\tentries: SessionEntry[],\n): { entryId: string; index: number; details: OpenAiRemoteCompactionDetails } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type !== \"compaction\") continue;\n\t\tconst details = getOpenAiRemoteCompactionDetails(entry.details);\n\t\tif (details) return { entryId: entry.id, index, details };\n\t\treturn undefined;\n\t}\n\treturn undefined;\n}\n\nfunction leadingPromptMessages(input: unknown): OpenAiRemoteInputItem[] {\n\tif (!Array.isArray(input)) return [];\n\tconst result: OpenAiRemoteInputItem[] = [];\n\tfor (const item of input) {\n\t\tif (!isRecord(item)) break;\n\t\tconst role = item.role;\n\t\tif (role !== \"system\" && role !== \"developer\") break;\n\t\tresult.push(providerNativeItem(item) ?? { role, content: typeof item.content === \"string\" ? item.content : [] });\n\t}\n\treturn result;\n}\n\nexport function rewriteOpenAiPayloadWithRemoteCompaction(\n\tpayload: unknown,\n\toptions: { model: Model<Api> | undefined; branchEntries: SessionEntry[] },\n\temit?: EmitCompactionEvent,\n): unknown | undefined {\n\tif (!isOpenAiResponsesModel(options.model) || !isRecord(payload)) return undefined;\n\tconst remote = latestRemoteCompaction(options.branchEntries);\n\tif (!remote) return undefined;\n\n\tconst postCompactionItems = convertBranchEntries(options.branchEntries.slice(remote.index + 1));\n\tif (!postCompactionItems) return undefined;\n\n\tconst input = [...leadingPromptMessages(payload.input), ...remote.details.replacementInput, ...postCompactionItems];\n\temit?.({\n\t\tversion: 1,\n\t\taction: \"remote_payload_rewritten\",\n\t\troute: \"builtin.compaction.openai_remote\",\n\t\tmodelId: options.model.id,\n\t\tcompactionEntryId: remote.entryId,\n\t\tinputItemCount: input.length,\n\t});\n\treturn { ...payload, input };\n}\n"]}
@@ -5,9 +5,9 @@ export type BuildMergedCompactionPromptOptions = {
5
5
  customInstructions?: string;
6
6
  };
7
7
  export declare const MERGED_COMPACTION_PROMPT_SYSTEM = "[SYSTEM DIRECTIVE: OH-MY-OPENCODE - COMPACTION CONTEXT]\n\nYou are the COMPACTION ARCHIVIST. Create a structured handoff summary that lets the next agent continue this exact session without restarting, re-searching, or losing constraints.\n\nCardinal rules:\nR1. Quote user requests and constraints VERBATIM. Do not paraphrase.\nR2. If a section has no content, write \"None.\" Never delete a section.\nR3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\nR4. Preserve every session_id, file path, and identifier byte-for-byte.\n\nDo NOT use tools. Output only the requested summary block.";
8
- export declare const MERGED_COMPACTION_PROMPT_USER = "[USER]\n[INTERNAL COMPACTION INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List ALL background agent tasks spawned during this session.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART \u2014 session_ids must be preserved byte-for-byte.\n- Each listed session retains full context. After compaction, use session_id to continue existing agent sessions instead of spawning new ones.\n\n## 9. Agent Verification State (CONDITIONAL \u2014 emit only for reviewer agents)\n- **Current Agent**: What agent is running.\n- **Verification Progress**: Files already verified or validated.\n- **Pending Verifications**: Files still needing verification.\n- **Previous Rejections**: If reviewer agent, what was rejected and why.\n- **Acceptance Status**: Current state of review process.\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
9
- export declare const MERGED_COMPACTION_PROMPT_UPDATE = "[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n## 8. Delegated Agent Sessions\n- Preserve every existing agent name, status, description, and session_id byte-for-byte unless updated by new messages.\n- RESUME, DON'T RESTART \u2014 session_ids must be preserved byte-for-byte.\n\n## 9. Agent Verification State (CONDITIONAL \u2014 emit only for reviewer agents)\n- Preserve reviewer context and update verification progress, pending verifications, previous rejections, and acceptance status.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
10
- export declare const MERGED_COMPACTION_PROMPT_BRANCH = "[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient \u00A72 toward the branched intent and why this branch exists.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List branch-relevant background agent tasks.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART \u2014 session_ids must be preserved byte-for-byte.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
8
+ export declare const MERGED_COMPACTION_PROMPT_USER = "[USER]\n[INTERNAL COMPACTION INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
9
+ export declare const MERGED_COMPACTION_PROMPT_UPDATE = "[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
10
+ export declare const MERGED_COMPACTION_PROMPT_BRANCH = "[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient \u00A72 toward the branched intent and why this branch exists.\n\nPASS 1 \u2014 Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
11
11
  export declare const MERGED_COMPACTION_PROMPT_TURN_PREFIX = "[USER]\n[INTERNAL TURN-PREFIX SUMMARY INSTRUCTION \u2014 NOT CONVERSATION HISTORY]\nCreate a compact prefix summary for the next turn. Emit only the sections listed below.\n\nPASS 1 \u2014 Internal task-intent extraction\nSilently determine the current task intent and the minimum context needed for the next turn.\n\nPASS 2 \u2014 Emit summary biased toward Pass 1\nThe structured output portion MUST be wrapped as `<summary>...</summary>` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Quote the active user request and any steering constraints exactly as stated.\n\n## 2. Final Goal\n- State the immediate end state needed for the next turn.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 5. Active Working Context\n- Include only files, identifiers, runtime state, and exact next-turn context needed to continue immediately.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.";
12
12
  export declare function buildPrompt(options: BuildMergedCompactionPromptOptions): {
13
13
  system: string;
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/prompts.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,6BAA6B,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,aAAa,CAAC;AAE5F,MAAM,MAAM,kCAAkC,GAAG;IAChD,OAAO,EAAE,6BAA6B,CAAC;IACvC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,+BAA+B,+rBAUe,CAAC;AAE5D,eAAO,MAAM,6BAA6B,+sHAgEyC,CAAC;AAEpF,eAAO,MAAM,+BAA+B,wiFAuDuC,CAAC;AAEpF,eAAO,MAAM,+BAA+B,25EAiDuC,CAAC;AAEpF,eAAO,MAAM,oCAAoC,6jCA0BkC,CAAC;AAEpF,wBAAgB,WAAW,CAAC,OAAO,EAAE,kCAAkC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAOzG","sourcesContent":["export type MergedCompactionPromptVariant = \"default\" | \"update\" | \"branch\" | \"turn_prefix\";\n\nexport type BuildMergedCompactionPromptOptions = {\n\tvariant: MergedCompactionPromptVariant;\n\tpreviousSummary?: string;\n\tcustomInstructions?: string;\n};\n\nexport const MERGED_COMPACTION_PROMPT_SYSTEM = `[SYSTEM DIRECTIVE: OH-MY-OPENCODE - COMPACTION CONTEXT]\n\nYou are the COMPACTION ARCHIVIST. Create a structured handoff summary that lets the next agent continue this exact session without restarting, re-searching, or losing constraints.\n\nCardinal rules:\nR1. Quote user requests and constraints VERBATIM. Do not paraphrase.\nR2. If a section has no content, write \"None.\" Never delete a section.\nR3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\nR4. Preserve every session_id, file path, and identifier byte-for-byte.\n\nDo NOT use tools. Output only the requested summary block.`;\n\nexport const MERGED_COMPACTION_PROMPT_USER = `[USER]\n[INTERNAL COMPACTION INSTRUCTION — NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List ALL background agent tasks spawned during this session.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n- Each listed session retains full context. After compaction, use session_id to continue existing agent sessions instead of spawning new ones.\n\n## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)\n- **Current Agent**: What agent is running.\n- **Verification Progress**: Files already verified or validated.\n- **Pending Verifications**: Files still needing verification.\n- **Previous Rejections**: If reviewer agent, what was rejected and why.\n- **Acceptance Status**: Current state of review process.\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_UPDATE = `[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION — NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 — Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n## 8. Delegated Agent Sessions\n- Preserve every existing agent name, status, description, and session_id byte-for-byte unless updated by new messages.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n\n## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)\n- Preserve reviewer context and update verification progress, pending verifications, previous rejections, and acceptance status.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_BRANCH = `[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient §2 toward the branched intent and why this branch exists.\n\nPASS 1 — Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List branch-relevant background agent tasks.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_TURN_PREFIX = `[USER]\n[INTERNAL TURN-PREFIX SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a compact prefix summary for the next turn. Emit only the sections listed below.\n\nPASS 1 — Internal task-intent extraction\nSilently determine the current task intent and the minimum context needed for the next turn.\n\nPASS 2 — Emit summary biased toward Pass 1\nThe structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Quote the active user request and any steering constraints exactly as stated.\n\n## 2. Final Goal\n- State the immediate end state needed for the next turn.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 5. Active Working Context\n- Include only files, identifiers, runtime state, and exact next-turn context needed to continue immediately.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport function buildPrompt(options: BuildMergedCompactionPromptOptions): { system: string; user: string } {\n\tconst user = buildUserPrompt(options);\n\n\treturn {\n\t\tsystem: MERGED_COMPACTION_PROMPT_SYSTEM,\n\t\tuser: appendCustomInstructions(user, options.customInstructions),\n\t};\n}\n\nfunction buildUserPrompt(options: BuildMergedCompactionPromptOptions): string {\n\tswitch (options.variant) {\n\t\tcase \"default\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_USER;\n\t\tcase \"update\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_UPDATE.replace(\n\t\t\t\t\"{{previousSummary}}\",\n\t\t\t\tsanitizePreviousSummary(options.previousSummary),\n\t\t\t);\n\t\tcase \"branch\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_BRANCH;\n\t\tcase \"turn_prefix\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_TURN_PREFIX;\n\t}\n\n\tconst exhaustiveCheck: never = options.variant;\n\treturn exhaustiveCheck;\n}\n\nfunction appendCustomInstructions(userPrompt: string, customInstructions: string | undefined): string {\n\tconst trimmedInstructions = customInstructions?.trim();\n\tif (!trimmedInstructions) {\n\t\treturn userPrompt;\n\t}\n\n\treturn `${userPrompt}\n\n<custom-instructions>\n${sanitizeCustomInstructions(trimmedInstructions)}\n</custom-instructions>`;\n}\n\nfunction sanitizePreviousSummary(previousSummary: string | undefined): string {\n\tconst trimmedSummary = previousSummary?.trim();\n\tif (!trimmedSummary) {\n\t\treturn \"None.\";\n\t}\n\n\treturn trimmedSummary.split(\"</previous-summary>\").join(\"[/previous-summary]\");\n}\n\nfunction sanitizeCustomInstructions(customInstructions: string): string {\n\treturn customInstructions.split(\"</custom-instructions>\").join(\"[/custom-instructions]\");\n}\n"]}
1
+ {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/prompts.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,6BAA6B,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,aAAa,CAAC;AAE5F,MAAM,MAAM,kCAAkC,GAAG;IAChD,OAAO,EAAE,6BAA6B,CAAC;IACvC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,+BAA+B,+rBAUe,CAAC;AAE5D,eAAO,MAAM,6BAA6B,g8FAoDyC,CAAC;AAEpF,eAAO,MAAM,+BAA+B,2mEAiDuC,CAAC;AAEpF,eAAO,MAAM,+BAA+B,srEA6CuC,CAAC;AAEpF,eAAO,MAAM,oCAAoC,6jCA0BkC,CAAC;AAEpF,wBAAgB,WAAW,CAAC,OAAO,EAAE,kCAAkC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAOzG","sourcesContent":["export type MergedCompactionPromptVariant = \"default\" | \"update\" | \"branch\" | \"turn_prefix\";\n\nexport type BuildMergedCompactionPromptOptions = {\n\tvariant: MergedCompactionPromptVariant;\n\tpreviousSummary?: string;\n\tcustomInstructions?: string;\n};\n\nexport const MERGED_COMPACTION_PROMPT_SYSTEM = `[SYSTEM DIRECTIVE: OH-MY-OPENCODE - COMPACTION CONTEXT]\n\nYou are the COMPACTION ARCHIVIST. Create a structured handoff summary that lets the next agent continue this exact session without restarting, re-searching, or losing constraints.\n\nCardinal rules:\nR1. Quote user requests and constraints VERBATIM. Do not paraphrase.\nR2. If a section has no content, write \"None.\" Never delete a section.\nR3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\nR4. Preserve every session_id, file path, and identifier byte-for-byte.\n\nDo NOT use tools. Output only the requested summary block.`;\n\nexport const MERGED_COMPACTION_PROMPT_USER = `[USER]\n[INTERNAL COMPACTION INSTRUCTION — NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_UPDATE = `[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION — NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 — Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_BRANCH = `[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient §2 toward the branched intent and why this branch exists.\n\nPASS 1 — Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_TURN_PREFIX = `[USER]\n[INTERNAL TURN-PREFIX SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a compact prefix summary for the next turn. Emit only the sections listed below.\n\nPASS 1 — Internal task-intent extraction\nSilently determine the current task intent and the minimum context needed for the next turn.\n\nPASS 2 — Emit summary biased toward Pass 1\nThe structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Quote the active user request and any steering constraints exactly as stated.\n\n## 2. Final Goal\n- State the immediate end state needed for the next turn.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 5. Active Working Context\n- Include only files, identifiers, runtime state, and exact next-turn context needed to continue immediately.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport function buildPrompt(options: BuildMergedCompactionPromptOptions): { system: string; user: string } {\n\tconst user = buildUserPrompt(options);\n\n\treturn {\n\t\tsystem: MERGED_COMPACTION_PROMPT_SYSTEM,\n\t\tuser: appendCustomInstructions(user, options.customInstructions),\n\t};\n}\n\nfunction buildUserPrompt(options: BuildMergedCompactionPromptOptions): string {\n\tswitch (options.variant) {\n\t\tcase \"default\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_USER;\n\t\tcase \"update\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_UPDATE.replace(\n\t\t\t\t\"{{previousSummary}}\",\n\t\t\t\tsanitizePreviousSummary(options.previousSummary),\n\t\t\t);\n\t\tcase \"branch\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_BRANCH;\n\t\tcase \"turn_prefix\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_TURN_PREFIX;\n\t}\n\n\tconst exhaustiveCheck: never = options.variant;\n\treturn exhaustiveCheck;\n}\n\nfunction appendCustomInstructions(userPrompt: string, customInstructions: string | undefined): string {\n\tconst trimmedInstructions = customInstructions?.trim();\n\tif (!trimmedInstructions) {\n\t\treturn userPrompt;\n\t}\n\n\treturn `${userPrompt}\n\n<custom-instructions>\n${sanitizeCustomInstructions(trimmedInstructions)}\n</custom-instructions>`;\n}\n\nfunction sanitizePreviousSummary(previousSummary: string | undefined): string {\n\tconst trimmedSummary = previousSummary?.trim();\n\tif (!trimmedSummary) {\n\t\treturn \"None.\";\n\t}\n\n\treturn trimmedSummary.split(\"</previous-summary>\").join(\"[/previous-summary]\");\n}\n\nfunction sanitizeCustomInstructions(customInstructions: string): string {\n\treturn customInstructions.split(\"</custom-instructions>\").join(\"[/custom-instructions]\");\n}\n"]}
@@ -58,18 +58,6 @@ Create a structured handoff summary of this conversation for seamless continuati
58
58
  - Include verbatim quotes from the conversation showing exactly where work was left off when helpful.
59
59
  - Do not suggest tangential tasks.
60
60
 
61
- ## 8. Delegated Agent Sessions
62
- - List ALL background agent tasks spawned during this session.
63
- - For each: agent name, category, status, description, and session_id.
64
- - RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.
65
- - Each listed session retains full context. After compaction, use session_id to continue existing agent sessions instead of spawning new ones.
66
-
67
- ## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)
68
- - **Current Agent**: What agent is running.
69
- - **Verification Progress**: Files already verified or validated.
70
- - **Pending Verifications**: Files still needing verification.
71
- - **Previous Rejections**: If reviewer agent, what was rejected and why.
72
- - **Acceptance Status**: Current state of review process.
73
61
  </summary>
74
62
 
75
63
  Verification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.
@@ -121,12 +109,6 @@ Update the structured handoff summary. The structured output portion MUST be wra
121
109
  - Update based on current state and the user's most recent request.
122
110
  - Keep this direct and immediately actionable.
123
111
 
124
- ## 8. Delegated Agent Sessions
125
- - Preserve every existing agent name, status, description, and session_id byte-for-byte unless updated by new messages.
126
- - RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.
127
-
128
- ## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)
129
- - Preserve reviewer context and update verification progress, pending verifications, previous rejections, and acceptance status.
130
112
  </summary>
131
113
 
132
114
  IMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;
@@ -173,10 +155,6 @@ Create a structured branch handoff summary. The structured output portion MUST b
173
155
  - State the precise next action for returning to this branch.
174
156
  - Do not suggest tangential tasks.
175
157
 
176
- ## 8. Delegated Agent Sessions
177
- - List branch-relevant background agent tasks.
178
- - For each: agent name, category, status, description, and session_id.
179
- - RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.
180
158
  </summary>
181
159
 
182
160
  IMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;
@@ -1 +1 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;IAC/C,OAAO,eAAe,CAAC;AAAA,CACvB;AAED,SAAS,wBAAwB,CAAC,UAAkB,EAAE,kBAAsC,EAAU;IACrG,MAAM,mBAAmB,GAAG,kBAAkB,EAAE,IAAI,EAAE,CAAC;IACvD,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,OAAO,GAAG,UAAU;;;EAGnB,0BAA0B,CAAC,mBAAmB,CAAC;uBAC1B,CAAC;AAAA,CACvB;AAED,SAAS,uBAAuB,CAAC,eAAmC,EAAU;IAC7E,MAAM,cAAc,GAAG,eAAe,EAAE,IAAI,EAAE,CAAC;IAC/C,IAAI,CAAC,cAAc,EAAE,CAAC;QACrB,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,OAAO,cAAc,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;AAAA,CAC/E;AAED,SAAS,0BAA0B,CAAC,kBAA0B,EAAU;IACvE,OAAO,kBAAkB,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;AAAA,CACzF","sourcesContent":["export type MergedCompactionPromptVariant = \"default\" | \"update\" | \"branch\" | \"turn_prefix\";\n\nexport type BuildMergedCompactionPromptOptions = {\n\tvariant: MergedCompactionPromptVariant;\n\tpreviousSummary?: string;\n\tcustomInstructions?: string;\n};\n\nexport const MERGED_COMPACTION_PROMPT_SYSTEM = `[SYSTEM DIRECTIVE: OH-MY-OPENCODE - COMPACTION CONTEXT]\n\nYou are the COMPACTION ARCHIVIST. Create a structured handoff summary that lets the next agent continue this exact session without restarting, re-searching, or losing constraints.\n\nCardinal rules:\nR1. Quote user requests and constraints VERBATIM. Do not paraphrase.\nR2. If a section has no content, write \"None.\" Never delete a section.\nR3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\nR4. Preserve every session_id, file path, and identifier byte-for-byte.\n\nDo NOT use tools. Output only the requested summary block.`;\n\nexport const MERGED_COMPACTION_PROMPT_USER = `[USER]\n[INTERNAL COMPACTION INSTRUCTION — NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List ALL background agent tasks spawned during this session.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n- Each listed session retains full context. After compaction, use session_id to continue existing agent sessions instead of spawning new ones.\n\n## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)\n- **Current Agent**: What agent is running.\n- **Verification Progress**: Files already verified or validated.\n- **Pending Verifications**: Files still needing verification.\n- **Previous Rejections**: If reviewer agent, what was rejected and why.\n- **Acceptance Status**: Current state of review process.\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_UPDATE = `[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION — NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 — Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n## 8. Delegated Agent Sessions\n- Preserve every existing agent name, status, description, and session_id byte-for-byte unless updated by new messages.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n\n## 9. Agent Verification State (CONDITIONAL — emit only for reviewer agents)\n- Preserve reviewer context and update verification progress, pending verifications, previous rejections, and acceptance status.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_BRANCH = `[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient §2 toward the branched intent and why this branch exists.\n\nPASS 1 — Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n## 8. Delegated Agent Sessions\n- List branch-relevant background agent tasks.\n- For each: agent name, category, status, description, and session_id.\n- RESUME, DON'T RESTART — session_ids must be preserved byte-for-byte.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_TURN_PREFIX = `[USER]\n[INTERNAL TURN-PREFIX SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a compact prefix summary for the next turn. Emit only the sections listed below.\n\nPASS 1 — Internal task-intent extraction\nSilently determine the current task intent and the minimum context needed for the next turn.\n\nPASS 2 — Emit summary biased toward Pass 1\nThe structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Quote the active user request and any steering constraints exactly as stated.\n\n## 2. Final Goal\n- State the immediate end state needed for the next turn.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 5. Active Working Context\n- Include only files, identifiers, runtime state, and exact next-turn context needed to continue immediately.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport function buildPrompt(options: BuildMergedCompactionPromptOptions): { system: string; user: string } {\n\tconst user = buildUserPrompt(options);\n\n\treturn {\n\t\tsystem: MERGED_COMPACTION_PROMPT_SYSTEM,\n\t\tuser: appendCustomInstructions(user, options.customInstructions),\n\t};\n}\n\nfunction buildUserPrompt(options: BuildMergedCompactionPromptOptions): string {\n\tswitch (options.variant) {\n\t\tcase \"default\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_USER;\n\t\tcase \"update\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_UPDATE.replace(\n\t\t\t\t\"{{previousSummary}}\",\n\t\t\t\tsanitizePreviousSummary(options.previousSummary),\n\t\t\t);\n\t\tcase \"branch\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_BRANCH;\n\t\tcase \"turn_prefix\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_TURN_PREFIX;\n\t}\n\n\tconst exhaustiveCheck: never = options.variant;\n\treturn exhaustiveCheck;\n}\n\nfunction appendCustomInstructions(userPrompt: string, customInstructions: string | undefined): string {\n\tconst trimmedInstructions = customInstructions?.trim();\n\tif (!trimmedInstructions) {\n\t\treturn userPrompt;\n\t}\n\n\treturn `${userPrompt}\n\n<custom-instructions>\n${sanitizeCustomInstructions(trimmedInstructions)}\n</custom-instructions>`;\n}\n\nfunction sanitizePreviousSummary(previousSummary: string | undefined): string {\n\tconst trimmedSummary = previousSummary?.trim();\n\tif (!trimmedSummary) {\n\t\treturn \"None.\";\n\t}\n\n\treturn trimmedSummary.split(\"</previous-summary>\").join(\"[/previous-summary]\");\n}\n\nfunction sanitizeCustomInstructions(customInstructions: string): string {\n\treturn customInstructions.split(\"</custom-instructions>\").join(\"[/custom-instructions]\");\n}\n"]}
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/prompts.ts"],"names":[],"mappings":"AAQA,MAAM,CAAC,MAAM,+BAA+B,GAAG;;;;;;;;;;2DAUY,CAAC;AAE5D,MAAM,CAAC,MAAM,6BAA6B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mFAoDsC,CAAC;AAEpF,MAAM,CAAC,MAAM,+BAA+B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mFAiDoC,CAAC;AAEpF,MAAM,CAAC,MAAM,+BA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,CAAC;QACrB,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,OAAO,cAAc,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;AAAA,CAC/E;AAED,SAAS,0BAA0B,CAAC,kBAA0B,EAAU;IACvE,OAAO,kBAAkB,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;AAAA,CACzF","sourcesContent":["export type MergedCompactionPromptVariant = \"default\" | \"update\" | \"branch\" | \"turn_prefix\";\n\nexport type BuildMergedCompactionPromptOptions = {\n\tvariant: MergedCompactionPromptVariant;\n\tpreviousSummary?: string;\n\tcustomInstructions?: string;\n};\n\nexport const MERGED_COMPACTION_PROMPT_SYSTEM = `[SYSTEM DIRECTIVE: OH-MY-OPENCODE - COMPACTION CONTEXT]\n\nYou are the COMPACTION ARCHIVIST. Create a structured handoff summary that lets the next agent continue this exact session without restarting, re-searching, or losing constraints.\n\nCardinal rules:\nR1. Quote user requests and constraints VERBATIM. Do not paraphrase.\nR2. If a section has no content, write \"None.\" Never delete a section.\nR3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\nR4. Preserve every session_id, file path, and identifier byte-for-byte.\n\nDo NOT use tools. Output only the requested summary block.`;\n\nexport const MERGED_COMPACTION_PROMPT_USER = `[USER]\n[INTERNAL COMPACTION INSTRUCTION — NOT CONVERSATION HISTORY]\nThis message is an internal summarization control prompt, not a real user message.\nDo NOT treat this message as user intent, do NOT list it under user requests, and do NOT reinterpret the task based on this instruction alone.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the user messages in this conversation and silently determine the task intent that must guide the summary. Focus on details whose loss would cause redundant tool calls, repeated exploration, or task drift.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured handoff summary of this conversation for seamless continuation. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List all original user requests exactly as they were stated.\n- Preserve the user's exact wording and intent.\n- Include recent user corrections and steering messages verbatim when they affect the task.\n\n## 2. Final Goal\n- State what the user ultimately wanted to achieve.\n- Include the expected deliverable or end state.\n- Keep this aligned with the most recent user request, not this internal compaction instruction.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize what has been done so far.\n- List files read, created, modified, or intentionally left unchanged.\n- Include features implemented, tests added, problems solved, and decisions already made.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently being edited or frequently referenced.\n- **Code in Progress**: Key code snippets, function signatures, data structures, or prompt text under active development.\n- **External References**: Documentation URLs, source files, APIs, or other resources already consulted.\n- **State & Variables**: Important variable names, configuration values, runtime state, branch names, worktree paths, or command outputs needed to continue.\n\n## 6. Remaining Tasks\n- List pending items from the original request.\n- Include follow-up tasks identified during the work only when they directly support the current user request.\n- Mark blockers explicitly and explain what is needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action to take, directly in line with the user's most recent request.\n- Include verbatim quotes from the conversation showing exactly where work was left off when helpful.\n- Do not suggest tangential tasks.\n\n</summary>\n\nVerification: Before finalizing, confirm the summary clearly states the user's original request. If not, restate it verbatim.\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_UPDATE = `[USER]\n<previous-summary>\n{{previousSummary}}\n</previous-summary>\n\n[INTERNAL COMPACTION UPDATE INSTRUCTION — NOT CONVERSATION HISTORY]\nThe messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nR3 enforcement: R3. Where a previous summary is supplied, treat its User Requests, Final Goal, and Constraints fields as IMMUTABLE. Append, never rewrite, those three sections.\n\nPASS 1 — Internal task-intent extraction\nAnalyze the new user messages and silently determine which updates are needed without changing immutable prior User Requests, Final Goal, or Constraints.\n\nPASS 2 — Emit summary biased toward Pass 1\nUpdate the structured handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Preserve prior entries from <previous-summary> byte-for-byte.\n- Append new user requests exactly as they were stated.\n\n## 2. Final Goal\n- Preserve the existing final goal unless the user explicitly changed it.\n- Append the explicit change verbatim if the goal changed.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Preserve prior constraints byte-for-byte.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- Append only new explicit constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Preserve completed work from the previous summary.\n- Add newly completed work, files changed, tests run, and decisions made.\n\n## 5. Active Working Context\n- Update files, code in progress, external references, state, variables, branch names, worktree paths, and command outputs needed to continue.\n\n## 6. Remaining Tasks\n- Remove tasks only when the new messages prove they are completed or cancelled.\n- Add newly identified direct follow-up tasks.\n\n## 7. Exact Next Steps\n- Update based on current state and the user's most recent request.\n- Keep this direct and immediately actionable.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_BRANCH = `[USER]\n[INTERNAL BRANCH SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a structured summary of this conversation branch for context when returning later. This is a branch-level handoff, so reorient §2 toward the branched intent and why this branch exists.\n\nPASS 1 — Internal task-intent extraction\nAnalyze this branch and silently determine the branch-specific intent, divergence point, and details whose loss would cause repeated work.\n\nPASS 2 — Emit summary biased toward Pass 1\nCreate a structured branch handoff summary. The structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- List user requests that caused or shaped this branch exactly as they were stated.\n- Preserve the user's exact wording and intent.\n\n## 2. Final Goal\n- State the branched intent: what this branch was trying to accomplish, test, compare, or preserve.\n- Include how this branch differs from the mainline path when known.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context.\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 4. Work Completed\n- Summarize branch-specific progress.\n- List files read, created, modified, or intentionally left unchanged on this branch.\n\n## 5. Active Working Context\n- **Files**: Paths of files currently edited or frequently referenced in this branch.\n- **Code in Progress**: Key snippets, signatures, data structures, or prompt text under active development.\n- **External References**: Sources already consulted for this branch.\n- **State & Variables**: Branch names, worktree paths, runtime state, command outputs, and identifiers needed to resume.\n\n## 6. Remaining Tasks\n- List branch-specific work still needed.\n- Include blockers and the concrete condition needed to unblock them.\n\n## 7. Exact Next Steps\n- State the precise next action for returning to this branch.\n- Do not suggest tangential tasks.\n\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport const MERGED_COMPACTION_PROMPT_TURN_PREFIX = `[USER]\n[INTERNAL TURN-PREFIX SUMMARY INSTRUCTION — NOT CONVERSATION HISTORY]\nCreate a compact prefix summary for the next turn. Emit only the sections listed below.\n\nPASS 1 — Internal task-intent extraction\nSilently determine the current task intent and the minimum context needed for the next turn.\n\nPASS 2 — Emit summary biased toward Pass 1\nThe structured output portion MUST be wrapped as \\`<summary>...</summary>\\` XML.\n\n<summary>\n## 1. User Requests (Verbatim)\n- Quote the active user request and any steering constraints exactly as stated.\n\n## 2. Final Goal\n- State the immediate end state needed for the next turn.\n\n## 3. Constraints & Preferences (Verbatim Only)\n- Quote constraints verbatim.\n- Do NOT invent, add, soften, or modify constraints.\n- If no explicit constraints exist, write \"None.\"\n\n## 5. Active Working Context\n- Include only files, identifiers, runtime state, and exact next-turn context needed to continue immediately.\n</summary>\n\nIMPORTANT: Respond with ONLY the <summary>...</summary> block as your text output.`;\n\nexport function buildPrompt(options: BuildMergedCompactionPromptOptions): { system: string; user: string } {\n\tconst user = buildUserPrompt(options);\n\n\treturn {\n\t\tsystem: MERGED_COMPACTION_PROMPT_SYSTEM,\n\t\tuser: appendCustomInstructions(user, options.customInstructions),\n\t};\n}\n\nfunction buildUserPrompt(options: BuildMergedCompactionPromptOptions): string {\n\tswitch (options.variant) {\n\t\tcase \"default\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_USER;\n\t\tcase \"update\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_UPDATE.replace(\n\t\t\t\t\"{{previousSummary}}\",\n\t\t\t\tsanitizePreviousSummary(options.previousSummary),\n\t\t\t);\n\t\tcase \"branch\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_BRANCH;\n\t\tcase \"turn_prefix\":\n\t\t\treturn MERGED_COMPACTION_PROMPT_TURN_PREFIX;\n\t}\n\n\tconst exhaustiveCheck: never = options.variant;\n\treturn exhaustiveCheck;\n}\n\nfunction appendCustomInstructions(userPrompt: string, customInstructions: string | undefined): string {\n\tconst trimmedInstructions = customInstructions?.trim();\n\tif (!trimmedInstructions) {\n\t\treturn userPrompt;\n\t}\n\n\treturn `${userPrompt}\n\n<custom-instructions>\n${sanitizeCustomInstructions(trimmedInstructions)}\n</custom-instructions>`;\n}\n\nfunction sanitizePreviousSummary(previousSummary: string | undefined): string {\n\tconst trimmedSummary = previousSummary?.trim();\n\tif (!trimmedSummary) {\n\t\treturn \"None.\";\n\t}\n\n\treturn trimmedSummary.split(\"</previous-summary>\").join(\"[/previous-summary]\");\n}\n\nfunction sanitizeCustomInstructions(customInstructions: string): string {\n\treturn customInstructions.split(\"</custom-instructions>\").join(\"[/custom-instructions]\");\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
2
+ export declare const TOOL_RESULT_PLACEHOLDER = "Tool output unavailable (context compacted)";
3
+ export declare function repairOrphanedToolResults(messages: Message[]): Message[];
4
+ //# sourceMappingURL=repair-tool-pairs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repair-tool-pairs.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/repair-tool-pairs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAe,MAAM,uBAAuB,CAAC;AAElE,eAAO,MAAM,uBAAuB,gDAAgD,CAAC;AAErF,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CA8CxE","sourcesContent":["import type { Message, TextContent } from \"@earendil-works/pi-ai\";\n\nexport const TOOL_RESULT_PLACEHOLDER = \"Tool output unavailable (context compacted)\";\n\nexport function repairOrphanedToolResults(messages: Message[]): Message[] {\n\tconst toolCallIds = new Set<string>();\n\tconst toolResultIds = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") toolCallIds.add(block.id);\n\t\t\t}\n\t\t}\n\t\tif (message.role === \"toolResult\") toolResultIds.add(message.toolCallId);\n\t}\n\n\tconst output: Message[] = [];\n\tconst dangling = new Set([...toolCallIds].filter((id) => !toolResultIds.has(id)));\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"toolResult\") {\n\t\t\tif (!toolCallIds.has(message.toolCallId)) {\n\t\t\t\toutput.push({\n\t\t\t\t\t...message,\n\t\t\t\t\tcontent: [{ type: \"text\", text: TOOL_RESULT_PLACEHOLDER }] satisfies TextContent[],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toutput.push(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\toutput.push(message);\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type !== \"toolCall\" || !dangling.has(block.id)) continue;\n\t\t\t\toutput.push({\n\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\ttoolCallId: block.id,\n\t\t\t\t\ttoolName: block.name,\n\t\t\t\t\tcontent: [{ type: \"text\", text: TOOL_RESULT_PLACEHOLDER }],\n\t\t\t\t\tisError: false,\n\t\t\t\t\ttimestamp: message.timestamp ? message.timestamp + 1 : Date.now(),\n\t\t\t\t});\n\t\t\t\tdangling.delete(block.id);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output;\n}\n"]}
@@ -0,0 +1,48 @@
1
+ export const TOOL_RESULT_PLACEHOLDER = "Tool output unavailable (context compacted)";
2
+ export function repairOrphanedToolResults(messages) {
3
+ const toolCallIds = new Set();
4
+ const toolResultIds = new Set();
5
+ for (const message of messages) {
6
+ if (message.role === "assistant") {
7
+ for (const block of message.content) {
8
+ if (block.type === "toolCall")
9
+ toolCallIds.add(block.id);
10
+ }
11
+ }
12
+ if (message.role === "toolResult")
13
+ toolResultIds.add(message.toolCallId);
14
+ }
15
+ const output = [];
16
+ const dangling = new Set([...toolCallIds].filter((id) => !toolResultIds.has(id)));
17
+ for (const message of messages) {
18
+ if (message.role === "toolResult") {
19
+ if (!toolCallIds.has(message.toolCallId)) {
20
+ output.push({
21
+ ...message,
22
+ content: [{ type: "text", text: TOOL_RESULT_PLACEHOLDER }],
23
+ });
24
+ continue;
25
+ }
26
+ output.push(message);
27
+ continue;
28
+ }
29
+ output.push(message);
30
+ if (message.role === "assistant") {
31
+ for (const block of message.content) {
32
+ if (block.type !== "toolCall" || !dangling.has(block.id))
33
+ continue;
34
+ output.push({
35
+ role: "toolResult",
36
+ toolCallId: block.id,
37
+ toolName: block.name,
38
+ content: [{ type: "text", text: TOOL_RESULT_PLACEHOLDER }],
39
+ isError: false,
40
+ timestamp: message.timestamp ? message.timestamp + 1 : Date.now(),
41
+ });
42
+ dangling.delete(block.id);
43
+ }
44
+ }
45
+ }
46
+ return output;
47
+ }
48
+ //# sourceMappingURL=repair-tool-pairs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repair-tool-pairs.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/repair-tool-pairs.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,uBAAuB,GAAG,6CAA6C,CAAC;AAErF,MAAM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B,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAClC,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;gBACrC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;oBAAE,SAAS;gBACnE,MAAM,CAAC,IAAI,CAAC;oBACX,IAAI,EAAE,YAAY;oBAClB,UAAU,EAAE,KAAK,CAAC,EAAE;oBACpB,QAAQ,EAAE,KAAK,CAAC,IAAI;oBACpB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,uBAAuB,EAAE,CAAC;oBAC1D,OAAO,EAAE,KAAK;oBACd,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;iBACjE,CAAC,CAAC;gBACH,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAC3B,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type { Message, TextContent } from \"@earendil-works/pi-ai\";\n\nexport const TOOL_RESULT_PLACEHOLDER = \"Tool output unavailable (context compacted)\";\n\nexport function repairOrphanedToolResults(messages: Message[]): Message[] {\n\tconst toolCallIds = new Set<string>();\n\tconst toolResultIds = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") toolCallIds.add(block.id);\n\t\t\t}\n\t\t}\n\t\tif (message.role === \"toolResult\") toolResultIds.add(message.toolCallId);\n\t}\n\n\tconst output: Message[] = [];\n\tconst dangling = new Set([...toolCallIds].filter((id) => !toolResultIds.has(id)));\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"toolResult\") {\n\t\t\tif (!toolCallIds.has(message.toolCallId)) {\n\t\t\t\toutput.push({\n\t\t\t\t\t...message,\n\t\t\t\t\tcontent: [{ type: \"text\", text: TOOL_RESULT_PLACEHOLDER }] satisfies TextContent[],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toutput.push(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\toutput.push(message);\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type !== \"toolCall\" || !dangling.has(block.id)) continue;\n\t\t\t\toutput.push({\n\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\ttoolCallId: block.id,\n\t\t\t\t\ttoolName: block.name,\n\t\t\t\t\tcontent: [{ type: \"text\", text: TOOL_RESULT_PLACEHOLDER }],\n\t\t\t\t\tisError: false,\n\t\t\t\t\ttimestamp: message.timestamp ? message.timestamp + 1 : Date.now(),\n\t\t\t\t});\n\t\t\t\tdangling.delete(block.id);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output;\n}\n"]}
@@ -5,6 +5,7 @@ import type { ModelRegistry } from "../../../model-registry.js";
5
5
  import type { ReadonlySessionManager } from "../../../session-manager.js";
6
6
  import type { ApplyCompactionResult, ContextUsage } from "../../types.js";
7
7
  import { type MergedCompactionPromptVariant } from "./prompts.js";
8
+ type CompactionProgressCallback = (delta: string) => void;
8
9
  export interface SpeculativeCompactionContext {
9
10
  model: Model<any> | undefined;
10
11
  sessionManager: ReadonlySessionManager;
@@ -51,8 +52,9 @@ export declare function createSpeculativeCompactionSnapshot(context: Speculative
51
52
  customInstructions?: string;
52
53
  generation: number;
53
54
  }): SpeculativeCompactionSnapshot | undefined;
54
- export declare function runExtensionCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot, signal?: AbortSignal): Promise<CompactionResult | undefined>;
55
+ export declare function runExtensionCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot, signal?: AbortSignal, onProgress?: CompactionProgressCallback): Promise<CompactionResult | undefined>;
55
56
  export declare function applyGeneratedCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot | undefined, getCurrentGeneration: () => number, compaction: CompactionResult | undefined): Promise<SpeculativeCompactionResult>;
56
57
  export declare function snapshotExtensionCompaction(context: SpeculativeCompactionContext, request: ExtensionCompactionRequest): SpeculativeCompactionSnapshot | undefined;
57
58
  export declare function applySpeculativeCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot | undefined, getCurrentGeneration: () => number, generate: () => Promise<CompactionResult | undefined>): Promise<SpeculativeCompactionResult>;
59
+ export {};
58
60
  //# sourceMappingURL=speculative.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"speculative.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAA0B,KAAK,KAAK,EAAoB,MAAM,uBAAuB,CAAC;AAC7F,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAMrB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAe,KAAK,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAS/E,MAAM,WAAW,4BAA4B;IAC5C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IAC9B,cAAc,EAAE,sBAAsB,CAAC;IACvC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,eAAe,IAAI,YAAY,GAAG,SAAS,CAAC;IAC5C,qBAAqB,CAAC,IAAI,qBAAqB,CAAC,UAAU,CAAC,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AE,4BAA4B,EACrC,OAAO,EAAE;IAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAC1D,6BAA6B,GAAG,SAAS,CAwB3C;AAED,wBAAsB,sBAAsB,CAC3C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,EACvC,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAgDvC;AAED,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,UAAU,EAAE,gBAAgB,GAAG,SAAS,GACtC,OAAO,CAAC,2BAA2B,CAAC,CAWtC;AAED,wBAAgB,2BAA2B,CAC1C,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,0BAA0B,GACjC,6BAA6B,GAAG,SAAS,CAE3C;AAED,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,QAAQ,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,GACnD,OAAO,CAAC,2BAA2B,CAAC,CAKtC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { complete, type Message, type Model, type TextContent } from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\testimateTokens,\n\tprepareCompaction,\n\tserializeConversation,\n} from \"../../../compaction/index.js\";\nimport { convertToLlm } from \"../../../messages.js\";\nimport type { ModelRegistry } from \"../../../model-registry.js\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.js\";\nimport type { ApplyCompactionResult, ContextUsage } from \"../../types.js\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.js\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.js\";\nimport * as truncation from \"./tool-truncation.js\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\nconst COMPACTION_BUDGET_RATIO = 0.6;\nconst EMERGENCY_CONTEXT_TARGET_RATIO = 0.95;\nconst MAX_SUMMARY_TOKENS = 8192;\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: { reason: \"extension\"; expectedRevision: number },\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tpromptVariant: MergedCompactionPromptVariant;\n\tcustomInstructions?: string;\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" };\n\nexport type ExtensionCompactionRequest = {\n\tcustomInstructions?: string;\n\tgeneration: number;\n\tsignal?: AbortSignal;\n};\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction getSummaryText(message: Message): string {\n\tconst content = Array.isArray(message.content)\n\t\t? message.content\n\t\t: [{ type: \"text\" as const, text: message.content }];\n\treturn content\n\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nfunction pruneToolResults(messages: AgentMessage[], contextWindow: number): AgentMessage[] {\n\tconst toolResults = messages\n\t\t.filter((message) => message.role === \"toolResult\")\n\t\t.map((message) => ({ content: message.content, details: undefined }));\n\tif (toolResults.length === 0) return messages;\n\n\tconst prunedResults = truncation.prePruneToolOutputsToBudget(toolResults, contextWindow * COMPACTION_BUDGET_RATIO);\n\tlet resultIndex = 0;\n\treturn messages.map((message) => {\n\t\tif (message.role !== \"toolResult\") return message;\n\t\tconst pruned = prunedResults[resultIndex];\n\t\tresultIndex++;\n\t\treturn pruned ? { ...message, content: pruned.content } : message;\n\t});\n}\n\nexport function truncateContextMessages(messages: AgentMessage[]): AgentMessage[] {\n\tconst toolResults = messages\n\t\t.filter((message) => message.role === \"toolResult\")\n\t\t.map((message) => ({ content: message.content, details: undefined }));\n\tif (toolResults.length === 0) return messages;\n\n\tconst truncatedResults = truncation.truncateOversizedToolResults(toolResults);\n\tlet resultIndex = 0;\n\treturn messages.map((message) => {\n\t\tif (message.role !== \"toolResult\") return message;\n\t\tconst truncated = truncatedResults[resultIndex];\n\t\tresultIndex++;\n\t\treturn truncated ? { ...message, content: truncated.content } : message;\n\t});\n}\n\nfunction getToolCallIds(message: AgentMessage): Set<string> {\n\tconst ids = new Set<string>();\n\tif (message.role !== \"assistant\") return ids;\n\tfor (const block of message.content) {\n\t\tif (block.type === \"toolCall\") ids.add(block.id);\n\t}\n\treturn ids;\n}\n\nfunction findLastUserLikeIndex(messages: AgentMessage[]): number {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst role = messages[index]?.role;\n\t\tif (role === \"user\" || role === \"bashExecution\") return index;\n\t}\n\treturn messages.length;\n}\n\nfunction removeAssistantToolPair(messages: AgentMessage[], assistantIndex: number): AgentMessage[] {\n\tconst ids = getToolCallIds(messages[assistantIndex]);\n\treturn messages.filter((message, index) => {\n\t\tif (index === assistantIndex) return false;\n\t\treturn message.role !== \"toolResult\" || !ids.has(message.toolCallId);\n\t});\n}\n\nfunction removeFirstOldToolPair(messages: AgentMessage[], boundaryIndex: number): AgentMessage[] | undefined {\n\tfor (let index = 0; index < boundaryIndex; index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tif (message.role === \"assistant\" && getToolCallIds(message).size > 0)\n\t\t\treturn removeAssistantToolPair(messages, index);\n\t\tif (message.role === \"toolResult\") return messages.filter((_message, candidateIndex) => candidateIndex !== index);\n\t}\n\treturn undefined;\n}\n\nfunction removeFirstOldMessage(messages: AgentMessage[], boundaryIndex: number): AgentMessage[] | undefined {\n\tfor (let index = 0; index < boundaryIndex; index++) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role === \"toolResult\") continue;\n\t\tif (message.role === \"assistant\" && getToolCallIds(message).size > 0)\n\t\t\treturn removeAssistantToolPair(messages, index);\n\t\treturn messages.filter((_candidate, candidateIndex) => candidateIndex !== index);\n\t}\n\treturn undefined;\n}\n\nfunction pruneOldMessagesToBudget(messages: AgentMessage[], targetTokens: number): AgentMessage[] {\n\tlet pruned = messages;\n\twhile (estimateTotalTokens(pruned) > targetTokens) {\n\t\tconst boundaryIndex = findLastUserLikeIndex(pruned);\n\t\tconst next = removeFirstOldToolPair(pruned, boundaryIndex) ?? removeFirstOldMessage(pruned, boundaryIndex);\n\t\tif (!next || next.length === pruned.length) break;\n\t\tpruned = next;\n\t}\n\treturn pruned;\n}\n\nfunction estimateTotalTokens(messages: AgentMessage[]): number {\n\tlet total = 0;\n\tfor (const message of messages) total += estimateTokens(message);\n\treturn total;\n}\n\nexport function hardLimitEmergencyPrune(\n\tmessages: AgentMessage[],\n\tcontextWindow: number,\n): {\n\tmessages: AgentMessage[];\n\tneedsAggressiveCompaction: boolean;\n} {\n\tconst targetTokens = Math.floor(contextWindow * EMERGENCY_CONTEXT_TARGET_RATIO);\n\tconst noLlmPruned = truncateContextMessages(pruneToolResults(messages, contextWindow));\n\tif (estimateTotalTokens(noLlmPruned) <= targetTokens) {\n\t\treturn { messages: noLlmPruned, needsAggressiveCompaction: false };\n\t}\n\treturn {\n\t\tmessages: pruneOldMessagesToBudget(noLlmPruned, targetTokens),\n\t\tneedsAggressiveCompaction: true,\n\t};\n}\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: { customInstructions?: string; generation: number },\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\tgeneration: options.generation,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tcustomInstructions: options.customInstructions,\n\t};\n}\n\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n): Promise<CompactionResult | undefined> {\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (!auth?.ok || !auth.apiKey) return undefined;\n\n\tconst messages = pruneToolResults(\n\t\t[...snapshot.preparation.messagesToSummarize, ...snapshot.preparation.turnPrefixMessages],\n\t\tsnapshot.contextWindow,\n\t);\n\tconst prompt = buildPrompt({\n\t\tvariant: snapshot.promptVariant,\n\t\tpreviousSummary: snapshot.preparation.previousSummary,\n\t\tcustomInstructions: snapshot.customInstructions,\n\t});\n\tconst conversationText = serializeConversation(convertToLlm(messages));\n\tconst response = await complete(\n\t\tsnapshot.model,\n\t\t{\n\t\t\tsystemPrompt: prompt.system,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: `${prompt.user}\\n\\n<conversation>\\n${conversationText}\\n</conversation>` },\n\t\t\t\t\t],\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tapiKey: auth.apiKey,\n\t\t\theaders: auth.headers,\n\t\t\textraBody: auth.extraBody,\n\t\t\tmaxTokens: MAX_SUMMARY_TOKENS,\n\t\t\tsignal,\n\t\t},\n\t);\n\tconst summary = getSummaryText(response);\n\tif (!summary) return undefined;\n\n\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\tif (tokenEstimate > snapshot.contextWindow * COMPACTION_BUDGET_RATIO) return undefined;\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\tdetails: { schema: SUMMARY_SCHEMA, promptVariant: snapshot.promptVariant, tokenEstimate },\n\t};\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration() || snapshot.expectedRevision !== context.getMessageRevision()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\texpectedRevision: snapshot.expectedRevision,\n\t});\n}\n\nexport function snapshotExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\trequest: ExtensionCompactionRequest,\n): SpeculativeCompactionSnapshot | undefined {\n\treturn createSpeculativeCompactionSnapshot(context, request);\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}
1
+ {"version":3,"file":"speculative.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAIN,KAAK,KAAK,EAGV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAMrB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAe,KAAK,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAS/E,KAAK,0BAA0B,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAE1D,MAAM,WAAW,4BAA4B;IAC5C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IAC9B,cAAc,EAAE,sBAAsB,CAAC;IACvC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,eAAe,IAAI,YAAY,GAAG,SAAS,CA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,GAAG,6BAA6B,CAKhC;AAED,wBAAgB,mCAAmC,CAClD,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE;IAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAC1D,6BAA6B,GAAG,SAAS,CAwB3C;AAED,wBAAsB,sBAAsB,CAC3C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,EACvC,MAAM,CAAC,EAAE,WAAW,EACpB,UAAU,CAAC,EAAE,0BAA0B,GACrC,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAwDvC;AAED,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,UAAU,EAAE,gBAAgB,GAAG,SAAS,GACtC,OAAO,CAAC,2BAA2B,CAAC,CAWtC;AAED,wBAAgB,2BAA2B,CAC1C,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,0BAA0B,GACjC,6BAA6B,GAAG,SAAS,CAE3C;AAED,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,4BAA4B,EACrC,QAAQ,EAAE,6BAA6B,GAAG,SAAS,EACnD,oBAAoB,EAAE,MAAM,MAAM,EAClC,QAAQ,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,GACnD,OAAO,CAAC,2BAA2B,CAAC,CAKtC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\tisContextOverflow,\n\ttype Message,\n\ttype Model,\n\tstream,\n\ttype TextContent,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\testimateTokens,\n\tprepareCompaction,\n\tserializeConversation,\n} from \"../../../compaction/index.js\";\nimport { convertToLlm } from \"../../../messages.js\";\nimport type { ModelRegistry } from \"../../../model-registry.js\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.js\";\nimport type { ApplyCompactionResult, ContextUsage } from \"../../types.js\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.js\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.js\";\nimport * as truncation from \"./tool-truncation.js\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\nconst COMPACTION_BUDGET_RATIO = 0.6;\nconst COMPACTION_RETRY_BUDGET_RATIO = 0.4;\nconst EMERGENCY_CONTEXT_TARGET_RATIO = 0.95;\nconst MAX_SUMMARY_TOKENS = 8192;\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\ntype CompactionProgressCallback = (delta: string) => void;\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: { reason: \"extension\"; expectedRevision: number },\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tpromptVariant: MergedCompactionPromptVariant;\n\tcustomInstructions?: string;\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" };\n\nexport type ExtensionCompactionRequest = {\n\tcustomInstructions?: string;\n\tgeneration: number;\n\tsignal?: AbortSignal;\n};\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction getSummaryText(message: Message): string {\n\tconst content = Array.isArray(message.content)\n\t\t? message.content\n\t\t: [{ type: \"text\" as const, text: message.content }];\n\treturn content\n\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nfunction isAssistantMessage(message: Message): message is AssistantMessage {\n\treturn message.role === \"assistant\" && \"stopReason\" in message;\n}\n\nasync function generateSummaryMessage(options: {\n\tmessages: AgentMessage[];\n\tonProgress?: CompactionProgressCallback;\n\tprompt: ReturnType<typeof buildPrompt>;\n\tsignal?: AbortSignal;\n\tsnapshot: SpeculativeCompactionSnapshot;\n\tauth: {\n\t\tapiKey: string;\n\t\theaders?: Record<string, string>;\n\t\textraBody?: Record<string, unknown>;\n\t};\n}): Promise<Message | undefined> {\n\tconst conversationText = serializeConversation(convertToLlm(options.messages));\n\tconst responseStream = stream(\n\t\toptions.snapshot.model,\n\t\t{\n\t\t\tsystemPrompt: options.prompt.system,\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `${options.prompt.user}\\n\\n<conversation>\\n${conversationText}\\n</conversation>`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tapiKey: options.auth.apiKey,\n\t\t\theaders: options.auth.headers,\n\t\t\textraBody: options.auth.extraBody,\n\t\t\tmaxTokens: MAX_SUMMARY_TOKENS,\n\t\t\tsignal: options.signal,\n\t\t},\n\t);\n\tfor await (const event of responseStream) {\n\t\tif (event.type === \"text_delta\" && event.delta) {\n\t\t\toptions.onProgress?.(event.delta);\n\t\t}\n\t}\n\treturn await responseStream.result();\n}\n\nfunction pruneToolResults(messages: AgentMessage[], contextWindow: number): AgentMessage[] {\n\tconst toolResults = messages\n\t\t.filter((message) => message.role === \"toolResult\")\n\t\t.map((message) => ({ content: message.content, details: undefined }));\n\tif (toolResults.length === 0) return messages;\n\n\tconst prunedResults = truncation.prePruneToolOutputsToBudget(toolResults, contextWindow * COMPACTION_BUDGET_RATIO);\n\tlet resultIndex = 0;\n\treturn messages.map((message) => {\n\t\tif (message.role !== \"toolResult\") return message;\n\t\tconst pruned = prunedResults[resultIndex];\n\t\tresultIndex++;\n\t\treturn pruned ? { ...message, content: pruned.content } : message;\n\t});\n}\n\nexport function truncateContextMessages(messages: AgentMessage[]): AgentMessage[] {\n\tconst toolResults = messages\n\t\t.filter((message) => message.role === \"toolResult\")\n\t\t.map((message) => ({ content: message.content, details: undefined }));\n\tif (toolResults.length === 0) return messages;\n\n\tconst truncatedResults = truncation.truncateOversizedToolResults(toolResults);\n\tlet resultIndex = 0;\n\treturn messages.map((message) => {\n\t\tif (message.role !== \"toolResult\") return message;\n\t\tconst truncated = truncatedResults[resultIndex];\n\t\tresultIndex++;\n\t\treturn truncated ? { ...message, content: truncated.content } : message;\n\t});\n}\n\nfunction getToolCallIds(message: AgentMessage): Set<string> {\n\tconst ids = new Set<string>();\n\tif (message.role !== \"assistant\") return ids;\n\tfor (const block of message.content) {\n\t\tif (block.type === \"toolCall\") ids.add(block.id);\n\t}\n\treturn ids;\n}\n\nfunction findLastUserLikeIndex(messages: AgentMessage[]): number {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst role = messages[index]?.role;\n\t\tif (role === \"user\" || role === \"bashExecution\") return index;\n\t}\n\treturn messages.length;\n}\n\nfunction removeAssistantToolPair(messages: AgentMessage[], assistantIndex: number): AgentMessage[] {\n\tconst ids = getToolCallIds(messages[assistantIndex]);\n\treturn messages.filter((message, index) => {\n\t\tif (index === assistantIndex) return false;\n\t\treturn message.role !== \"toolResult\" || !ids.has(message.toolCallId);\n\t});\n}\n\nfunction removeFirstOldToolPair(messages: AgentMessage[], boundaryIndex: number): AgentMessage[] | undefined {\n\tfor (let index = 0; index < boundaryIndex; index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tif (message.role === \"assistant\" && getToolCallIds(message).size > 0)\n\t\t\treturn removeAssistantToolPair(messages, index);\n\t\tif (message.role === \"toolResult\") return messages.filter((_message, candidateIndex) => candidateIndex !== index);\n\t}\n\treturn undefined;\n}\n\nfunction removeFirstOldMessage(messages: AgentMessage[], boundaryIndex: number): AgentMessage[] | undefined {\n\tfor (let index = 0; index < boundaryIndex; index++) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role === \"toolResult\") continue;\n\t\tif (message.role === \"assistant\" && getToolCallIds(message).size > 0)\n\t\t\treturn removeAssistantToolPair(messages, index);\n\t\treturn messages.filter((_candidate, candidateIndex) => candidateIndex !== index);\n\t}\n\treturn undefined;\n}\n\nfunction pruneOldMessagesToBudget(messages: AgentMessage[], targetTokens: number): AgentMessage[] {\n\tlet pruned = messages;\n\twhile (estimateTotalTokens(pruned) > targetTokens) {\n\t\tconst boundaryIndex = findLastUserLikeIndex(pruned);\n\t\tconst next = removeFirstOldToolPair(pruned, boundaryIndex) ?? removeFirstOldMessage(pruned, boundaryIndex);\n\t\tif (!next || next.length === pruned.length) break;\n\t\tpruned = next;\n\t}\n\treturn pruned;\n}\n\nfunction pruneMessagesForOverflowRetry(messages: AgentMessage[], targetTokens: number): AgentMessage[] | undefined {\n\tconst budgetPruned = pruneOldMessagesToBudget(messages, targetTokens);\n\tif (budgetPruned.length < messages.length) return budgetPruned;\n\tconst boundaryIndex = findLastUserLikeIndex(messages);\n\treturn (\n\t\tremoveFirstOldToolPair(messages, boundaryIndex) ??\n\t\tremoveFirstOldMessage(messages, boundaryIndex) ??\n\t\t(messages.length > 1 ? messages.slice(1) : undefined)\n\t);\n}\n\nfunction estimateTotalTokens(messages: AgentMessage[]): number {\n\tlet total = 0;\n\tfor (const message of messages) total += estimateTokens(message);\n\treturn total;\n}\n\nexport function hardLimitEmergencyPrune(\n\tmessages: AgentMessage[],\n\tcontextWindow: number,\n): {\n\tmessages: AgentMessage[];\n\tneedsAggressiveCompaction: boolean;\n} {\n\tconst targetTokens = Math.floor(contextWindow * EMERGENCY_CONTEXT_TARGET_RATIO);\n\tconst noLlmPruned = truncateContextMessages(pruneToolResults(messages, contextWindow));\n\tif (estimateTotalTokens(noLlmPruned) <= targetTokens) {\n\t\treturn { messages: noLlmPruned, needsAggressiveCompaction: false };\n\t}\n\treturn {\n\t\tmessages: pruneOldMessagesToBudget(noLlmPruned, targetTokens),\n\t\tneedsAggressiveCompaction: true,\n\t};\n}\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: { customInstructions?: string; generation: number },\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\tgeneration: options.generation,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tcustomInstructions: options.customInstructions,\n\t};\n}\n\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n\tonProgress?: CompactionProgressCallback,\n): Promise<CompactionResult | undefined> {\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (!auth?.ok || !auth.apiKey) return undefined;\n\n\tlet messages = pruneToolResults(\n\t\t[...snapshot.preparation.messagesToSummarize, ...snapshot.preparation.turnPrefixMessages],\n\t\tsnapshot.contextWindow,\n\t);\n\tconst prompt = buildPrompt({\n\t\tvariant: snapshot.promptVariant,\n\t\tpreviousSummary: snapshot.preparation.previousSummary,\n\t\tcustomInstructions: snapshot.customInstructions,\n\t});\n\n\tfor (let attempt = 0; attempt < 2; attempt++) {\n\t\tconst response = await generateSummaryMessage({\n\t\t\tmessages,\n\t\t\tonProgress,\n\t\t\tprompt,\n\t\t\tsignal,\n\t\t\tsnapshot,\n\t\t\tauth: {\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\theaders: auth.headers,\n\t\t\t\textraBody: auth.extraBody,\n\t\t\t},\n\t\t});\n\t\tif (!response) return undefined;\n\n\t\tif (isAssistantMessage(response) && isContextOverflow(response, snapshot.contextWindow)) {\n\t\t\tconst retryMessages = pruneMessagesForOverflowRetry(\n\t\t\t\tmessages,\n\t\t\t\tMath.floor(snapshot.contextWindow * COMPACTION_RETRY_BUDGET_RATIO),\n\t\t\t);\n\t\t\tif (!retryMessages || retryMessages.length === messages.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmessages = retryMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst summary = getSummaryText(response);\n\t\tif (!summary) return undefined;\n\n\t\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\t\tif (tokenEstimate > snapshot.contextWindow * COMPACTION_BUDGET_RATIO) return undefined;\n\n\t\treturn {\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\tdetails: { schema: SUMMARY_SCHEMA, promptVariant: snapshot.promptVariant, tokenEstimate },\n\t\t};\n\t}\n\n\tthrow new Error(\"Compaction summary request exceeded the context window after retrying with a smaller input\");\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration() || snapshot.expectedRevision !== context.getMessageRevision()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\texpectedRevision: snapshot.expectedRevision,\n\t});\n}\n\nexport function snapshotExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\trequest: ExtensionCompactionRequest,\n): SpeculativeCompactionSnapshot | undefined {\n\treturn createSpeculativeCompactionSnapshot(context, request);\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}