@bastani/atomic 0.10.1-alpha.1 → 0.10.2-alpha.1

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 (295) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/watchdog.ts +4 -0
  4. package/dist/builtin/intercom/package.json +1 -1
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/CHANGELOG.md +22 -0
  7. package/dist/builtin/subagents/README.md +2 -0
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/subagents/skills/subagent/SKILL.md +3 -3
  10. package/dist/builtin/subagents/src/extension/index.bundle.mjs +269 -144
  11. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  12. package/dist/builtin/web-access/index.bundle.mjs +9 -5
  13. package/dist/builtin/web-access/package.json +1 -1
  14. package/dist/cli/list-models.d.ts.map +1 -1
  15. package/dist/cli/list-models.js +1 -14
  16. package/dist/cli/list-models.js.map +1 -1
  17. package/dist/core/agent-session-export.d.ts.map +1 -1
  18. package/dist/core/agent-session-export.js +13 -9
  19. package/dist/core/agent-session-export.js.map +1 -1
  20. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  21. package/dist/core/agent-session-message-queue.js +6 -3
  22. package/dist/core/agent-session-message-queue.js.map +1 -1
  23. package/dist/core/agent-session-methods.d.ts +3 -0
  24. package/dist/core/agent-session-methods.d.ts.map +1 -1
  25. package/dist/core/agent-session-methods.js.map +1 -1
  26. package/dist/core/agent-session-nested-tools.d.ts.map +1 -1
  27. package/dist/core/agent-session-nested-tools.js +2 -1
  28. package/dist/core/agent-session-nested-tools.js.map +1 -1
  29. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  30. package/dist/core/agent-session-prompt.js +12 -0
  31. package/dist/core/agent-session-prompt.js.map +1 -1
  32. package/dist/core/agent-session-state.d.ts +6 -0
  33. package/dist/core/agent-session-state.d.ts.map +1 -1
  34. package/dist/core/agent-session-state.js +71 -4
  35. package/dist/core/agent-session-state.js.map +1 -1
  36. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  37. package/dist/core/agent-session-tool-hooks.js +9 -1
  38. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  39. package/dist/core/agent-session-types.d.ts +2 -0
  40. package/dist/core/agent-session-types.d.ts.map +1 -1
  41. package/dist/core/agent-session-types.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +3 -0
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +7 -0
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/cache-stats.d.ts +15 -0
  47. package/dist/core/cache-stats.d.ts.map +1 -1
  48. package/dist/core/cache-stats.js +40 -2
  49. package/dist/core/cache-stats.js.map +1 -1
  50. package/dist/core/diagnostic-writer.d.ts.map +1 -1
  51. package/dist/core/diagnostic-writer.js +2 -1
  52. package/dist/core/diagnostic-writer.js.map +1 -1
  53. package/dist/core/export-html/template.js +14 -4
  54. package/dist/core/extensions/context-types.d.ts +6 -0
  55. package/dist/core/extensions/context-types.d.ts.map +1 -1
  56. package/dist/core/extensions/context-types.js.map +1 -1
  57. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  58. package/dist/core/extensions/loader-api.js +5 -2
  59. package/dist/core/extensions/loader-api.js.map +1 -1
  60. package/dist/core/queued-message-delivery.d.ts +100 -7
  61. package/dist/core/queued-message-delivery.d.ts.map +1 -1
  62. package/dist/core/queued-message-delivery.js +194 -4
  63. package/dist/core/queued-message-delivery.js.map +1 -1
  64. package/dist/core/resume-cache-checkpoint.d.ts +32 -0
  65. package/dist/core/resume-cache-checkpoint.d.ts.map +1 -0
  66. package/dist/core/resume-cache-checkpoint.js +67 -0
  67. package/dist/core/resume-cache-checkpoint.js.map +1 -0
  68. package/dist/core/sdk-types.d.ts +37 -0
  69. package/dist/core/sdk-types.d.ts.map +1 -1
  70. package/dist/core/sdk-types.js.map +1 -1
  71. package/dist/core/sdk.d.ts.map +1 -1
  72. package/dist/core/sdk.js +57 -28
  73. package/dist/core/sdk.js.map +1 -1
  74. package/dist/core/session-manager-core.d.ts.map +1 -1
  75. package/dist/core/session-manager-core.js +12 -3
  76. package/dist/core/session-manager-core.js.map +1 -1
  77. package/dist/core/session-manager-entries.d.ts +13 -0
  78. package/dist/core/session-manager-entries.d.ts.map +1 -1
  79. package/dist/core/session-manager-entries.js +38 -6
  80. package/dist/core/session-manager-entries.js.map +1 -1
  81. package/dist/core/settings-lock-directory.d.ts.map +1 -1
  82. package/dist/core/settings-lock-directory.js +2 -1
  83. package/dist/core/settings-lock-directory.js.map +1 -1
  84. package/dist/core/storage/node-sqlite-file-gate.d.ts +173 -0
  85. package/dist/core/storage/node-sqlite-file-gate.d.ts.map +1 -0
  86. package/dist/core/storage/node-sqlite-file-gate.js +1033 -0
  87. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -0
  88. package/dist/core/storage/node-sqlite-thread.d.ts +33 -6
  89. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
  90. package/dist/core/storage/node-sqlite-thread.js +72 -2
  91. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  92. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  93. package/dist/core/storage/node-sqlite.js +216 -15
  94. package/dist/core/storage/node-sqlite.js.map +1 -1
  95. package/dist/core/storage/session/entry-structure.d.ts.map +1 -1
  96. package/dist/core/storage/session/entry-structure.js +39 -2
  97. package/dist/core/storage/session/entry-structure.js.map +1 -1
  98. package/dist/core/storage/session/session-resume.d.ts.map +1 -1
  99. package/dist/core/storage/session/session-resume.js +1 -0
  100. package/dist/core/storage/session/session-resume.js.map +1 -1
  101. package/dist/core/storage/session/session-search-index.d.ts.map +1 -1
  102. package/dist/core/storage/session/session-search-index.js +56 -9
  103. package/dist/core/storage/session/session-search-index.js.map +1 -1
  104. package/dist/core/storage/statement-sequence.d.ts +36 -0
  105. package/dist/core/storage/statement-sequence.d.ts.map +1 -0
  106. package/dist/core/storage/statement-sequence.js +22 -0
  107. package/dist/core/storage/statement-sequence.js.map +1 -0
  108. package/dist/core/system-prompt.d.ts.map +1 -1
  109. package/dist/core/system-prompt.js +13 -4
  110. package/dist/core/system-prompt.js.map +1 -1
  111. package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -1
  112. package/dist/core/tasks/heartbeat-notice.js +2 -1
  113. package/dist/core/tasks/heartbeat-notice.js.map +1 -1
  114. package/dist/core/tool-loadout.d.ts +4 -2
  115. package/dist/core/tool-loadout.d.ts.map +1 -1
  116. package/dist/core/tool-loadout.js +27 -5
  117. package/dist/core/tool-loadout.js.map +1 -1
  118. package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
  119. package/dist/core/tools/history-regex-worker.js +2 -1
  120. package/dist/core/tools/history-regex-worker.js.map +1 -1
  121. package/dist/core/tools/powershell.d.ts +22 -22
  122. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  123. package/dist/core/tools/sqlite-selector-connection.js +7 -0
  124. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  125. package/dist/core/transformed-system-prompt.d.ts +92 -0
  126. package/dist/core/transformed-system-prompt.d.ts.map +1 -0
  127. package/dist/core/transformed-system-prompt.js +240 -0
  128. package/dist/core/transformed-system-prompt.js.map +1 -0
  129. package/dist/extensions/codemode/execute.js +1 -1
  130. package/dist/extensions/codemode/execute.js.map +1 -1
  131. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  132. package/dist/extensions/codemode/tool.js +16 -3
  133. package/dist/extensions/codemode/tool.js.map +1 -1
  134. package/dist/extensions/llama/ui.d.ts.map +1 -1
  135. package/dist/extensions/llama/ui.js +13 -8
  136. package/dist/extensions/llama/ui.js.map +1 -1
  137. package/dist/extensions/mcp/config.d.ts +2 -0
  138. package/dist/extensions/mcp/config.d.ts.map +1 -1
  139. package/dist/extensions/mcp/config.js +5 -0
  140. package/dist/extensions/mcp/config.js.map +1 -1
  141. package/dist/extensions/mcp/index.d.ts +4 -0
  142. package/dist/extensions/mcp/index.d.ts.map +1 -1
  143. package/dist/extensions/mcp/index.js +289 -64
  144. package/dist/extensions/mcp/index.js.map +1 -1
  145. package/dist/extensions/mcp/runtime.d.ts +1 -1
  146. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  147. package/dist/extensions/mcp/runtime.js +2 -2
  148. package/dist/extensions/mcp/runtime.js.map +1 -1
  149. package/dist/extensions/mcp/tool-records.d.ts +58 -0
  150. package/dist/extensions/mcp/tool-records.d.ts.map +1 -0
  151. package/dist/extensions/mcp/tool-records.js +129 -0
  152. package/dist/extensions/mcp/tool-records.js.map +1 -0
  153. package/dist/index.d.ts +1 -0
  154. package/dist/index.d.ts.map +1 -1
  155. package/dist/index.js +1 -0
  156. package/dist/index.js.map +1 -1
  157. package/dist/modes/interactive/components/agent-panel.d.ts +2 -4
  158. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/agent-panel.js +65 -80
  160. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  161. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  162. package/dist/modes/interactive/components/compaction-boundary-message.js +3 -3
  163. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  164. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  165. package/dist/modes/interactive/components/footer.js +35 -28
  166. package/dist/modes/interactive/components/footer.js.map +1 -1
  167. package/dist/modes/interactive/components/notice-line.d.ts +16 -0
  168. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/notice-line.js +7 -0
  170. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  171. package/dist/modes/interactive/components/prompt-slot.d.ts +1 -0
  172. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/prompt-slot.js +8 -4
  174. package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
  175. package/dist/modes/interactive/components/task-board.d.ts +0 -1
  176. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/task-board.js +6 -14
  178. package/dist/modes/interactive/components/task-board.js.map +1 -1
  179. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/task-row.js +7 -6
  181. package/dist/modes/interactive/components/task-row.js.map +1 -1
  182. package/dist/modes/interactive/components/token-segment.d.ts +2 -1
  183. package/dist/modes/interactive/components/token-segment.d.ts.map +1 -1
  184. package/dist/modes/interactive/components/token-segment.js +2 -4
  185. package/dist/modes/interactive/components/token-segment.js.map +1 -1
  186. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  187. package/dist/modes/interactive/components/tree-selector-content.js +2 -2
  188. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  189. package/dist/modes/interactive/components/working-run-meter.d.ts +0 -1
  190. package/dist/modes/interactive/components/working-run-meter.d.ts.map +1 -1
  191. package/dist/modes/interactive/components/working-run-meter.js +0 -9
  192. package/dist/modes/interactive/components/working-run-meter.js.map +1 -1
  193. package/dist/modes/interactive/extension-command-hold.d.ts +25 -0
  194. package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -0
  195. package/dist/modes/interactive/extension-command-hold.js +45 -0
  196. package/dist/modes/interactive/extension-command-hold.js.map +1 -0
  197. package/dist/modes/interactive/interactive-agent-events.js +2 -1
  198. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  199. package/dist/modes/interactive/interactive-extension-context.js +18 -10
  200. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  201. package/dist/modes/interactive/interactive-extension-custom-ui.js +3 -0
  202. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  203. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  204. package/dist/modes/interactive/interactive-input-handling.js +54 -13
  205. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  206. package/dist/modes/interactive/interactive-model-routing.d.ts +6 -0
  207. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  208. package/dist/modes/interactive/interactive-model-routing.js +15 -9
  209. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  210. package/dist/modes/interactive/interactive-prompt-turn.js +4 -0
  211. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  212. package/dist/modes/interactive/interactive-queueing.d.ts +7 -0
  213. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  214. package/dist/modes/interactive/interactive-queueing.js +47 -1
  215. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  216. package/dist/modes/interactive/interactive-session-routing.js +6 -0
  217. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  218. package/dist/modes/interactive/interactive-slash-commands.js +165 -65
  219. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  220. package/dist/modes/interactive/screen-hold.d.ts +3 -0
  221. package/dist/modes/interactive/screen-hold.d.ts.map +1 -1
  222. package/dist/modes/interactive/screen-hold.js +9 -1
  223. package/dist/modes/interactive/screen-hold.js.map +1 -1
  224. package/dist/modes/interactive-engine/engine-health.d.ts +11 -3
  225. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  226. package/dist/modes/interactive-engine/engine-health.js +5 -4
  227. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  228. package/dist/modes/interactive-engine/engine-quit-intent.d.ts +7 -0
  229. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  230. package/dist/modes/interactive-engine/engine-quit-intent.js +19 -0
  231. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  232. package/dist/modes/interactive-engine/isolated-runtime.d.ts +18 -0
  233. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  234. package/dist/modes/interactive-engine/isolated-runtime.js +56 -4
  235. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  236. package/dist/modes/interactive-engine/protocol.d.ts +7 -0
  237. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  238. package/dist/modes/interactive-engine/protocol.js +1 -0
  239. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  240. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  241. package/dist/modes/rpc/agent-panel-bridge.js +0 -13
  242. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  243. package/dist/modes/rpc/rpc-client-process.d.ts +14 -1
  244. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  245. package/dist/modes/rpc/rpc-client-process.js +74 -10
  246. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  247. package/dist/modes/rpc/rpc-client.d.ts +27 -1
  248. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  249. package/dist/modes/rpc/rpc-client.js +81 -5
  250. package/dist/modes/rpc/rpc-client.js.map +1 -1
  251. package/dist/modes/rpc/rpc-event-buffer.d.ts +2 -0
  252. package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
  253. package/dist/modes/rpc/rpc-event-buffer.js +9 -0
  254. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  255. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  256. package/dist/modes/rpc/rpc-mode.js +16 -3
  257. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  258. package/dist/modes/rpc/rpc-session-binding.d.ts +7 -1
  259. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  260. package/dist/modes/rpc/rpc-session-binding.js +10 -2
  261. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  262. package/dist/utils/image-resize.d.ts.map +1 -1
  263. package/dist/utils/image-resize.js +2 -1
  264. package/dist/utils/image-resize.js.map +1 -1
  265. package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
  266. package/dist/utils/interactive-engine-bootstrap.d.ts.map +1 -1
  267. package/dist/utils/interactive-engine-bootstrap.js +1 -0
  268. package/dist/utils/interactive-engine-bootstrap.js.map +1 -1
  269. package/dist/utils/interactive-engine-env.d.ts +2 -0
  270. package/dist/utils/interactive-engine-env.d.ts.map +1 -1
  271. package/dist/utils/interactive-engine-env.js +1 -0
  272. package/dist/utils/interactive-engine-env.js.map +1 -1
  273. package/dist/utils/shell.d.ts.map +1 -1
  274. package/dist/utils/shell.js +2 -0
  275. package/dist/utils/shell.js.map +1 -1
  276. package/dist/utils/token-count.d.ts +8 -0
  277. package/dist/utils/token-count.d.ts.map +1 -0
  278. package/dist/utils/token-count.js +25 -0
  279. package/dist/utils/token-count.js.map +1 -0
  280. package/dist/utils/worker-threads.d.ts +18 -0
  281. package/dist/utils/worker-threads.d.ts.map +1 -0
  282. package/dist/utils/worker-threads.js +28 -0
  283. package/dist/utils/worker-threads.js.map +1 -0
  284. package/docs/background-tasks.md +13 -12
  285. package/docs/compaction.md +2 -2
  286. package/docs/development.md +1 -1
  287. package/docs/extensions/api-reference.md +5 -3
  288. package/docs/extensions/events.md +2 -0
  289. package/docs/mcp-servers.md +1 -1
  290. package/docs/settings.md +2 -0
  291. package/docs/storage.md +3 -1
  292. package/docs/subagents.md +6 -2
  293. package/docs/usage.md +1 -1
  294. package/npm-shrinkwrap.json +49 -49
  295. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-selector-connection.d.ts","sourceRoot":"","sources":["../../../src/core/tools/sqlite-selector-connection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErE,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AACnE,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AAuGpE,qBAAa,wBAAwB;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8B;IACtD,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,KAAK,CAAoB;IACjC,OAAO,CAAC,OAAO,CAA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ACtD,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,KAAK,CAAoB;IACjC,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC,OAAO,eAWN;IAED,OAAa,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAkBhH;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,SAAS,mBAAmB,EAAO,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAE1F;IAED,6GAA6G;IAC7G,WAAW,CAAC,CAAC,SAAS,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAE1F;IAED,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAE7D;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,SAAS,mBAAmB,EAAO,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAE1F;IAED,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CASrB;IAED,OAAO,CAAC,OAAO;IASf,OAAO,CAAC,GAAG;CAKX"}
@@ -1,4 +1,6 @@
1
+ import { isBuiltin } from "node:module";
1
2
  import { Worker } from "node:worker_threads";
3
+ import { evalWorkerExecArgv } from "../../utils/worker-threads.js";
2
4
  const MISSING_NODE_SQLITE = "SQLite selectors need node:sqlite (Node >= 22.13 or Bun >= 1.4.2); this runtime does not provide it.";
3
5
  const CONNECTION_SOURCE = `
4
6
  const { parentPort, workerData } = require("node:worker_threads");
@@ -93,8 +95,13 @@ export class SqliteSelectorConnection {
93
95
  worker.on("exit", (code) => this.end(new Error(`SQLite selector worker exited with code ${code}`)));
94
96
  }
95
97
  static async open(path, options = {}) {
98
+ // Asked on this thread, without loading the module: the worker starts without the process's flags, so a
99
+ // `--no-experimental-sqlite` given to the process would not reach it.
100
+ if (!isBuiltin("node:sqlite"))
101
+ throw new Error(MISSING_NODE_SQLITE);
96
102
  const worker = new Worker(CONNECTION_SOURCE, {
97
103
  eval: true,
104
+ execArgv: evalWorkerExecArgv(),
98
105
  workerData: { path, readonly: options.readonly === true },
99
106
  });
100
107
  const connection = new SqliteSelectorConnection(worker);
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-selector-connection.js","sourceRoot":"","sources":["../../../src/core/tools/sqlite-selector-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAM7C,MAAM,mBAAmB,GACxB,sGAAsG,CAAC;AAExG,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDzB,CAAC;AA2BF,SAAS,OAAO,CAAC,OAA0B;IAC1C,IAAI,OAAO,CAAC,aAAa;QAAE,OAAO,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACjE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC1B,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;QAC3B,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;QAC7D,GAAG,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC;Q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AAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACJ,CAAC;IAEO,GAAG,CAAC,KAAY;QACvB,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { SqliteRow, SqliteValue } from \"../storage/database.js\";\n\nexport type SqliteSelectorValue = string | number | boolean | null;\nexport type SqliteSelectorRow = Record<string, SqliteSelectorValue>;\n\nconst MISSING_NODE_SQLITE =\n\t\"SQLite selectors need node:sqlite (Node >= 22.13 or Bun >= 1.4.2); this runtime does not provide it.\";\n\nconst CONNECTION_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nlet database;\n\nfunction failure(error, missingModule) {\n\treturn {\n\t\tname: error?.name ?? \"Error\",\n\t\tmessage: String(error?.message ?? error),\n\t\tcode: error?.code,\n\t\terrcode: error?.errcode,\n\t\terrstr: error?.errstr,\n\t\tmissingModule,\n\t};\n}\n\nconst statements = {\n\tall: (request) => database.prepare(request.sql).all(...request.params),\n\trows: (request) => {\n\t\tconst rows = [];\n\t\tif (rows.length >= request.limit) return rows;\n\t\tfor (const row of database.prepare(request.sql).iterate(...request.params)) {\n\t\t\trows.push(row);\n\t\t\tif (rows.length >= request.limit) break;\n\t\t}\n\t\treturn rows;\n\t},\n\trun: (request) => ({ changes: Number(database.prepare(request.sql).run(...request.params).changes ?? 0) }),\n\tclose: () => {\n\t\tdatabase.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\nlet DatabaseSync;\ntry {\n\t({ DatabaseSync } = require(\"node:sqlite\"));\n} catch (error) {\n\tparentPort.postMessage({ id: 0, failure: failure(error, true) });\n}\nif (DatabaseSync !== undefined) {\n\ttry {\n\t\tdatabase = workerData.readonly ? new DatabaseSync(workerData.path, { readOnly: true }) : new DatabaseSync(workerData.path);\n\t\tparentPort.postMessage({ id: 0 });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: 0, failure: failure(error, false) });\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: statements[request.kind](request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error, false) });\n\t}\n});\n`;\n\ninterface ConnectionFailure {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly code?: string;\n\treadonly errcode?: number;\n\treadonly errstr?: string;\n\treadonly missingModule?: boolean;\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: unknown;\n\treadonly failure?: ConnectionFailure;\n}\n\ntype ConnectionRequest =\n\t| { readonly kind: \"all\" | \"run\"; readonly sql: string; readonly params: readonly unknown[] }\n\t| { readonly kind: \"rows\"; readonly sql: string; readonly params: readonly unknown[]; readonly limit: number }\n\t| { readonly kind: \"close\" };\n\ninterface Waiting {\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: Error) => void;\n}\n\nfunction errorOf(failure: ConnectionFailure): Error {\n\tif (failure.missingModule) return new Error(MISSING_NODE_SQLITE);\n\tconst error = new Error(failure.message);\n\terror.name = failure.name;\n\treturn Object.assign(error, {\n\t\t...(failure.code === undefined ? {} : { code: failure.code }),\n\t\t...(failure.errcode === undefined ? {} : { errcode: failure.errcode }),\n\t\t...(failure.errstr === undefined ? {} : { errstr: failure.errstr }),\n\t});\n}\n\nfunction bindValues(params: readonly SqliteSelectorValue[]): unknown[] {\n\treturn params.map((param) => (typeof param === \"boolean\" ? (param ? 1 : 0) : param));\n}\n\nexport class SqliteSelectorConnection {\n\tprivate readonly waiting = new Map<number, Waiting>();\n\tprivate nextId = 1;\n\tprivate ended: Error | undefined;\n\tprivate closing: Promise<void> | undefined;\n\tprivate readonly worker: Worker;\n\n\tprivate constructor(worker: Worker) {\n\t\tthis.worker = worker;\n\t\tworker.on(\"message\", (reply: ConnectionReply) => {\n\t\t\tconst waiting = this.waiting.get(reply.id);\n\t\t\tif (waiting === undefined) return;\n\t\t\tthis.waiting.delete(reply.id);\n\t\t\tif (reply.failure === undefined) waiting.resolve(reply.value);\n\t\t\telse waiting.reject(errorOf(reply.failure));\n\t\t});\n\t\tworker.on(\"error\", (error) => this.end(error));\n\t\tworker.on(\"exit\", (code) => this.end(new Error(`SQLite selector worker exited with code ${code}`)));\n\t}\n\n\tstatic async open(path: string, options: { readonly readonly?: boolean } = {}): Promise<SqliteSelectorConnection> {\n\t\tconst worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\tworkerData: { path, readonly: options.readonly === true },\n\t\t});\n\t\tconst connection = new SqliteSelectorConnection(worker);\n\t\tconst opened = new Promise<unknown>((resolve, reject) => connection.waiting.set(0, { resolve, reject }));\n\t\ttry {\n\t\t\tawait opened;\n\t\t} catch (error) {\n\t\t\tawait worker.terminate();\n\t\t\tthrow error;\n\t\t}\n\t\treturn connection;\n\t}\n\n\tall(sql: string, params: readonly SqliteSelectorValue[] = []): Promise<SqliteSelectorRow[]> {\n\t\treturn this.request({ kind: \"all\", sql, params: bindValues(params) }) as Promise<SqliteSelectorRow[]>;\n\t}\n\n\t/** Transcript entries can contain binary chunks; preserve their SQLite values across the worker boundary. */\n\tstorageRows<T extends SqliteRow>(sql: string, params: readonly SqliteValue[]): Promise<T[]> {\n\t\treturn this.request({ kind: \"all\", sql, params }) as Promise<T[]>;\n\t}\n\n\trows(sql: string, limit: number): Promise<SqliteSelectorRow[]> {\n\t\treturn this.request({ kind: \"rows\", sql, params: [], limit }) as Promise<SqliteSelectorRow[]>;\n\t}\n\n\trun(sql: string, params: readonly SqliteSelectorValue[] = []): Promise<{ changes: number }> {\n\t\treturn this.request({ kind: \"run\", sql, params: bindValues(params) }) as Promise<{ changes: number }>;\n\t}\n\n\tclose(): Promise<void> {\n\t\tthis.closing ??= this.request({ kind: \"close\" }).then(\n\t\t\t() => this.worker.terminate().then(() => undefined),\n\t\t\tasync (error: unknown) => {\n\t\t\t\tawait this.worker.terminate();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\treturn this.closing;\n\t}\n\n\tprivate request(request: ConnectionRequest): Promise<unknown> {\n\t\tif (this.ended !== undefined) return Promise.reject(this.ended);\n\t\tconst id = this.nextId++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tthis.worker.postMessage({ ...request, id });\n\t\t});\n\t}\n\n\tprivate end(error: Error): void {\n\t\tthis.ended ??= error;\n\t\tfor (const waiting of this.waiting.values()) waiting.reject(this.ended);\n\t\tthis.waiting.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"sqlite-selector-connection.js","sourceRoot":"","sources":["../../../src/core/tools/sqlite-selector-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAMnE,MAAM,mBAAmB,GACxB,sGAAsG,CAAC;AAExG,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDzB,CAAC;AA2BF,SAAS,OAAO,CAAC,OAA0B;IAC1C,IAAI,OAAO,CAAC,aAAa;QAAE,OAAO,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACjE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC1B,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;QAC3B,GAAG,CAAC,OAAO,CAAC,I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ACzC,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAChE,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACzB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1C,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACJ,CAAC;IAEO,GAAG,CAAC,KAAY;QACvB,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACD","sourcesContent":["import { isBuiltin } from \"node:module\";\nimport { Worker } from \"node:worker_threads\";\nimport { evalWorkerExecArgv } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteValue } from \"../storage/database.js\";\n\nexport type SqliteSelectorValue = string | number | boolean | null;\nexport type SqliteSelectorRow = Record<string, SqliteSelectorValue>;\n\nconst MISSING_NODE_SQLITE =\n\t\"SQLite selectors need node:sqlite (Node >= 22.13 or Bun >= 1.4.2); this runtime does not provide it.\";\n\nconst CONNECTION_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nlet database;\n\nfunction failure(error, missingModule) {\n\treturn {\n\t\tname: error?.name ?? \"Error\",\n\t\tmessage: String(error?.message ?? error),\n\t\tcode: error?.code,\n\t\terrcode: error?.errcode,\n\t\terrstr: error?.errstr,\n\t\tmissingModule,\n\t};\n}\n\nconst statements = {\n\tall: (request) => database.prepare(request.sql).all(...request.params),\n\trows: (request) => {\n\t\tconst rows = [];\n\t\tif (rows.length >= request.limit) return rows;\n\t\tfor (const row of database.prepare(request.sql).iterate(...request.params)) {\n\t\t\trows.push(row);\n\t\t\tif (rows.length >= request.limit) break;\n\t\t}\n\t\treturn rows;\n\t},\n\trun: (request) => ({ changes: Number(database.prepare(request.sql).run(...request.params).changes ?? 0) }),\n\tclose: () => {\n\t\tdatabase.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\nlet DatabaseSync;\ntry {\n\t({ DatabaseSync } = require(\"node:sqlite\"));\n} catch (error) {\n\tparentPort.postMessage({ id: 0, failure: failure(error, true) });\n}\nif (DatabaseSync !== undefined) {\n\ttry {\n\t\tdatabase = workerData.readonly ? new DatabaseSync(workerData.path, { readOnly: true }) : new DatabaseSync(workerData.path);\n\t\tparentPort.postMessage({ id: 0 });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: 0, failure: failure(error, false) });\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: statements[request.kind](request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error, false) });\n\t}\n});\n`;\n\ninterface ConnectionFailure {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly code?: string;\n\treadonly errcode?: number;\n\treadonly errstr?: string;\n\treadonly missingModule?: boolean;\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: unknown;\n\treadonly failure?: ConnectionFailure;\n}\n\ntype ConnectionRequest =\n\t| { readonly kind: \"all\" | \"run\"; readonly sql: string; readonly params: readonly unknown[] }\n\t| { readonly kind: \"rows\"; readonly sql: string; readonly params: readonly unknown[]; readonly limit: number }\n\t| { readonly kind: \"close\" };\n\ninterface Waiting {\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: Error) => void;\n}\n\nfunction errorOf(failure: ConnectionFailure): Error {\n\tif (failure.missingModule) return new Error(MISSING_NODE_SQLITE);\n\tconst error = new Error(failure.message);\n\terror.name = failure.name;\n\treturn Object.assign(error, {\n\t\t...(failure.code === undefined ? {} : { code: failure.code }),\n\t\t...(failure.errcode === undefined ? {} : { errcode: failure.errcode }),\n\t\t...(failure.errstr === undefined ? {} : { errstr: failure.errstr }),\n\t});\n}\n\nfunction bindValues(params: readonly SqliteSelectorValue[]): unknown[] {\n\treturn params.map((param) => (typeof param === \"boolean\" ? (param ? 1 : 0) : param));\n}\n\nexport class SqliteSelectorConnection {\n\tprivate readonly waiting = new Map<number, Waiting>();\n\tprivate nextId = 1;\n\tprivate ended: Error | undefined;\n\tprivate closing: Promise<void> | undefined;\n\tprivate readonly worker: Worker;\n\n\tprivate constructor(worker: Worker) {\n\t\tthis.worker = worker;\n\t\tworker.on(\"message\", (reply: ConnectionReply) => {\n\t\t\tconst waiting = this.waiting.get(reply.id);\n\t\t\tif (waiting === undefined) return;\n\t\t\tthis.waiting.delete(reply.id);\n\t\t\tif (reply.failure === undefined) waiting.resolve(reply.value);\n\t\t\telse waiting.reject(errorOf(reply.failure));\n\t\t});\n\t\tworker.on(\"error\", (error) => this.end(error));\n\t\tworker.on(\"exit\", (code) => this.end(new Error(`SQLite selector worker exited with code ${code}`)));\n\t}\n\n\tstatic async open(path: string, options: { readonly readonly?: boolean } = {}): Promise<SqliteSelectorConnection> {\n\t\t// Asked on this thread, without loading the module: the worker starts without the process's flags, so a\n\t\t// `--no-experimental-sqlite` given to the process would not reach it.\n\t\tif (!isBuiltin(\"node:sqlite\")) throw new Error(MISSING_NODE_SQLITE);\n\t\tconst worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: evalWorkerExecArgv(),\n\t\t\tworkerData: { path, readonly: options.readonly === true },\n\t\t});\n\t\tconst connection = new SqliteSelectorConnection(worker);\n\t\tconst opened = new Promise<unknown>((resolve, reject) => connection.waiting.set(0, { resolve, reject }));\n\t\ttry {\n\t\t\tawait opened;\n\t\t} catch (error) {\n\t\t\tawait worker.terminate();\n\t\t\tthrow error;\n\t\t}\n\t\treturn connection;\n\t}\n\n\tall(sql: string, params: readonly SqliteSelectorValue[] = []): Promise<SqliteSelectorRow[]> {\n\t\treturn this.request({ kind: \"all\", sql, params: bindValues(params) }) as Promise<SqliteSelectorRow[]>;\n\t}\n\n\t/** Transcript entries can contain binary chunks; preserve their SQLite values across the worker boundary. */\n\tstorageRows<T extends SqliteRow>(sql: string, params: readonly SqliteValue[]): Promise<T[]> {\n\t\treturn this.request({ kind: \"all\", sql, params }) as Promise<T[]>;\n\t}\n\n\trows(sql: string, limit: number): Promise<SqliteSelectorRow[]> {\n\t\treturn this.request({ kind: \"rows\", sql, params: [], limit }) as Promise<SqliteSelectorRow[]>;\n\t}\n\n\trun(sql: string, params: readonly SqliteSelectorValue[] = []): Promise<{ changes: number }> {\n\t\treturn this.request({ kind: \"run\", sql, params: bindValues(params) }) as Promise<{ changes: number }>;\n\t}\n\n\tclose(): Promise<void> {\n\t\tthis.closing ??= this.request({ kind: \"close\" }).then(\n\t\t\t() => this.worker.terminate().then(() => undefined),\n\t\t\tasync (error: unknown) => {\n\t\t\t\tawait this.worker.terminate();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\treturn this.closing;\n\t}\n\n\tprivate request(request: ConnectionRequest): Promise<unknown> {\n\t\tif (this.ended !== undefined) return Promise.reject(this.ended);\n\t\tconst id = this.nextId++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tthis.worker.postMessage({ ...request, id });\n\t\t});\n\t}\n\n\tprivate end(error: Error): void {\n\t\tthis.ended ??= error;\n\t\tfor (const waiting of this.waiting.values()) waiting.reject(this.ended);\n\t\tthis.waiting.clear();\n\t}\n}\n"]}
@@ -0,0 +1,92 @@
1
+ import type { AgentMessage } from "@bastani/atomic-agent-core";
2
+ import { type Api, type Model, type SystemMessage, type Tool } from "@bastani/atomic-ai";
3
+ import type { SystemPromptSections } from "./system-prompt.ts";
4
+ export interface TransformedPromptHead {
5
+ /** The exact text the session leads with. */
6
+ readonly content?: string;
7
+ /**
8
+ * A fork: the conversation before this row is sent as it was, with the tools its requests hid (`hidden`) left
9
+ * out, and `note` opens what the fork adds.
10
+ */
11
+ readonly fork?: {
12
+ readonly note: string;
13
+ readonly hidden?: readonly string[];
14
+ };
15
+ /** A digest of each section the model is told at this row, before its `sections` changes. */
16
+ readonly digests: Record<string, string>;
17
+ readonly owner: string;
18
+ /** The session started as a fork: kept on every later head, also across compactions. */
19
+ readonly forked?: true;
20
+ }
21
+ export interface TransformedPromptRecord {
22
+ /**
23
+ * On the row that starts the prompt. A head with neither text nor fork (a fork after a compaction) has nothing to
24
+ * lead with: the next request records the session's current prompt.
25
+ */
26
+ readonly head?: TransformedPromptHead;
27
+ /** The sections that changed at this row; `null` removes one. */
28
+ readonly sections?: Record<string, string | null>;
29
+ }
30
+ /** The transformed prompt a session built and the sections it renders. */
31
+ export interface TransformedPrompt {
32
+ readonly content: string;
33
+ readonly sections: SystemPromptSections;
34
+ }
35
+ /** How a fork that continues a conversation adds its own prompt. */
36
+ export interface TransformedPromptFork {
37
+ /** The sections of the conversation's prompt it continues, as the model was told them. */
38
+ readonly sections: SystemPromptSections;
39
+ readonly note: string;
40
+ /** The tools the conversation's requests declared but hid. */
41
+ readonly hidden?: readonly string[];
42
+ }
43
+ /** Which tool changes the transport can declare after the first message; see `TranscriptToolSupport`. */
44
+ export type ToolChangeSupport = "none" | "additions" | "changes";
45
+ /** The tool changes a model's transport declares in place, from the compatibility flags its transports read. */
46
+ export declare function toolChangeSupport(compat: Model<Api>["compat"]): ToolChangeSupport;
47
+ export type SystemMessageWithTransformedPrompt = SystemMessage & {
48
+ transformedPrompt?: TransformedPromptRecord;
49
+ };
50
+ /** The owner a session records its transformed prompt under: the session and the transform's key. */
51
+ export declare function transformedPromptOwner(sessionId: string, key: string): string;
52
+ /** Whether any row of `messages` recorded a transformed prompt, under any owner. */
53
+ export declare function hasRecordedTransformedPrompt(messages: readonly AgentMessage[]): boolean;
54
+ /** Whether `messages` record that their session started as a fork that continues another session's conversation. */
55
+ export declare function startedAsFork(messages: readonly AgentMessage[]): boolean;
56
+ /** Whether `owner` recorded the transformed prompt the next request leads with. */
57
+ export declare function hasTransformedPrompt(messages: readonly AgentMessage[], owner: string): boolean;
58
+ /**
59
+ * The record for the next request: a new head when `owner` has no prompt to lead with, otherwise the sections of
60
+ * `desired` that changed since the model was last told them, or undefined when nothing changed. A fork whose
61
+ * conversation never recorded a prompt continues it: its head keeps the conversation's prompt and adds `desired` after
62
+ * it, and its own sections are the only ones it ever changes or removes. Any other session leads with `prompt`.
63
+ */
64
+ export declare function nextTransformedPromptRecord(messages: readonly AgentMessage[], owner: string, prompt: TransformedPrompt, desired: SystemPromptSections, fork?: TransformedPromptFork): TransformedPromptRecord | undefined;
65
+ /**
66
+ * Carry the transformed prompt into a compaction's system message: the same leading text, with every change made
67
+ * since as one update, so the prompt stays what the model was told. A fork's prompt is the conversation the
68
+ * compaction replaces, so it carries only its owner: the next request records the session's current prompt.
69
+ */
70
+ export declare function carriedTransformedPrompt(messages: readonly AgentMessage[]): TransformedPromptRecord | undefined;
71
+ /**
72
+ * Which tools a fork that continues a conversation declares: the conversation's own declarations are kept, whatever
73
+ * the fork may call (it refuses a call to a tool it lacks). The removal of a tool the fork cannot call (`callable`
74
+ * names the tools it can) is declared only where the transport declares changes in place. A tool only the fork has
75
+ * is declared where the transport can add it in place; otherwise it is reached through the conversation's codemode
76
+ * when the fork has codemode too, and declared (changing the top-level tool list) when not.
77
+ */
78
+ export declare function forkToolDeclarations(inherited: readonly Tool[], support: ToolChangeSupport, callable: readonly string[]): {
79
+ readonly keepRemoval: (name: string) => boolean;
80
+ readonly keepAddition: (tool: Tool) => boolean;
81
+ readonly throughCodemode: boolean;
82
+ };
83
+ /**
84
+ * The request projection of a transcript whose transformed prompt `owner` recorded, or undefined when `owner` has
85
+ * none to lead with. A recorded text leads with the tools declared up to its row, and earlier system messages fold
86
+ * into it. A fork sends the conversation before its row as it was, then its note. After the head, a system message
87
+ * carries its tool changes and its transformed section changes in place; the untransformed sections are never sent.
88
+ * `isHidden` names the session's own tools whose declarations its requests leave out; a fork leaves out the tools
89
+ * the conversation it continues hid before its row.
90
+ */
91
+ export declare function projectTransformedPrompt(messages: readonly AgentMessage[], owner: string, toolSupport: ToolChangeSupport, callable: readonly string[], isHidden: (name: string) => boolean): AgentMessage[] | undefined;
92
+ //# sourceMappingURL=transformed-system-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transformed-system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/transformed-system-prompt.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACN,KAAK,GAAG,EAER,KAAK,KAAK,EACV,KAAK,aAAa,EAClB,KAAK,IAAI,EAET,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,MAAM,WAAW,qBAAqB;IACrC,6CAA6C;IAC7C,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAC;IAC/E,6FAA6F;IAC7F,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,wFAAwF;IACxF,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,uBAAuB;IACvC;;;OAGG;IACH,QAAQ,CAAC,IAAI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wBAAgB,2BAA2B,CAC1C,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,iBAAiB,EACzB,OAAO,EAAE,oBAAoB,EAC7B,IAAI,CAAC,EAAE,qBAAqB,GAC1B,uBAAuB,GAAG,SAAS,CAkBrC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,uBAAuB,GAAG,SAAS,CAU/G;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CACnC,SAAS,EAAE,SAAS,IAAI,EAAE,EAC1B,OAAO,EAAE,iBAAiB,EAC1B,QAAQ,EAAE,SAAS,MAAM,EAAE,GACzB;IACF,QAAQ,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IAChD,QAAQ,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC;IAC/C,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAC;CAClC,CASA;AAgBD;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACvC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,iBAAiB,EAC9B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,GACjC,YAAY,EAAE,GAAG,SAAS,CAwD5B"}
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The prompt a session with a transformed system prompt (an in-process subagent child) actually sent.
3
+ *
4
+ * Such a session's own system messages record the structured prompt before the transform, which the model never
5
+ * sees. The transformed prompt is recorded beside them. The row that starts it records a digest of each section the
6
+ * model is told and its owner (the session and the transform's key), and either the exact text it leads with or, in
7
+ * a fork, a note: a fork leads with the conversation it continues, sent exactly as that conversation was sent, and
8
+ * adds the note and its own sections after it. A later row records the sections that changed. A session reopened on
9
+ * another day or after an upgrade therefore keeps its cached prefix and is told what changed as section updates, as a
10
+ * session with the structured prompt is. Only the latest recorded prompt is sent, and only by its owner: a session
11
+ * reopened under another key records and sends its current prompt instead.
12
+ */
13
+ import { createHash } from "node:crypto";
14
+ import { getCurrentTools, } from "@bastani/atomic-ai";
15
+ /** The tool changes a model's transport declares in place, from the compatibility flags its transports read. */
16
+ export function toolChangeSupport(compat) {
17
+ if (!compat || !("supportsMidConvoSystemMessages" in compat) || !compat.supportsMidConvoSystemMessages)
18
+ return "none";
19
+ if (("supportsMidConvoToolChanges" in compat && compat.supportsMidConvoToolChanges) ||
20
+ ("supportsAdditionalTools" in compat && compat.supportsAdditionalTools))
21
+ return "changes";
22
+ return "supportsMidConvoToolAdditions" in compat && compat.supportsMidConvoToolAdditions ? "additions" : "none";
23
+ }
24
+ /** The sections a fork keeps as the conversation it continues was sent: it never changes or removes them. */
25
+ const CONVERSATION_SECTIONS = new Set(["project_context", "skills"]);
26
+ function forkOwnSections(sections) {
27
+ return Object.fromEntries(Object.entries(sections).filter(([name]) => !CONVERSATION_SECTIONS.has(name)));
28
+ }
29
+ function transformedPromptOf(message) {
30
+ return message.role === "system" ? message.transformedPrompt : undefined;
31
+ }
32
+ /** The owner a session records its transformed prompt under: the session and the transform's key. */
33
+ export function transformedPromptOwner(sessionId, key) {
34
+ return JSON.stringify([sessionId, key]);
35
+ }
36
+ function latestHeadIndex(messages) {
37
+ return messages.findLastIndex((message) => transformedPromptOf(message)?.head !== undefined);
38
+ }
39
+ /**
40
+ * The row of the latest recorded prompt when `owner` recorded it and it has something to lead with, or -1: a prompt
41
+ * recorded before another owner's, and the changes recorded after it, are never sent again.
42
+ */
43
+ function headIndex(messages, owner) {
44
+ const index = latestHeadIndex(messages);
45
+ const head = index < 0 ? undefined : transformedPromptOf(messages[index])?.head;
46
+ return head?.owner === owner && (head.content !== undefined || head.fork !== undefined) ? index : -1;
47
+ }
48
+ function digest(text) {
49
+ return createHash("sha256").update(text).digest("base64url");
50
+ }
51
+ function digestsOf(sections) {
52
+ return Object.fromEntries(Object.entries(sections).map(([name, text]) => [name, digest(text)]));
53
+ }
54
+ /** The transformed prompt of `owner` as the model was last told it, or undefined when it has none to lead with. */
55
+ function transformedPromptState(messages, owner) {
56
+ const index = headIndex(messages, owner);
57
+ return index < 0 ? undefined : stateFrom(messages, index);
58
+ }
59
+ function stateFrom(messages, index) {
60
+ const head = transformedPromptOf(messages[index])?.head;
61
+ if (head === undefined)
62
+ return undefined;
63
+ const digests = new Map(Object.entries(head.digests));
64
+ const changed = new Map();
65
+ for (const message of messages.slice(index)) {
66
+ for (const [name, text] of Object.entries(transformedPromptOf(message)?.sections ?? {})) {
67
+ if (text === null)
68
+ digests.delete(name);
69
+ else
70
+ digests.set(name, digest(text));
71
+ changed.set(name, text);
72
+ }
73
+ }
74
+ return { head, digests, changed };
75
+ }
76
+ /** The sections of `desired` the model was not told; a section it was told and `removable` allows that is gone. */
77
+ function changedSections(told, desired, removable) {
78
+ const changes = {};
79
+ for (const [name, text] of Object.entries(desired))
80
+ if (told.get(name) !== digest(text))
81
+ changes[name] = text;
82
+ for (const name of told.keys())
83
+ if (desired[name] === undefined && removable(name))
84
+ changes[name] = null;
85
+ return Object.keys(changes).length > 0 ? changes : undefined;
86
+ }
87
+ /** Whether any row of `messages` recorded a transformed prompt, under any owner. */
88
+ export function hasRecordedTransformedPrompt(messages) {
89
+ return messages.some((message) => transformedPromptOf(message) !== undefined);
90
+ }
91
+ /** Whether `messages` record that their session started as a fork that continues another session's conversation. */
92
+ export function startedAsFork(messages) {
93
+ return messages.some((message) => {
94
+ const head = transformedPromptOf(message)?.head;
95
+ return head?.fork !== undefined || head?.forked === true;
96
+ });
97
+ }
98
+ /** Whether `owner` recorded the transformed prompt the next request leads with. */
99
+ export function hasTransformedPrompt(messages, owner) {
100
+ return headIndex(messages, owner) >= 0;
101
+ }
102
+ /**
103
+ * The record for the next request: a new head when `owner` has no prompt to lead with, otherwise the sections of
104
+ * `desired` that changed since the model was last told them, or undefined when nothing changed. A fork whose
105
+ * conversation never recorded a prompt continues it: its head keeps the conversation's prompt and adds `desired` after
106
+ * it, and its own sections are the only ones it ever changes or removes. Any other session leads with `prompt`.
107
+ */
108
+ export function nextTransformedPromptRecord(messages, owner, prompt, desired, fork) {
109
+ const state = transformedPromptState(messages, owner);
110
+ if (state !== undefined) {
111
+ const forked = state.head.fork !== undefined;
112
+ const own = (name) => !forked || typeof state.changed.get(name) === "string";
113
+ const sections = changedSections(state.digests, forked ? forkOwnSections(desired) : desired, own);
114
+ return sections ? { sections } : undefined;
115
+ }
116
+ if (fork !== undefined && latestHeadIndex(messages) < 0) {
117
+ const digests = digestsOf(fork.sections);
118
+ const sections = changedSections(new Map(Object.entries(digests)), forkOwnSections(desired), () => false);
119
+ const forked = { note: fork.note, ...(fork.hidden?.length ? { hidden: [...fork.hidden] } : {}) };
120
+ return { head: { fork: forked, digests, owner }, ...(sections ? { sections } : {}) };
121
+ }
122
+ const digests = digestsOf(prompt.sections);
123
+ const sections = changedSections(new Map(Object.entries(digests)), desired, () => true);
124
+ const forked = startedAsFork(messages) ? { forked: true } : {};
125
+ return { head: { content: prompt.content, digests, owner, ...forked }, ...(sections ? { sections } : {}) };
126
+ }
127
+ /**
128
+ * Carry the transformed prompt into a compaction's system message: the same leading text, with every change made
129
+ * since as one update, so the prompt stays what the model was told. A fork's prompt is the conversation the
130
+ * compaction replaces, so it carries only its owner: the next request records the session's current prompt.
131
+ */
132
+ export function carriedTransformedPrompt(messages) {
133
+ const index = latestHeadIndex(messages);
134
+ const state = index < 0 ? undefined : stateFrom(messages, index);
135
+ if (state === undefined)
136
+ return undefined;
137
+ if (state.head.content === undefined)
138
+ return { head: { digests: {}, owner: state.head.owner, forked: true } };
139
+ const sections = {};
140
+ for (const [name, text] of state.changed) {
141
+ if (text === null ? name in state.head.digests : state.head.digests[name] !== digest(text))
142
+ sections[name] = text;
143
+ }
144
+ return { head: state.head, ...(Object.keys(sections).length > 0 ? { sections } : {}) };
145
+ }
146
+ /**
147
+ * Which tools a fork that continues a conversation declares: the conversation's own declarations are kept, whatever
148
+ * the fork may call (it refuses a call to a tool it lacks). The removal of a tool the fork cannot call (`callable`
149
+ * names the tools it can) is declared only where the transport declares changes in place. A tool only the fork has
150
+ * is declared where the transport can add it in place; otherwise it is reached through the conversation's codemode
151
+ * when the fork has codemode too, and declared (changing the top-level tool list) when not.
152
+ */
153
+ export function forkToolDeclarations(inherited, support, callable) {
154
+ const declared = new Set(inherited.map((tool) => tool.name));
155
+ const own = new Set(callable);
156
+ const throughCodemode = support === "none" && own.has("codemode") && declared.has("codemode");
157
+ return {
158
+ keepRemoval: (name) => support === "changes" && !own.has(name),
159
+ keepAddition: (tool) => !declared.has(tool.name) && !throughCodemode,
160
+ throughCodemode,
161
+ };
162
+ }
163
+ /** A system message as a request that hides `hidden` declarations sends it (as `projectToolLoadout` does). */
164
+ function withoutHidden(message, hidden) {
165
+ if (!message.toolsAdded && !message.toolsRemoved)
166
+ return message;
167
+ const { toolsAdded, toolsRemoved, ...rest } = message;
168
+ const added = toolsAdded?.filter((tool) => !hidden(tool.name)) ?? [];
169
+ const removed = toolsRemoved?.filter((tool) => !hidden(tool.name)) ?? [];
170
+ if (added.length === (toolsAdded?.length ?? 0) && removed.length === (toolsRemoved?.length ?? 0))
171
+ return message;
172
+ return {
173
+ ...rest,
174
+ ...(added.length ? { toolsAdded: added } : {}),
175
+ ...(removed.length ? { toolsRemoved: removed } : {}),
176
+ };
177
+ }
178
+ /**
179
+ * The request projection of a transcript whose transformed prompt `owner` recorded, or undefined when `owner` has
180
+ * none to lead with. A recorded text leads with the tools declared up to its row, and earlier system messages fold
181
+ * into it. A fork sends the conversation before its row as it was, then its note. After the head, a system message
182
+ * carries its tool changes and its transformed section changes in place; the untransformed sections are never sent.
183
+ * `isHidden` names the session's own tools whose declarations its requests leave out; a fork leaves out the tools
184
+ * the conversation it continues hid before its row.
185
+ */
186
+ export function projectTransformedPrompt(messages, owner, toolSupport, callable, isHidden) {
187
+ const index = headIndex(messages, owner);
188
+ const head = index < 0 ? undefined : transformedPromptOf(messages[index])?.head;
189
+ if (head === undefined)
190
+ return undefined;
191
+ const inheritedHidden = new Set(head.fork?.hidden ?? []);
192
+ const declarations = head.fork
193
+ ? forkToolDeclarations(getCurrentTools(messages.slice(0, index)).filter((tool) => !inheritedHidden.has(tool.name)), toolSupport, callable)
194
+ : undefined;
195
+ const shown = (hidden) => (tool) => !hidden(tool.name);
196
+ const projected = [];
197
+ if (!head.fork) {
198
+ const tools = getCurrentTools(messages.slice(0, index + 1)).filter(shown(isHidden));
199
+ projected.push({
200
+ role: "system",
201
+ content: head.content ?? "",
202
+ ...(tools.length > 0 ? { toolsAdded: tools } : {}),
203
+ timestamp: messages.find((message) => message.role === "system")?.timestamp ?? Date.now(),
204
+ });
205
+ }
206
+ for (const [position, message] of messages.entries()) {
207
+ if (message.role !== "system") {
208
+ projected.push(message);
209
+ continue;
210
+ }
211
+ if (position < index) {
212
+ if (head.fork)
213
+ projected.push(withoutHidden(message, (name) => inheritedHidden.has(name)));
214
+ continue;
215
+ }
216
+ const sections = transformedPromptOf(message)?.sections;
217
+ const content = position === index ? (head.fork?.note ?? "") : "";
218
+ const ownHead = position === index && !head.fork;
219
+ let toolsAdded = ownHead ? undefined : message.toolsAdded?.filter(shown(isHidden));
220
+ let toolsRemoved = ownHead
221
+ ? undefined
222
+ : message.toolsRemoved?.filter(shown(isHidden));
223
+ if (declarations) {
224
+ toolsAdded = toolsAdded?.filter(declarations.keepAddition);
225
+ toolsRemoved = toolsRemoved?.filter((tool) => declarations.keepRemoval(tool.name) && !inheritedHidden.has(tool.name));
226
+ }
227
+ if (!content && !sections && !toolsAdded?.length && !toolsRemoved?.length)
228
+ continue;
229
+ projected.push({
230
+ role: "system",
231
+ content,
232
+ ...(sections ? { sections } : {}),
233
+ ...(toolsAdded?.length ? { toolsAdded } : {}),
234
+ ...(toolsRemoved?.length ? { toolsRemoved } : {}),
235
+ timestamp: message.timestamp,
236
+ });
237
+ }
238
+ return projected;
239
+ }
240
+ //# sourceMappingURL=transformed-system-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transformed-system-prompt.js","sourceRoot":"","sources":["../../src/core/transformed-system-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAEN,eAAe,GAKf,MAAM,oBAAoB,CAAC;AA8C5B,gHAAgH;AAChH,MAAM,UAAU,iBAAiB,CAAC,MAA4B;IAC7D,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,gCAAgC,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,8BAA8B;QACrG,OAAO,MAAM,CAAC;IACf,IACC,CAAC,6BAA6B,IAAI,MAAM,IAAI,MAAM,CAAC,2BAA2B,CAAC;QAC/E,CAAC,yBAAyB,IAAI,MAAM,IAAI,MAAM,CAAC,uBAAuB,CAAC;QAEvE,OAAO,SAAS,CAAC;IAClB,OAAO,+BAA+B,IAAI,MAAM,IAAI,MAAM,CAAC,6BAA6B,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC;AACjH,CAAC;AAED,6GAA6G;AAC7G,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC,CAAC;AAErE,SAAS,eAAe,CAAC,QAA8B;IACtD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,qBAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1G,CAAC;AAID,SAAS,mBAAmB,CAAC,OAAqB;IACjD,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAE,OAA8C,CAAC,iBAAiB,CAAC,CAAC,CAAC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MAAM,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;YAC3D,YAAY,GAAG,YAAY,EAAE,MAAM,CAClC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAChF,CAAC;QACH,CAAC;QACD,IAAI,CAAC,OAAO,IAAI,CAAC,QAAQ,IAAI,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,MAAM;YAAE,SAAS;QACpF,SAAS,CAAC,IAAI,CAAC;YACd,IAAI,EAAE,QAAQ;YACd,OAAO;YACP,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7C,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjD,SAAS,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["/**\n * The prompt a session with a transformed system prompt (an in-process subagent child) actually sent.\n *\n * Such a session's own system messages record the structured prompt before the transform, which the model never\n * sees. The transformed prompt is recorded beside them. The row that starts it records a digest of each section the\n * model is told and its owner (the session and the transform's key), and either the exact text it leads with or, in\n * a fork, a note: a fork leads with the conversation it continues, sent exactly as that conversation was sent, and\n * adds the note and its own sections after it. A later row records the sections that changed. A session reopened on\n * another day or after an upgrade therefore keeps its cached prefix and is told what changed as section updates, as a\n * session with the structured prompt is. Only the latest recorded prompt is sent, and only by its owner: a session\n * reopened under another key records and sends its current prompt instead.\n */\nimport { createHash } from \"node:crypto\";\nimport type { AgentMessage } from \"@bastani/atomic-agent-core\";\nimport {\n\ttype Api,\n\tgetCurrentTools,\n\ttype Model,\n\ttype SystemMessage,\n\ttype Tool,\n\ttype ToolReference,\n} from \"@bastani/atomic-ai\";\nimport type { SystemPromptSections } from \"./system-prompt.ts\";\n\nexport interface TransformedPromptHead {\n\t/** The exact text the session leads with. */\n\treadonly content?: string;\n\t/**\n\t * A fork: the conversation before this row is sent as it was, with the tools its requests hid (`hidden`) left\n\t * out, and `note` opens what the fork adds.\n\t */\n\treadonly fork?: { readonly note: string; readonly hidden?: readonly string[] };\n\t/** A digest of each section the model is told at this row, before its `sections` changes. */\n\treadonly digests: Record<string, string>;\n\treadonly owner: string;\n\t/** The session started as a fork: kept on every later head, also across compactions. */\n\treadonly forked?: true;\n}\n\nexport interface TransformedPromptRecord {\n\t/**\n\t * On the row that starts the prompt. A head with neither text nor fork (a fork after a compaction) has nothing to\n\t * lead with: the next request records the session's current prompt.\n\t */\n\treadonly head?: TransformedPromptHead;\n\t/** The sections that changed at this row; `null` removes one. */\n\treadonly sections?: Record<string, string | null>;\n}\n\n/** The transformed prompt a session built and the sections it renders. */\nexport interface TransformedPrompt {\n\treadonly content: string;\n\treadonly sections: SystemPromptSections;\n}\n\n/** How a fork that continues a conversation adds its own prompt. */\nexport interface TransformedPromptFork {\n\t/** The sections of the conversation's prompt it continues, as the model was told them. */\n\treadonly sections: SystemPromptSections;\n\treadonly note: string;\n\t/** The tools the conversation's requests declared but hid. */\n\treadonly hidden?: readonly string[];\n}\n\n/** Which tool changes the transport can declare after the first message; see `TranscriptToolSupport`. */\nexport type ToolChangeSupport = \"none\" | \"additions\" | \"changes\";\n\n/** The tool changes a model's transport declares in place, from the compatibility flags its transports read. */\nexport function toolChangeSupport(compat: Model<Api>[\"compat\"]): ToolChangeSupport {\n\tif (!compat || !(\"supportsMidConvoSystemMessages\" in compat) || !compat.supportsMidConvoSystemMessages)\n\t\treturn \"none\";\n\tif (\n\t\t(\"supportsMidConvoToolChanges\" in compat && compat.supportsMidConvoToolChanges) ||\n\t\t(\"supportsAdditionalTools\" in compat && compat.supportsAdditionalTools)\n\t)\n\t\treturn \"changes\";\n\treturn \"supportsMidConvoToolAdditions\" in compat && compat.supportsMidConvoToolAdditions ? \"additions\" : \"none\";\n}\n\n/** The sections a fork keeps as the conversation it continues was sent: it never changes or removes them. */\nconst CONVERSATION_SECTIONS = new Set([\"project_context\", \"skills\"]);\n\nfunction forkOwnSections(sections: SystemPromptSections): SystemPromptSections {\n\treturn Object.fromEntries(Object.entries(sections).filter(([name]) => !CONVERSATION_SECTIONS.has(name)));\n}\n\nexport type SystemMessageWithTransformedPrompt = SystemMessage & { transformedPrompt?: TransformedPromptRecord };\n\nfunction transformedPromptOf(message: AgentMessage): TransformedPromptRecord | undefined {\n\treturn message.role === \"system\" ? (message as SystemMessageWithTransformedPrompt).transformedPrompt : undefined;\n}\n\n/** The owner a session records its transformed prompt under: the session and the transform's key. */\nexport function transformedPromptOwner(sessionId: string, key: string): string {\n\treturn JSON.stringify([sessionId, key]);\n}\n\nfunction latestHeadIndex(messages: readonly AgentMessage[]): number {\n\treturn messages.findLastIndex((message) => transformedPromptOf(message)?.head !== undefined);\n}\n\n/**\n * The row of the latest recorded prompt when `owner` recorded it and it has something to lead with, or -1: a prompt\n * recorded before another owner's, and the changes recorded after it, are never sent again.\n */\nfunction headIndex(messages: readonly AgentMessage[], owner: string): number {\n\tconst index = latestHeadIndex(messages);\n\tconst head = index < 0 ? undefined : transformedPromptOf(messages[index])?.head;\n\treturn head?.owner === owner && (head.content !== undefined || head.fork !== undefined) ? index : -1;\n}\n\nfunction digest(text: string): string {\n\treturn createHash(\"sha256\").update(text).digest(\"base64url\");\n}\n\nfunction digestsOf(sections: SystemPromptSections): Record<string, string> {\n\treturn Object.fromEntries(Object.entries(sections).map(([name, text]) => [name, digest(text)]));\n}\n\ninterface TransformedPromptState {\n\treadonly head: TransformedPromptHead;\n\t/** The digest of each section the model was last told. */\n\treadonly digests: Map<string, string>;\n\t/** The text of each section changed since the head, or null for one removed since. */\n\treadonly changed: Map<string, string | null>;\n}\n\n/** The transformed prompt of `owner` as the model was last told it, or undefined when it has none to lead with. */\nfunction transformedPromptState(messages: readonly AgentMessage[], owner: string): TransformedPromptState | undefined {\n\tconst index = headIndex(messages, owner);\n\treturn index < 0 ? undefined : stateFrom(messages, index);\n}\n\nfunction stateFrom(messages: readonly AgentMessage[], index: number): TransformedPromptState | undefined {\n\tconst head = transformedPromptOf(messages[index])?.head;\n\tif (head === undefined) return undefined;\n\tconst digests = new Map(Object.entries(head.digests));\n\tconst changed = new Map<string, string | null>();\n\tfor (const message of messages.slice(index)) {\n\t\tfor (const [name, text] of Object.entries(transformedPromptOf(message)?.sections ?? {})) {\n\t\t\tif (text === null) digests.delete(name);\n\t\t\telse digests.set(name, digest(text));\n\t\t\tchanged.set(name, text);\n\t\t}\n\t}\n\treturn { head, digests, changed };\n}\n\n/** The sections of `desired` the model was not told; a section it was told and `removable` allows that is gone. */\nfunction changedSections(\n\ttold: ReadonlyMap<string, string>,\n\tdesired: SystemPromptSections,\n\tremovable: (name: string) => boolean,\n): Record<string, string | null> | undefined {\n\tconst changes: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(desired)) if (told.get(name) !== digest(text)) changes[name] = text;\n\tfor (const name of told.keys()) if (desired[name] === undefined && removable(name)) changes[name] = null;\n\treturn Object.keys(changes).length > 0 ? changes : undefined;\n}\n\n/** Whether any row of `messages` recorded a transformed prompt, under any owner. */\nexport function hasRecordedTransformedPrompt(messages: readonly AgentMessage[]): boolean {\n\treturn messages.some((message) => transformedPromptOf(message) !== undefined);\n}\n\n/** Whether `messages` record that their session started as a fork that continues another session's conversation. */\nexport function startedAsFork(messages: readonly AgentMessage[]): boolean {\n\treturn messages.some((message) => {\n\t\tconst head = transformedPromptOf(message)?.head;\n\t\treturn head?.fork !== undefined || head?.forked === true;\n\t});\n}\n\n/** Whether `owner` recorded the transformed prompt the next request leads with. */\nexport function hasTransformedPrompt(messages: readonly AgentMessage[], owner: string): boolean {\n\treturn headIndex(messages, owner) >= 0;\n}\n\n/**\n * The record for the next request: a new head when `owner` has no prompt to lead with, otherwise the sections of\n * `desired` that changed since the model was last told them, or undefined when nothing changed. A fork whose\n * conversation never recorded a prompt continues it: its head keeps the conversation's prompt and adds `desired` after\n * it, and its own sections are the only ones it ever changes or removes. Any other session leads with `prompt`.\n */\nexport function nextTransformedPromptRecord(\n\tmessages: readonly AgentMessage[],\n\towner: string,\n\tprompt: TransformedPrompt,\n\tdesired: SystemPromptSections,\n\tfork?: TransformedPromptFork,\n): TransformedPromptRecord | undefined {\n\tconst state = transformedPromptState(messages, owner);\n\tif (state !== undefined) {\n\t\tconst forked = state.head.fork !== undefined;\n\t\tconst own = (name: string) => !forked || typeof state.changed.get(name) === \"string\";\n\t\tconst sections = changedSections(state.digests, forked ? forkOwnSections(desired) : desired, own);\n\t\treturn sections ? { sections } : undefined;\n\t}\n\tif (fork !== undefined && latestHeadIndex(messages) < 0) {\n\t\tconst digests = digestsOf(fork.sections);\n\t\tconst sections = changedSections(new Map(Object.entries(digests)), forkOwnSections(desired), () => false);\n\t\tconst forked = { note: fork.note, ...(fork.hidden?.length ? { hidden: [...fork.hidden] } : {}) };\n\t\treturn { head: { fork: forked, digests, owner }, ...(sections ? { sections } : {}) };\n\t}\n\tconst digests = digestsOf(prompt.sections);\n\tconst sections = changedSections(new Map(Object.entries(digests)), desired, () => true);\n\tconst forked = startedAsFork(messages) ? ({ forked: true } as const) : {};\n\treturn { head: { content: prompt.content, digests, owner, ...forked }, ...(sections ? { sections } : {}) };\n}\n\n/**\n * Carry the transformed prompt into a compaction's system message: the same leading text, with every change made\n * since as one update, so the prompt stays what the model was told. A fork's prompt is the conversation the\n * compaction replaces, so it carries only its owner: the next request records the session's current prompt.\n */\nexport function carriedTransformedPrompt(messages: readonly AgentMessage[]): TransformedPromptRecord | undefined {\n\tconst index = latestHeadIndex(messages);\n\tconst state = index < 0 ? undefined : stateFrom(messages, index);\n\tif (state === undefined) return undefined;\n\tif (state.head.content === undefined) return { head: { digests: {}, owner: state.head.owner, forked: true } };\n\tconst sections: Record<string, string | null> = {};\n\tfor (const [name, text] of state.changed) {\n\t\tif (text === null ? name in state.head.digests : state.head.digests[name] !== digest(text)) sections[name] = text;\n\t}\n\treturn { head: state.head, ...(Object.keys(sections).length > 0 ? { sections } : {}) };\n}\n\n/**\n * Which tools a fork that continues a conversation declares: the conversation's own declarations are kept, whatever\n * the fork may call (it refuses a call to a tool it lacks). The removal of a tool the fork cannot call (`callable`\n * names the tools it can) is declared only where the transport declares changes in place. A tool only the fork has\n * is declared where the transport can add it in place; otherwise it is reached through the conversation's codemode\n * when the fork has codemode too, and declared (changing the top-level tool list) when not.\n */\nexport function forkToolDeclarations(\n\tinherited: readonly Tool[],\n\tsupport: ToolChangeSupport,\n\tcallable: readonly string[],\n): {\n\treadonly keepRemoval: (name: string) => boolean;\n\treadonly keepAddition: (tool: Tool) => boolean;\n\treadonly throughCodemode: boolean;\n} {\n\tconst declared = new Set(inherited.map((tool) => tool.name));\n\tconst own = new Set(callable);\n\tconst throughCodemode = support === \"none\" && own.has(\"codemode\") && declared.has(\"codemode\");\n\treturn {\n\t\tkeepRemoval: (name) => support === \"changes\" && !own.has(name),\n\t\tkeepAddition: (tool) => !declared.has(tool.name) && !throughCodemode,\n\t\tthroughCodemode,\n\t};\n}\n\n/** A system message as a request that hides `hidden` declarations sends it (as `projectToolLoadout` does). */\nfunction withoutHidden(message: SystemMessage, hidden: (name: string) => boolean): SystemMessage {\n\tif (!message.toolsAdded && !message.toolsRemoved) return message;\n\tconst { toolsAdded, toolsRemoved, ...rest } = message;\n\tconst added = toolsAdded?.filter((tool) => !hidden(tool.name)) ?? [];\n\tconst removed = toolsRemoved?.filter((tool) => !hidden(tool.name)) ?? [];\n\tif (added.length === (toolsAdded?.length ?? 0) && removed.length === (toolsRemoved?.length ?? 0)) return message;\n\treturn {\n\t\t...rest,\n\t\t...(added.length ? { toolsAdded: added } : {}),\n\t\t...(removed.length ? { toolsRemoved: removed } : {}),\n\t};\n}\n\n/**\n * The request projection of a transcript whose transformed prompt `owner` recorded, or undefined when `owner` has\n * none to lead with. A recorded text leads with the tools declared up to its row, and earlier system messages fold\n * into it. A fork sends the conversation before its row as it was, then its note. After the head, a system message\n * carries its tool changes and its transformed section changes in place; the untransformed sections are never sent.\n * `isHidden` names the session's own tools whose declarations its requests leave out; a fork leaves out the tools\n * the conversation it continues hid before its row.\n */\nexport function projectTransformedPrompt(\n\tmessages: readonly AgentMessage[],\n\towner: string,\n\ttoolSupport: ToolChangeSupport,\n\tcallable: readonly string[],\n\tisHidden: (name: string) => boolean,\n): AgentMessage[] | undefined {\n\tconst index = headIndex(messages, owner);\n\tconst head = index < 0 ? undefined : transformedPromptOf(messages[index])?.head;\n\tif (head === undefined) return undefined;\n\tconst inheritedHidden = new Set(head.fork?.hidden ?? []);\n\tconst declarations = head.fork\n\t\t? forkToolDeclarations(\n\t\t\t\tgetCurrentTools(messages.slice(0, index)).filter((tool) => !inheritedHidden.has(tool.name)),\n\t\t\t\ttoolSupport,\n\t\t\t\tcallable,\n\t\t\t)\n\t\t: undefined;\n\tconst shown = (hidden: (name: string) => boolean) => (tool: { readonly name: string }) => !hidden(tool.name);\n\tconst projected: AgentMessage[] = [];\n\tif (!head.fork) {\n\t\tconst tools = getCurrentTools(messages.slice(0, index + 1)).filter(shown(isHidden));\n\t\tprojected.push({\n\t\t\trole: \"system\",\n\t\t\tcontent: head.content ?? \"\",\n\t\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\t\ttimestamp: messages.find((message) => message.role === \"system\")?.timestamp ?? Date.now(),\n\t\t});\n\t}\n\tfor (const [position, message] of messages.entries()) {\n\t\tif (message.role !== \"system\") {\n\t\t\tprojected.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (position < index) {\n\t\t\tif (head.fork) projected.push(withoutHidden(message, (name) => inheritedHidden.has(name)));\n\t\t\tcontinue;\n\t\t}\n\t\tconst sections = transformedPromptOf(message)?.sections;\n\t\tconst content = position === index ? (head.fork?.note ?? \"\") : \"\";\n\t\tconst ownHead = position === index && !head.fork;\n\t\tlet toolsAdded: Tool[] | undefined = ownHead ? undefined : message.toolsAdded?.filter(shown(isHidden));\n\t\tlet toolsRemoved: ToolReference[] | undefined = ownHead\n\t\t\t? undefined\n\t\t\t: message.toolsRemoved?.filter(shown(isHidden));\n\t\tif (declarations) {\n\t\t\ttoolsAdded = toolsAdded?.filter(declarations.keepAddition);\n\t\t\ttoolsRemoved = toolsRemoved?.filter(\n\t\t\t\t(tool) => declarations.keepRemoval(tool.name) && !inheritedHidden.has(tool.name),\n\t\t\t);\n\t\t}\n\t\tif (!content && !sections && !toolsAdded?.length && !toolsRemoved?.length) continue;\n\t\tprojected.push({\n\t\t\trole: \"system\",\n\t\t\tcontent,\n\t\t\t...(sections ? { sections } : {}),\n\t\t\t...(toolsAdded?.length ? { toolsAdded } : {}),\n\t\t\t...(toolsRemoved?.length ? { toolsRemoved } : {}),\n\t\t\ttimestamp: message.timestamp,\n\t\t});\n\t}\n\treturn projected;\n}\n"]}
@@ -613,7 +613,7 @@ export async function executeCodemode(id, input, signal, update, ctx, options =
613
613
  })),
614
614
  globals: [
615
615
  ...discoveryGlobals(callable, samples, options),
616
- ...(options.models && ctx
616
+ ...(options.models && ctx && ctx.subagentPolicy?.codemodeRoutingOnly !== true
617
617
  ? modelGlobals(ctx, id, calls, publish, (extra) => {
618
618
  usage = usage ? combineUsage(usage, extra) : extra;
619
619
  }, (images) => {