@bastani/atomic 0.9.20-alpha.7 → 0.9.20-alpha.9

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 (315) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/builtin/intercom/package.json +3 -5
  3. package/dist/builtin/mcp/package.json +3 -3
  4. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  5. package/dist/builtin/subagents/package.json +3 -3
  6. package/dist/builtin/subagents/src/extension/index.bundle.mjs +11 -2
  7. package/dist/builtin/web-access/package.json +1 -1
  8. package/dist/builtin/workflows/CHANGELOG.md +37 -0
  9. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  10. package/dist/builtin/workflows/builtin/{chunk-ffdrv23t.js → chunk-18yz7r43.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-9z3ztr2a.js → chunk-1pd5zcfa.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-5724b0cf.js → chunk-24c235x7.js} +1 -1
  13. package/dist/builtin/workflows/builtin/{chunk-vn0wb31x.js → chunk-2jv44yz7.js} +1 -1
  14. package/dist/builtin/workflows/builtin/{chunk-hmt5w62g.js → chunk-2npg6daz.js} +1 -1
  15. package/dist/builtin/workflows/builtin/{chunk-njmf5ze7.js → chunk-7ps7bnb4.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-jngsbbpm.js → chunk-ad864596.js} +3 -3
  17. package/dist/builtin/workflows/builtin/{chunk-7n51c5gh.js → chunk-f8jjd90r.js} +1 -1
  18. package/dist/builtin/workflows/builtin/{chunk-3tx8ry44.js → chunk-gxrhbnaj.js} +2 -1
  19. package/dist/builtin/workflows/builtin/{chunk-2hzrv5y8.js → chunk-twefqrv0.js} +986 -199
  20. package/dist/builtin/workflows/builtin/{chunk-7bzcersz.js → chunk-ynded223.js} +3 -3
  21. package/dist/builtin/workflows/builtin/{chunk-dxjxtgmp.js → chunk-z5xdqrs6.js} +1 -1
  22. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  23. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  24. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  25. package/dist/builtin/workflows/builtin/goal.js +4 -4
  26. package/dist/builtin/workflows/builtin/index.js +12 -12
  27. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  28. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  29. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  30. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  31. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  32. package/dist/builtin/workflows/package.json +4 -4
  33. package/dist/builtin/workflows/src/authoring.d.ts +6 -3
  34. package/dist/builtin/workflows/src/extension/index.bundle.mjs +26991 -26238
  35. package/dist/builtin/workflows/src/index.js +41619 -12907
  36. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +13 -0
  37. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  38. package/dist/core/agent-session-boundaries.js +9 -4
  39. package/dist/core/agent-session-boundaries.js.map +1 -1
  40. package/dist/core/agent-session-events.d.ts.map +1 -1
  41. package/dist/core/agent-session-events.js +4 -0
  42. package/dist/core/agent-session-events.js.map +1 -1
  43. package/dist/core/agent-session-methods.d.ts +3 -0
  44. package/dist/core/agent-session-methods.d.ts.map +1 -1
  45. package/dist/core/agent-session-methods.js.map +1 -1
  46. package/dist/core/agent-session-tasks.js +4 -4
  47. package/dist/core/agent-session-tasks.js.map +1 -1
  48. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  49. package/dist/core/agent-session-tool-registry.js +4 -3
  50. package/dist/core/agent-session-tool-registry.js.map +1 -1
  51. package/dist/core/agent-session.d.ts +3 -0
  52. package/dist/core/agent-session.d.ts.map +1 -1
  53. package/dist/core/agent-session.js +3 -0
  54. package/dist/core/agent-session.js.map +1 -1
  55. package/dist/core/cache-stats.d.ts +7 -1
  56. package/dist/core/cache-stats.d.ts.map +1 -1
  57. package/dist/core/cache-stats.js +24 -5
  58. package/dist/core/cache-stats.js.map +1 -1
  59. package/dist/core/execution-model-router.d.ts +1 -1
  60. package/dist/core/execution-model-router.d.ts.map +1 -1
  61. package/dist/core/execution-model-router.js +23 -14
  62. package/dist/core/execution-model-router.js.map +1 -1
  63. package/dist/core/extensions/agent-events.d.ts +9 -1
  64. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  65. package/dist/core/extensions/agent-events.js.map +1 -1
  66. package/dist/core/extensions/api-types.d.ts +2 -1
  67. package/dist/core/extensions/api-types.d.ts.map +1 -1
  68. package/dist/core/extensions/api-types.js.map +1 -1
  69. package/dist/core/extensions/event-types.d.ts +2 -2
  70. package/dist/core/extensions/event-types.d.ts.map +1 -1
  71. package/dist/core/extensions/event-types.js.map +1 -1
  72. package/dist/core/extensions/index.d.ts +1 -1
  73. package/dist/core/extensions/index.d.ts.map +1 -1
  74. package/dist/core/extensions/index.js.map +1 -1
  75. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  76. package/dist/core/extensions/loader-core.js +1 -0
  77. package/dist/core/extensions/loader-core.js.map +1 -1
  78. package/dist/core/extensions/provider-types.d.ts +34 -16
  79. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  80. package/dist/core/extensions/provider-types.js.map +1 -1
  81. package/dist/core/extensions/runtime-types.d.ts +4 -0
  82. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  83. package/dist/core/extensions/runtime-types.js.map +1 -1
  84. package/dist/core/extensions/tool-types.d.ts +9 -0
  85. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  86. package/dist/core/extensions/tool-types.js.map +1 -1
  87. package/dist/core/fast-model-routing.d.ts.map +1 -1
  88. package/dist/core/fast-model-routing.js +1 -0
  89. package/dist/core/fast-model-routing.js.map +1 -1
  90. package/dist/core/fast-model-variants.d.ts +10 -0
  91. package/dist/core/fast-model-variants.d.ts.map +1 -1
  92. package/dist/core/fast-model-variants.js +13 -1
  93. package/dist/core/fast-model-variants.js.map +1 -1
  94. package/dist/core/model-registry.d.ts +3 -1
  95. package/dist/core/model-registry.d.ts.map +1 -1
  96. package/dist/core/model-registry.js +6 -0
  97. package/dist/core/model-registry.js.map +1 -1
  98. package/dist/core/model-runtime-auth.d.ts +2 -2
  99. package/dist/core/model-runtime-auth.d.ts.map +1 -1
  100. package/dist/core/model-runtime-auth.js.map +1 -1
  101. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  102. package/dist/core/model-runtime-streaming.js +2 -1
  103. package/dist/core/model-runtime-streaming.js.map +1 -1
  104. package/dist/core/model-runtime.d.ts +11 -3
  105. package/dist/core/model-runtime.d.ts.map +1 -1
  106. package/dist/core/model-runtime.js +41 -6
  107. package/dist/core/model-runtime.js.map +1 -1
  108. package/dist/core/package-manager-npm.d.ts.map +1 -1
  109. package/dist/core/package-manager-npm.js +32 -8
  110. package/dist/core/package-manager-npm.js.map +1 -1
  111. package/dist/core/package-manager-resolver.js +3 -1
  112. package/dist/core/package-manager-resolver.js.map +1 -1
  113. package/dist/core/package-manager-types.d.ts +1 -0
  114. package/dist/core/package-manager-types.d.ts.map +1 -1
  115. package/dist/core/package-manager-types.js.map +1 -1
  116. package/dist/core/provider-composer-internal.d.ts +40 -21
  117. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  118. package/dist/core/provider-composer-internal.js +22 -20
  119. package/dist/core/provider-composer-internal.js.map +1 -1
  120. package/dist/core/provider-composer.d.ts +3 -3
  121. package/dist/core/provider-composer.d.ts.map +1 -1
  122. package/dist/core/provider-composer.js +54 -10
  123. package/dist/core/provider-composer.js.map +1 -1
  124. package/dist/core/remote-catalog-provider.d.ts +8 -1
  125. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  126. package/dist/core/remote-catalog-provider.js +46 -4
  127. package/dist/core/remote-catalog-provider.js.map +1 -1
  128. package/dist/core/resource-loader-core.d.ts.map +1 -1
  129. package/dist/core/resource-loader-core.js +7 -3
  130. package/dist/core/resource-loader-core.js.map +1 -1
  131. package/dist/core/resource-loader-extension-warnings.d.ts +9 -0
  132. package/dist/core/resource-loader-extension-warnings.d.ts.map +1 -0
  133. package/dist/core/resource-loader-extension-warnings.js +54 -0
  134. package/dist/core/resource-loader-extension-warnings.js.map +1 -0
  135. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  136. package/dist/core/resource-loader-extensions.js +1 -0
  137. package/dist/core/resource-loader-extensions.js.map +1 -1
  138. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  139. package/dist/core/resource-loader-reload.js +6 -0
  140. package/dist/core/resource-loader-reload.js.map +1 -1
  141. package/dist/core/runtime-credentials.d.ts.map +1 -1
  142. package/dist/core/runtime-credentials.js +3 -1
  143. package/dist/core/runtime-credentials.js.map +1 -1
  144. package/dist/core/sdk.js +16 -6
  145. package/dist/core/sdk.js.map +1 -1
  146. package/dist/core/settings-manager-basic-accessors.js +4 -4
  147. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  148. package/dist/core/skill-catalog.d.ts.map +1 -1
  149. package/dist/core/skill-catalog.js +18 -6
  150. package/dist/core/skill-catalog.js.map +1 -1
  151. package/dist/core/structured-output/choice-schema.d.ts +8 -0
  152. package/dist/core/structured-output/choice-schema.d.ts.map +1 -0
  153. package/dist/core/structured-output/choice-schema.js +79 -0
  154. package/dist/core/structured-output/choice-schema.js.map +1 -0
  155. package/dist/core/structured-output/index.d.ts +3 -5
  156. package/dist/core/structured-output/index.d.ts.map +1 -1
  157. package/dist/core/structured-output/index.js +218 -41
  158. package/dist/core/structured-output/index.js.map +1 -1
  159. package/dist/core/structured-output/resolver.d.ts +0 -46
  160. package/dist/core/structured-output/resolver.d.ts.map +1 -1
  161. package/dist/core/structured-output/resolver.js +15 -93
  162. package/dist/core/structured-output/resolver.js.map +1 -1
  163. package/dist/core/structured-output/types.d.ts +27 -21
  164. package/dist/core/structured-output/types.d.ts.map +1 -1
  165. package/dist/core/structured-output/types.js.map +1 -1
  166. package/dist/core/system-prompt.d.ts.map +1 -1
  167. package/dist/core/system-prompt.js +9 -1
  168. package/dist/core/system-prompt.js.map +1 -1
  169. package/dist/core/tasks/owner-store.d.ts +6 -0
  170. package/dist/core/tasks/owner-store.d.ts.map +1 -1
  171. package/dist/core/tasks/owner-store.js +16 -3
  172. package/dist/core/tasks/owner-store.js.map +1 -1
  173. package/dist/core/tasks/pause.js +1 -1
  174. package/dist/core/tasks/pause.js.map +1 -1
  175. package/dist/core/tasks/supervisor.d.ts +4 -2
  176. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  177. package/dist/core/tasks/supervisor.js +9 -3
  178. package/dist/core/tasks/supervisor.js.map +1 -1
  179. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  180. package/dist/core/tools/ask-user-question/ask-user-question.js +1 -0
  181. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  182. package/dist/core/tools/bash.d.ts.map +1 -1
  183. package/dist/core/tools/bash.js +16 -13
  184. package/dist/core/tools/bash.js.map +1 -1
  185. package/dist/core/tools/edit.d.ts.map +1 -1
  186. package/dist/core/tools/edit.js +1 -0
  187. package/dist/core/tools/edit.js.map +1 -1
  188. package/dist/core/tools/file-mutation-coordinator.d.ts +4 -3
  189. package/dist/core/tools/file-mutation-coordinator.d.ts.map +1 -1
  190. package/dist/core/tools/file-mutation-coordinator.js +45 -38
  191. package/dist/core/tools/file-mutation-coordinator.js.map +1 -1
  192. package/dist/core/tools/powershell.d.ts +16 -0
  193. package/dist/core/tools/powershell.d.ts.map +1 -1
  194. package/dist/core/tools/structured-output.d.ts +9 -6
  195. package/dist/core/tools/structured-output.d.ts.map +1 -1
  196. package/dist/core/tools/structured-output.js +36 -8
  197. package/dist/core/tools/structured-output.js.map +1 -1
  198. package/dist/core/tools/todos.d.ts.map +1 -1
  199. package/dist/core/tools/todos.js +1 -0
  200. package/dist/core/tools/todos.js.map +1 -1
  201. package/dist/core/tools/tool-concurrency.d.ts +23 -0
  202. package/dist/core/tools/tool-concurrency.d.ts.map +1 -0
  203. package/dist/core/tools/tool-concurrency.js +58 -0
  204. package/dist/core/tools/tool-concurrency.js.map +1 -0
  205. package/dist/core/tools/tool-definition-wrapper.d.ts +4 -1
  206. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  207. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  208. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  209. package/dist/core/tools/write.d.ts.map +1 -1
  210. package/dist/core/tools/write.js +1 -0
  211. package/dist/core/tools/write.js.map +1 -1
  212. package/dist/index-extensions.d.ts +1 -1
  213. package/dist/index-extensions.d.ts.map +1 -1
  214. package/dist/index-extensions.js.map +1 -1
  215. package/dist/index.d.ts +2 -2
  216. package/dist/index.d.ts.map +1 -1
  217. package/dist/index.js +2 -2
  218. package/dist/index.js.map +1 -1
  219. package/dist/main.d.ts.map +1 -1
  220. package/dist/main.js +4 -0
  221. package/dist/main.js.map +1 -1
  222. package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
  223. package/dist/modes/interactive/components/atomic-banner.js +3 -2
  224. package/dist/modes/interactive/components/atomic-banner.js.map +1 -1
  225. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  226. package/dist/modes/interactive/components/settings-selector-items.js +11 -9
  227. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  228. package/dist/modes/interactive/components/settings-selector-types.d.ts +2 -1
  229. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  230. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  231. package/dist/modes/interactive/components/startup-identity.d.ts +3 -0
  232. package/dist/modes/interactive/components/startup-identity.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/startup-identity.js +11 -2
  234. package/dist/modes/interactive/components/startup-identity.js.map +1 -1
  235. package/dist/modes/interactive/components/task-inspector.d.ts +1 -0
  236. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/task-inspector.js +11 -11
  238. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  239. package/dist/modes/interactive/components/task-list.d.ts +9 -3
  240. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  241. package/dist/modes/interactive/components/task-list.js +26 -2
  242. package/dist/modes/interactive/components/task-list.js.map +1 -1
  243. package/dist/modes/interactive/interactive-agent-events.js +3 -9
  244. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  245. package/dist/modes/interactive/interactive-auth-login.js +1 -1
  246. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  247. package/dist/modes/interactive/interactive-render-chat.js +3 -9
  248. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  249. package/dist/modes/interactive/interactive-resource-rendering.js +6 -9
  250. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  251. package/dist/modes/interactive/interactive-selectors.js +1 -0
  252. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  253. package/dist/modes/interactive/interactive-slash-commands.js +2 -4
  254. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  255. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  256. package/dist/modes/interactive/interactive-tui.js +2 -0
  257. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  258. package/dist/modes/interactive/overlay-line-composite.d.ts +7 -0
  259. package/dist/modes/interactive/overlay-line-composite.d.ts.map +1 -0
  260. package/dist/modes/interactive/overlay-line-composite.js +24 -0
  261. package/dist/modes/interactive/overlay-line-composite.js.map +1 -0
  262. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -0
  263. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  264. package/dist/modes/interactive-engine/isolated-runtime.js +5 -0
  265. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  266. package/dist/utils/child-process.d.ts +1 -0
  267. package/dist/utils/child-process.d.ts.map +1 -1
  268. package/dist/utils/child-process.js +7 -8
  269. package/dist/utils/child-process.js.map +1 -1
  270. package/dist/utils/clipboard-image.d.ts.map +1 -1
  271. package/dist/utils/clipboard-image.js +14 -17
  272. package/dist/utils/clipboard-image.js.map +1 -1
  273. package/dist/utils/shell.d.ts.map +1 -1
  274. package/dist/utils/shell.js +18 -1
  275. package/dist/utils/shell.js.map +1 -1
  276. package/docs/background-tasks.md +1 -0
  277. package/docs/computer-use.md +2 -2
  278. package/docs/custom-provider/registration.md +1 -1
  279. package/docs/custom-provider.md +43 -1
  280. package/docs/extensions/authoring.md +22 -3
  281. package/docs/extensions/events.md +18 -0
  282. package/docs/extensions/examples.md +1 -0
  283. package/docs/models/evals.md +31 -79
  284. package/docs/models/model-selection.md +5 -1
  285. package/docs/packages/authoring.md +3 -1
  286. package/docs/providers.md +11 -12
  287. package/docs/sdk/reference.md +18 -42
  288. package/docs/sdk/structured-decisions.md +44 -89
  289. package/docs/sdk.md +1 -1
  290. package/docs/settings.md +6 -6
  291. package/docs/subagents/reference.md +7 -8
  292. package/docs/usage.md +13 -0
  293. package/docs/workflows/api-reference.md +38 -35
  294. package/docs/workflows/authoring.md +113 -1
  295. package/docs/workflows/builtins.md +1 -1
  296. package/docs/workflows/operations.md +51 -29
  297. package/docs/workflows/verification.md +13 -0
  298. package/examples/extensions/README.md +1 -0
  299. package/examples/extensions/debug-provider.ts +90 -0
  300. package/examples/extensions/structured-output.ts +6 -0
  301. package/npm-shrinkwrap.json +32 -32
  302. package/package.json +3 -3
  303. package/dist/builtin/workflows/src/durable/dependency-doctor-types.d.ts +0 -42
  304. package/dist/core/decision-provider.d.ts +0 -4
  305. package/dist/core/decision-provider.d.ts.map +0 -1
  306. package/dist/core/decision-provider.js +0 -12
  307. package/dist/core/decision-provider.js.map +0 -1
  308. package/dist/core/structured-output/jev-client.d.ts +0 -25
  309. package/dist/core/structured-output/jev-client.d.ts.map +0 -1
  310. package/dist/core/structured-output/jev-client.js +0 -174
  311. package/dist/core/structured-output/jev-client.js.map +0 -1
  312. package/dist/core/structured-output/jev.d.ts +0 -5
  313. package/dist/core/structured-output/jev.d.ts.map +0 -1
  314. package/dist/core/structured-output/jev.js +0 -249
  315. package/dist/core/structured-output/jev.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAC/F;QACD,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC;QACrD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB,IAAI,EAAE;QAClD,QAAQ,E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K,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line installer and report its side effects; never run \\`cua-driver skills install\\`. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAC/F;QACD,gBAAgB,EAAE,CAAC,GA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AAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
@@ -22,6 +22,7 @@ export declare class OwnerTaskStore {
22
22
  private activityCursors;
23
23
  private omittedActivity;
24
24
  private backgroundIds;
25
+ private settlements;
25
26
  readonly anchors: Map<TaskId, TaskAnchor>;
26
27
  private current?;
27
28
  readonly supervisor: TaskSupervisor;
@@ -32,6 +33,11 @@ export declare class OwnerTaskStore {
32
33
  get tasks(): TaskRecord[];
33
34
  /** Background membership survives foreground waits and terminal observation cleanup. */
34
35
  get backgroundTasks(): TaskRecord[];
36
+ /**
37
+ * Journal sequence at which each task settled; higher is more recent. Tasks first seen settled in a
38
+ * snapshot without their settlement event share that snapshot's sequence, so their order is unknown.
39
+ */
40
+ get settlementOrder(): ReadonlyMap<TaskId, bigint>;
35
41
  /** Resolve only within the owner that authorized this store. */
36
42
  resolveTask(id: TaskId): Result<TaskLease, WaitError>;
37
43
  recentActivity(id: TaskId): TaskActivity[];
@@ -1 +1 @@
1
- {"version":3,"file":"owner-store.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/owner-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,cAAc,EACd,MAAM,EAEN,aAAa,EACb,MAAM,EACN,MAAM,EACN,UAAU,EACV,SAAS,EACT,UAAU,EACV,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAoB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE/F,oFAAoF;AACpF,eAAO,MAAM,mBAAmB,KAAK,CAAC;AACtC,eAAO,MAAM,mBAAmB,OAAO,CAAC;AACxC,MAAM,MAAM,UAAU,GAAG;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACrC,UAAU,EAAE,MAAM,CAA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,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAE7E;AAED,oFAAoF;AACpF,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAU5F"}
@@ -14,6 +14,7 @@ export class OwnerTaskStore {
14
14
  this.activityCursors = new Map();
15
15
  this.omittedActivity = new Set();
16
16
  this.backgroundIds = new Set();
17
+ this.settlements = new Map();
17
18
  this.anchors = new Map();
18
19
  this.supervisor = supervisor;
19
20
  this.owner = owner;
@@ -31,6 +32,13 @@ export class OwnerTaskStore {
31
32
  get backgroundTasks() {
32
33
  return this.tasks.filter((task) => task.wasBackground || isBackground(task.observation) || this.backgroundIds.has(task.ref.taskId));
33
34
  }
35
+ /**
36
+ * Journal sequence at which each task settled; higher is more recent. Tasks first seen settled in a
37
+ * snapshot without their settlement event share that snapshot's sequence, so their order is unknown.
38
+ */
39
+ get settlementOrder() {
40
+ return this.settlements;
41
+ }
34
42
  /** Resolve only within the owner that authorized this store. */
35
43
  resolveTask(id) {
36
44
  return this.supervisor.lookupTask(this.owner, id);
@@ -54,8 +62,8 @@ export class OwnerTaskStore {
54
62
  return watched;
55
63
  const subscription = watched.value;
56
64
  this.subscription = subscription;
57
- this.reconcile(subscription.snapshot);
58
- subscription.onReconcile = (snapshot) => this.reconcile(snapshot);
65
+ this.reconcile(subscription.snapshot, []);
66
+ subscription.onReconcile = (snapshot, events) => this.reconcile(snapshot, events);
59
67
  void this.observe(subscription);
60
68
  return { ok: true, value: undefined };
61
69
  }
@@ -67,19 +75,24 @@ export class OwnerTaskStore {
67
75
  this.subscription?.dispose();
68
76
  this.subscription = undefined;
69
77
  }
70
- reconcile(snapshot) {
78
+ reconcile(snapshot, events) {
71
79
  if (this.current &&
72
80
  (snapshot.ownerId !== this.current.ownerId || snapshot.generation !== this.current.generation))
73
81
  throw new Error("StaleGeneration: cannot replace a task owner projection");
74
82
  if (this.current && BigInt(snapshot.cursor.sequence) <= BigInt(this.current.cursor.sequence))
75
83
  return;
76
84
  this.current = snapshot;
85
+ for (const event of events)
86
+ if (event.payload.kind === "task-settled" && !this.settlements.has(event.payload.ref.taskId))
87
+ this.settlements.set(event.payload.ref.taskId, BigInt(event.cursor.sequence));
77
88
  for (const task of snapshot.tasks) {
78
89
  const previous = this.records.get(task.ref.taskId);
79
90
  if (isBackground(task.observation) || isBackground(previous?.observation))
80
91
  this.backgroundIds.add(task.ref.taskId);
81
92
  // Native settlement is immutable, even when recovering a view from a snapshot.
82
93
  this.records.set(task.ref.taskId, previous?.execution.kind === "settled" ? { ...task, execution: previous.execution } : task);
94
+ if (task.execution.kind === "settled" && !this.settlements.has(task.ref.taskId))
95
+ this.settlements.set(task.ref.taskId, BigInt(snapshot.cursor.sequence));
83
96
  if (!this.anchors.has(task.ref.taskId))
84
97
  this.anchors.set(task.ref.taskId, {
85
98
  taskId: task.ref.taskId,
@@ -1 +1 @@
1
- {"version":3,"file":"owner-store.js","sourceRoot":"","sources":["../../../src/core/tasks/owner-store.ts"],"names":[],"mappings":"AAaA,oFAAoF;AACpF,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AACtC,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AASxC,SAAS,YAAY,CAAC,WAAkD;IACvE,4EAA4E;IAC5E,OAAO,WAAW,EAAE,IAAI,KAAK,YAAY,IAAI,WAAW,CAAC,MAAM,KAAK,cAAc,CAAC;AACpF,CAAC;AAED,qEAAqE;AACrE,MAAM,OAAO,cAAc;IAY1B,YAAY,UAA0B,EAAE,KAAiB;QAVjD,cAAS,GAAG,IAAI,GAAG,EAAc,CAAC;QAClC,YAAO,GAAG,IAAI,GAAG,EAAsB,CAAC;QACxC,aAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;QAC7C,oBAAe,GAAG,IAAI,GAAG,EAAkB,CAAC;QAC5C,oBAAe,GAAG,IAAI,GAAG,EAAU,CAAC;QACpC,kB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AAE,CAAC;QACtB,gBAAgB,CAAC,GAAG,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAC1C,CAAC;IACD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACxB,OAAO,GAAG,EAAE;QACX,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC,CAAC;AACH,CAAC","sourcesContent":["import type {\n\tActivityReport,\n\tCursor,\n\tNativeEvent,\n\tOwnerSnapshot,\n\tResult,\n\tTaskId,\n\tTaskRecord,\n\tWaitError,\n\tWatchError,\n} from \"./contracts.js\";\nimport type { OwnerLease, TaskLease, TaskSubscription, TaskSupervisor } from \"./supervisor.js\";\n\n/** Activity previews are bounded independently of authoritative session history. */\nexport const TASK_ACTIVITY_LIMIT = 64;\nexport const TASK_ACTIVITY_BYTES = 8192;\nexport type TaskAnchor = {\n\ttaskId: TaskId;\n\tactivitySequence: Cursor[\"sequence\"];\n\tcellOffset: number;\n\tfollowBottom: boolean;\n};\nexport type TaskActivity = { cursor: Cursor; report: ActivityReport };\n\nfunction isBackground(observation: TaskRecord[\"observation\"] | undefined): boolean {\n\t// Admission starts unobserved; that placeholder is not a background launch.\n\treturn observation?.kind === \"background\" && observation.reason !== \"not-observed\";\n}\n\n/** A view subscription owns neither the owner nor its executions. */\nexport class OwnerTaskStore {\n\tprivate subscription?: TaskSubscription;\n\tprivate listeners = new Set<() => void>();\n\tprivate records = new Map<TaskId, TaskRecord>();\n\tprivate activity = new Map<TaskId, TaskActivity[]>();\n\tprivate activityCursors = new Map<TaskId, bigint>();\n\tprivate omittedActivity = new Set<TaskId>();\n\tprivate backgroundIds = new Set<TaskId>();\n\treadonly anchors = new Map<TaskId, TaskAnchor>();\n\tprivate current?: OwnerSnapshot;\n\treadonly supervisor: TaskSupervisor;\n\tprivate readonly owner: OwnerLease;\n\tconstructor(supervisor: TaskSupervisor, owner: OwnerLease) {\n\t\tthis.supervisor = supervisor;\n\t\tthis.owner = owner;\n\t}\n\n\tget snapshot(): OwnerSnapshot | undefined {\n\t\treturn this.current;\n\t}\n\tget cursor(): Cursor | undefined {\n\t\treturn this.current?.cursor;\n\t}\n\tget tasks(): TaskRecord[] {\n\t\treturn [...this.records.values()];\n\t}\n\t/** Background membership survives foreground waits and terminal observation cleanup. */\n\tget backgroundTasks(): TaskRecord[] {\n\t\treturn this.tasks.filter(\n\t\t\t(task) => task.wasBackground || isBackground(task.observation) || this.backgroundIds.has(task.ref.taskId),\n\t\t);\n\t}\n\t/** Resolve only within the owner that authorized this store. */\n\tresolveTask(id: TaskId): Result<TaskLease, WaitError> {\n\t\treturn this.supervisor.lookupTask(this.owner, id);\n\t}\n\trecentActivity(id: TaskId): TaskActivity[] {\n\t\treturn [...(this.activity.get(id) ?? [])];\n\t}\n\tactivityOmitted(id: TaskId): boolean {\n\t\treturn this.omittedActivity.has(id);\n\t}\n\tsubscribe(listener: () => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tconnect(): Result<void, WatchError> {\n\t\tthis.dispose();\n\t\tconst watched = this.supervisor.watchOwnerTasks(this.owner, this.cursor);\n\t\tif (!watched.ok) return watched;\n\t\tconst subscription = watched.value;\n\t\tthis.subscription = subscription;\n\t\tthis.reconcile(subscription.snapshot);\n\t\tsubscription.onReconcile = (snapshot) => this.reconcile(snapshot);\n\t\tvoid this.observe(subscription);\n\t\treturn { ok: true, value: undefined };\n\t}\n\t/** Useful at explicit host barriers; no transcript repaint timer is installed. */\n\tdrain(): void {\n\t\tthis.subscription?.drain();\n\t}\n\tdispose(): void {\n\t\tthis.subscription?.dispose();\n\t\tthis.subscription = undefined;\n\t}\n\tprivate reconcile(snapshot: OwnerSnapshot): void {\n\t\tif (\n\t\t\tthis.current &&\n\t\t\t(snapshot.ownerId !== this.current.ownerId || snapshot.generation !== this.current.generation)\n\t\t)\n\t\t\tthrow new Error(\"StaleGeneration: cannot replace a task owner projection\");\n\t\tif (this.current && BigInt(snapshot.cursor.sequence) <= BigInt(this.current.cursor.sequence)) return;\n\t\tthis.current = snapshot;\n\t\tfor (const task of snapshot.tasks) {\n\t\t\tconst previous = this.records.get(task.ref.taskId);\n\t\t\tif (isBackground(task.observation) || isBackground(previous?.observation))\n\t\t\t\tthis.backgroundIds.add(task.ref.taskId);\n\t\t\t// Native settlement is immutable, even when recovering a view from a snapshot.\n\t\t\tthis.records.set(\n\t\t\t\ttask.ref.taskId,\n\t\t\t\tprevious?.execution.kind === \"settled\" ? { ...task, execution: previous.execution } : task,\n\t\t\t);\n\t\t\tif (!this.anchors.has(task.ref.taskId))\n\t\t\t\tthis.anchors.set(task.ref.taskId, {\n\t\t\t\t\ttaskId: task.ref.taskId,\n\t\t\t\t\tactivitySequence: snapshot.cursor.sequence,\n\t\t\t\t\tcellOffset: 0,\n\t\t\t\t\tfollowBottom: true,\n\t\t\t\t});\n\t\t}\n\t\tthis.notify();\n\t}\n\tprivate async observe(subscription: TaskSubscription): Promise<void> {\n\t\t// Journal overflow ends the old iterator after publishing a reset snapshot.\n\t\twhile (this.subscription === subscription && this.current?.state !== \"closed\") {\n\t\t\tfor await (const event of subscription.events) {\n\t\t\t\tif (this.subscription !== subscription) return;\n\t\t\t\tthis.retainActivity(event);\n\t\t\t}\n\t\t\tif (this.subscription !== subscription || this.snapshot?.state === \"closed\") return;\n\t\t\tawait new Promise<void>((resolve) => setImmediate(resolve));\n\t\t}\n\t}\n\tprivate retainActivity(event: NativeEvent): void {\n\t\tif (event.payload.kind === \"host-observation-changed\" && isBackground(event.payload.observation)) {\n\t\t\tthis.backgroundIds.add(event.payload.ref.taskId);\n\t\t\tthis.notify();\n\t\t}\n\t\tif (event.payload.kind !== \"task-activity\") return;\n\t\tconst id = event.payload.ref.taskId;\n\t\tconst sequence = BigInt(event.cursor.sequence);\n\t\tif (sequence <= (this.activityCursors.get(id) ?? -1n)) return;\n\t\tthis.activityCursors.set(id, sequence);\n\t\tconst entries = this.activity.get(id) ?? [];\n\t\tentries.push({ cursor: event.cursor, report: event.payload.activity });\n\t\twhile (entries.length > TASK_ACTIVITY_LIMIT || Buffer.byteLength(JSON.stringify(entries)) > TASK_ACTIVITY_BYTES) {\n\t\t\tentries.shift();\n\t\t\tthis.omittedActivity.add(id);\n\t\t}\n\t\tthis.activity.set(id, entries);\n\t\tthis.notify();\n\t}\n\tprivate notify(): void {\n\t\tfor (const listener of this.listeners) listener();\n\t}\n}\n\n// Host adapters bind their existing session object, never a model-provided owner id.\nconst sessionStores = new WeakMap<object, OwnerTaskStore>();\nconst bindingListeners = new WeakMap<object, Set<() => void>>();\nexport function bindOwnerTaskStore(session: object, store: OwnerTaskStore): void {\n\tsessionStores.set(session, store);\n\tfor (const listener of bindingListeners.get(session) ?? []) listener();\n}\nexport function getOwnerTaskStore(session: object): OwnerTaskStore | undefined {\n\treturn sessionStores.get(session);\n}\n\n/** Observe lazy producer binding without waiting for another tool/session event. */\nexport function watchOwnerTaskStoreBinding(session: object, listener: () => void): () => void {\n\tlet listeners = bindingListeners.get(session);\n\tif (!listeners) {\n\t\tlisteners = new Set();\n\t\tbindingListeners.set(session, listeners);\n\t}\n\tlisteners.add(listener);\n\treturn () => {\n\t\tlisteners.delete(listener);\n\t};\n}\n"]}
1
+ {"version":3,"file":"owner-store.js","sourceRoot":"","sources":["../../../src/core/tasks/owner-store.ts"],"names":[],"mappings":"AAaA,oFAAoF;AACpF,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AACtC,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AASxC,SAAS,YAAY,CAAC,WAAkD;IACvE,4EAA4E;IAC5E,OAAO,WAAW,EAAE,IAAI,KAAK,YAAY,IAAI,WAAW,CAAC,MAAM,KAAK,cAAc,CAAC;AACpF,CAAC;AAED,qEAAqE;AACrE,MAAM,OAAO,cAAc;IAa1B,YAAY,UAA0B,EAAE,KAAiB;QAXjD,cAAS,GAAG,IAAI,GAAG,EAAc,CAAC;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\n\tActivityReport,\n\tCursor,\n\tNativeEvent,\n\tOwnerSnapshot,\n\tResult,\n\tTaskId,\n\tTaskRecord,\n\tWaitError,\n\tWatchError,\n} from \"./contracts.js\";\nimport type { OwnerLease, TaskLease, TaskSubscription, TaskSupervisor } from \"./supervisor.js\";\n\n/** Activity previews are bounded independently of authoritative session history. */\nexport const TASK_ACTIVITY_LIMIT = 64;\nexport const TASK_ACTIVITY_BYTES = 8192;\nexport type TaskAnchor = {\n\ttaskId: TaskId;\n\tactivitySequence: Cursor[\"sequence\"];\n\tcellOffset: number;\n\tfollowBottom: boolean;\n};\nexport type TaskActivity = { cursor: Cursor; report: ActivityReport };\n\nfunction isBackground(observation: TaskRecord[\"observation\"] | undefined): boolean {\n\t// Admission starts unobserved; that placeholder is not a background launch.\n\treturn observation?.kind === \"background\" && observation.reason !== \"not-observed\";\n}\n\n/** A view subscription owns neither the owner nor its executions. */\nexport class OwnerTaskStore {\n\tprivate subscription?: TaskSubscription;\n\tprivate listeners = new Set<() => void>();\n\tprivate records = new Map<TaskId, TaskRecord>();\n\tprivate activity = new Map<TaskId, TaskActivity[]>();\n\tprivate activityCursors = new Map<TaskId, bigint>();\n\tprivate omittedActivity = new Set<TaskId>();\n\tprivate backgroundIds = new Set<TaskId>();\n\tprivate settlements = new Map<TaskId, bigint>();\n\treadonly anchors = new Map<TaskId, TaskAnchor>();\n\tprivate current?: OwnerSnapshot;\n\treadonly supervisor: TaskSupervisor;\n\tprivate readonly owner: OwnerLease;\n\tconstructor(supervisor: TaskSupervisor, owner: OwnerLease) {\n\t\tthis.supervisor = supervisor;\n\t\tthis.owner = owner;\n\t}\n\n\tget snapshot(): OwnerSnapshot | undefined {\n\t\treturn this.current;\n\t}\n\tget cursor(): Cursor | undefined {\n\t\treturn this.current?.cursor;\n\t}\n\tget tasks(): TaskRecord[] {\n\t\treturn [...this.records.values()];\n\t}\n\t/** Background membership survives foreground waits and terminal observation cleanup. */\n\tget backgroundTasks(): TaskRecord[] {\n\t\treturn this.tasks.filter(\n\t\t\t(task) => task.wasBackground || isBackground(task.observation) || this.backgroundIds.has(task.ref.taskId),\n\t\t);\n\t}\n\t/**\n\t * Journal sequence at which each task settled; higher is more recent. Tasks first seen settled in a\n\t * snapshot without their settlement event share that snapshot's sequence, so their order is unknown.\n\t */\n\tget settlementOrder(): ReadonlyMap<TaskId, bigint> {\n\t\treturn this.settlements;\n\t}\n\t/** Resolve only within the owner that authorized this store. */\n\tresolveTask(id: TaskId): Result<TaskLease, WaitError> {\n\t\treturn this.supervisor.lookupTask(this.owner, id);\n\t}\n\trecentActivity(id: TaskId): TaskActivity[] {\n\t\treturn [...(this.activity.get(id) ?? [])];\n\t}\n\tactivityOmitted(id: TaskId): boolean {\n\t\treturn this.omittedActivity.has(id);\n\t}\n\tsubscribe(listener: () => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tconnect(): Result<void, WatchError> {\n\t\tthis.dispose();\n\t\tconst watched = this.supervisor.watchOwnerTasks(this.owner, this.cursor);\n\t\tif (!watched.ok) return watched;\n\t\tconst subscription = watched.value;\n\t\tthis.subscription = subscription;\n\t\tthis.reconcile(subscription.snapshot, []);\n\t\tsubscription.onReconcile = (snapshot, events) => this.reconcile(snapshot, events);\n\t\tvoid this.observe(subscription);\n\t\treturn { ok: true, value: undefined };\n\t}\n\t/** Useful at explicit host barriers; no transcript repaint timer is installed. */\n\tdrain(): void {\n\t\tthis.subscription?.drain();\n\t}\n\tdispose(): void {\n\t\tthis.subscription?.dispose();\n\t\tthis.subscription = undefined;\n\t}\n\tprivate reconcile(snapshot: OwnerSnapshot, events: readonly NativeEvent[]): void {\n\t\tif (\n\t\t\tthis.current &&\n\t\t\t(snapshot.ownerId !== this.current.ownerId || snapshot.generation !== this.current.generation)\n\t\t)\n\t\t\tthrow new Error(\"StaleGeneration: cannot replace a task owner projection\");\n\t\tif (this.current && BigInt(snapshot.cursor.sequence) <= BigInt(this.current.cursor.sequence)) return;\n\t\tthis.current = snapshot;\n\t\tfor (const event of events)\n\t\t\tif (event.payload.kind === \"task-settled\" && !this.settlements.has(event.payload.ref.taskId))\n\t\t\t\tthis.settlements.set(event.payload.ref.taskId, BigInt(event.cursor.sequence));\n\t\tfor (const task of snapshot.tasks) {\n\t\t\tconst previous = this.records.get(task.ref.taskId);\n\t\t\tif (isBackground(task.observation) || isBackground(previous?.observation))\n\t\t\t\tthis.backgroundIds.add(task.ref.taskId);\n\t\t\t// Native settlement is immutable, even when recovering a view from a snapshot.\n\t\t\tthis.records.set(\n\t\t\t\ttask.ref.taskId,\n\t\t\t\tprevious?.execution.kind === \"settled\" ? { ...task, execution: previous.execution } : task,\n\t\t\t);\n\t\t\tif (task.execution.kind === \"settled\" && !this.settlements.has(task.ref.taskId))\n\t\t\t\tthis.settlements.set(task.ref.taskId, BigInt(snapshot.cursor.sequence));\n\t\t\tif (!this.anchors.has(task.ref.taskId))\n\t\t\t\tthis.anchors.set(task.ref.taskId, {\n\t\t\t\t\ttaskId: task.ref.taskId,\n\t\t\t\t\tactivitySequence: snapshot.cursor.sequence,\n\t\t\t\t\tcellOffset: 0,\n\t\t\t\t\tfollowBottom: true,\n\t\t\t\t});\n\t\t}\n\t\tthis.notify();\n\t}\n\tprivate async observe(subscription: TaskSubscription): Promise<void> {\n\t\t// Journal overflow ends the old iterator after publishing a reset snapshot.\n\t\twhile (this.subscription === subscription && this.current?.state !== \"closed\") {\n\t\t\tfor await (const event of subscription.events) {\n\t\t\t\tif (this.subscription !== subscription) return;\n\t\t\t\tthis.retainActivity(event);\n\t\t\t}\n\t\t\tif (this.subscription !== subscription || this.snapshot?.state === \"closed\") return;\n\t\t\tawait new Promise<void>((resolve) => setImmediate(resolve));\n\t\t}\n\t}\n\tprivate retainActivity(event: NativeEvent): void {\n\t\tif (event.payload.kind === \"host-observation-changed\" && isBackground(event.payload.observation)) {\n\t\t\tthis.backgroundIds.add(event.payload.ref.taskId);\n\t\t\tthis.notify();\n\t\t}\n\t\tif (event.payload.kind !== \"task-activity\") return;\n\t\tconst id = event.payload.ref.taskId;\n\t\tconst sequence = BigInt(event.cursor.sequence);\n\t\tif (sequence <= (this.activityCursors.get(id) ?? -1n)) return;\n\t\tthis.activityCursors.set(id, sequence);\n\t\tconst entries = this.activity.get(id) ?? [];\n\t\tentries.push({ cursor: event.cursor, report: event.payload.activity });\n\t\twhile (entries.length > TASK_ACTIVITY_LIMIT || Buffer.byteLength(JSON.stringify(entries)) > TASK_ACTIVITY_BYTES) {\n\t\t\tentries.shift();\n\t\t\tthis.omittedActivity.add(id);\n\t\t}\n\t\tthis.activity.set(id, entries);\n\t\tthis.notify();\n\t}\n\tprivate notify(): void {\n\t\tfor (const listener of this.listeners) listener();\n\t}\n}\n\n// Host adapters bind their existing session object, never a model-provided owner id.\nconst sessionStores = new WeakMap<object, OwnerTaskStore>();\nconst bindingListeners = new WeakMap<object, Set<() => void>>();\nexport function bindOwnerTaskStore(session: object, store: OwnerTaskStore): void {\n\tsessionStores.set(session, store);\n\tfor (const listener of bindingListeners.get(session) ?? []) listener();\n}\nexport function getOwnerTaskStore(session: object): OwnerTaskStore | undefined {\n\treturn sessionStores.get(session);\n}\n\n/** Observe lazy producer binding without waiting for another tool/session event. */\nexport function watchOwnerTaskStoreBinding(session: object, listener: () => void): () => void {\n\tlet listeners = bindingListeners.get(session);\n\tif (!listeners) {\n\t\tlisteners = new Set();\n\t\tbindingListeners.set(session, listeners);\n\t}\n\tlisteners.add(listener);\n\treturn () => {\n\t\tlisteners.delete(listener);\n\t};\n}\n"]}
@@ -39,7 +39,7 @@ export async function cancelPausedOwnerTasks(host) {
39
39
  resolve();
40
40
  };
41
41
  watch.drain();
42
- watch.onReconcile(watch.snapshot);
42
+ watch.onReconcile(watch.snapshot, []);
43
43
  });
44
44
  }
45
45
  finally {
@@ -1 +1 @@
1
- {"version":3,"file":"pause.js","sourceRoot":"","sources":["../../../src/core/tasks/pause.ts"],"names":[],"mappings":"AAG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Q,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAChD,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAC5D,CAAC;gBACF,IAAI,QAAQ,CAAC,MAAM;oBAClB,MAAM,CACL,IAAI,KAAK,CACR,uCAAuC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACxH,CACD,CAAC;;oBACE,OAAO,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,KAAK,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;AACF,CAAC","sourcesContent":["import type { AgentTaskHost } from \"./agent-adapter.js\";\nimport type { OwnerSnapshot, TaskRecord } from \"./contracts.js\";\n\n/** The caller synchronously blocks new launches; this never closes the owner or its messages. */\nexport async function cancelPausedOwnerTasks(host: AgentTaskHost): Promise<void> {\n\tconst errors: Error[] = [];\n\tconst cancel = async (tasks: TaskRecord[]): Promise<void> => {\n\t\t// Cancel every queued agent before an active cancellation can free a dispatch slot.\n\t\tconst ordered = tasks.sort(\n\t\t\t(a, b) => Number(b.execution.kind === \"queued\") - Number(a.execution.kind === \"queued\"),\n\t\t);\n\t\tconst results = await Promise.allSettled(ordered.map((task) => host.cancelTask(task.ref.taskId, \"user\")));\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") errors.push(new Error(String(result.reason)));\n\t\t\telse if (!result.value.ok) errors.push(new Error(`${result.value.error.code}: ${result.value.error.message}`));\n\t\t}\n\t};\n\tconst watched = host.watchOwnerTasks();\n\tif (!watched.ok) throw new Error(`${watched.error.code}: ${watched.error.message}`);\n\tconst watch = watched.value;\n\ttry {\n\t\tawait cancel(watch.snapshot.tasks.filter((task) => task.kind === \"agent\" && task.execution.kind !== \"settled\"));\n\t\tconst { supervisor, owner } = host.ownerBinding;\n\t\t// Already-started native setup may briefly launch during the transition. Wait for\n\t\t// every admitted lease before cancelling shells and certifying the final snapshot.\n\t\tawait supervisor.drainCommandAdmissions(owner);\n\t\twatch.drain();\n\t\tawait cancel(watch.snapshot.tasks.filter((task) => task.kind === \"command\" && task.execution.kind !== \"settled\"));\n\t\tif (errors.length) throw new AggregateError(errors, \"Workflow stage task cancellation failed\");\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\twatch.onReconcile = (snapshot: OwnerSnapshot) => {\n\t\t\t\tif (\n\t\t\t\t\tsnapshot.tasks.some(\n\t\t\t\t\t\t(task) =>\n\t\t\t\t\t\t\ttask.cleanup.kind === \"active\" ||\n\t\t\t\t\t\t\ttask.cleanup.kind === \"draining\" ||\n\t\t\t\t\t\t\t(task.execution.kind !== \"settled\" && task.cleanup.kind !== \"failed\"),\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tconst failures = snapshot.tasks.flatMap((task) =>\n\t\t\t\t\ttask.cleanup.kind === \"failed\" ? task.cleanup.resources : [],\n\t\t\t\t);\n\t\t\t\tif (failures.length)\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`Workflow stage task cleanup failed: ${failures.map((failure) => `${failure.resource}: ${failure.message}`).join(\"; \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\telse resolve();\n\t\t\t};\n\t\t\twatch.drain();\n\t\t\twatch.onReconcile(watch.snapshot);\n\t\t});\n\t} finally {\n\t\twatch.dispose();\n\t}\n}\n"]}
1
+ {"version":3,"file":"pause.js","sourceRoot":"","sources":["../../../src/core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O;gBACR,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAChD,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAC5D,CAAC;gBACF,IAAI,QAAQ,CAAC,MAAM;oBAClB,MAAM,CACL,IAAI,KAAK,CACR,uCAAuC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACxH,CACD,CAAC;;oBACE,OAAO,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,KAAK,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;AACF,CAAC","sourcesContent":["import type { AgentTaskHost } from \"./agent-adapter.js\";\nimport type { OwnerSnapshot, TaskRecord } from \"./contracts.js\";\n\n/** The caller synchronously blocks new launches; this never closes the owner or its messages. */\nexport async function cancelPausedOwnerTasks(host: AgentTaskHost): Promise<void> {\n\tconst errors: Error[] = [];\n\tconst cancel = async (tasks: TaskRecord[]): Promise<void> => {\n\t\t// Cancel every queued agent before an active cancellation can free a dispatch slot.\n\t\tconst ordered = tasks.sort(\n\t\t\t(a, b) => Number(b.execution.kind === \"queued\") - Number(a.execution.kind === \"queued\"),\n\t\t);\n\t\tconst results = await Promise.allSettled(ordered.map((task) => host.cancelTask(task.ref.taskId, \"user\")));\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") errors.push(new Error(String(result.reason)));\n\t\t\telse if (!result.value.ok) errors.push(new Error(`${result.value.error.code}: ${result.value.error.message}`));\n\t\t}\n\t};\n\tconst watched = host.watchOwnerTasks();\n\tif (!watched.ok) throw new Error(`${watched.error.code}: ${watched.error.message}`);\n\tconst watch = watched.value;\n\ttry {\n\t\tawait cancel(watch.snapshot.tasks.filter((task) => task.kind === \"agent\" && task.execution.kind !== \"settled\"));\n\t\tconst { supervisor, owner } = host.ownerBinding;\n\t\t// Already-started native setup may briefly launch during the transition. Wait for\n\t\t// every admitted lease before cancelling shells and certifying the final snapshot.\n\t\tawait supervisor.drainCommandAdmissions(owner);\n\t\twatch.drain();\n\t\tawait cancel(watch.snapshot.tasks.filter((task) => task.kind === \"command\" && task.execution.kind !== \"settled\"));\n\t\tif (errors.length) throw new AggregateError(errors, \"Workflow stage task cancellation failed\");\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\twatch.onReconcile = (snapshot: OwnerSnapshot) => {\n\t\t\t\tif (\n\t\t\t\t\tsnapshot.tasks.some(\n\t\t\t\t\t\t(task) =>\n\t\t\t\t\t\t\ttask.cleanup.kind === \"active\" ||\n\t\t\t\t\t\t\ttask.cleanup.kind === \"draining\" ||\n\t\t\t\t\t\t\t(task.execution.kind !== \"settled\" && task.cleanup.kind !== \"failed\"),\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tconst failures = snapshot.tasks.flatMap((task) =>\n\t\t\t\t\ttask.cleanup.kind === \"failed\" ? task.cleanup.resources : [],\n\t\t\t\t);\n\t\t\t\tif (failures.length)\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`Workflow stage task cleanup failed: ${failures.map((failure) => `${failure.resource}: ${failure.message}`).join(\"; \")}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\telse resolve();\n\t\t\t};\n\t\t\twatch.drain();\n\t\t\twatch.onReconcile(watch.snapshot, []);\n\t\t});\n\t} finally {\n\t\twatch.dispose();\n\t}\n}\n"]}
@@ -69,10 +69,12 @@ export declare function taskTranscriptSource(task: TaskLease): C.Result<{
69
69
  session: TaskTranscriptSource;
70
70
  taskId: C.TaskId;
71
71
  }, C.Failure<"UnknownTask" | "TranscriptUnavailable">>;
72
+ /** History the runner produced; a forked child's inherited parent entries are excluded. */
73
+ export declare function taskOwnTranscriptEntries(task: TaskLease): ReturnType<TaskTranscriptSource["getEntries"]> | undefined;
72
74
  export declare class TaskSubscription {
73
75
  #private;
74
- /** Reconciliation supplements the RFC snapshot/cursor/iterable contract. */
75
- onReconcile: (snapshot: C.OwnerSnapshot) => void;
76
+ /** Reconciliation supplements the RFC snapshot/cursor/iterable contract with the events it applied. */
77
+ onReconcile: (snapshot: C.OwnerSnapshot, events: readonly C.NativeEvent[]) => void;
76
78
  readonly events: AsyncIterable<C.NativeEvent>;
77
79
  readonly lease: SubscriptionLease;
78
80
  constructor(actor: native.TaskSupervisor, initial: native.NativeTaskSubscription, onDispose: () => void);
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/supervisor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,MAAM,MAAM,yBAAyB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAElE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,KAAK,KAAK,CAAC,MAAM,gBAAgB,CAAC;AAEzC,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,cAAc,EAAE,cAAc,GAAG,YAAY,CAAC,GAAG;IACxF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACjD,6EAA6E;IAC7E,SAAS,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE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Unavailable", message: "Transcript unavailable" } };
65
65
  return { ok: true, value: { session: state.transcript, taskId: state.ref.taskId } };
66
66
  }
67
+ /** History the runner produced; a forked child's inherited parent entries are excluded. */
68
+ export function taskOwnTranscriptEntries(task) {
69
+ const state = environment.tasks.get(task);
70
+ return state?.transcript?.getEntries().slice(state.inheritedEntryCount ?? 0);
71
+ }
67
72
  /** Promise rejections, setup throws and consumer exceptions may be arbitrary JavaScript values. */
68
73
  function rejectionMessage(reason) {
69
74
  try {
@@ -392,7 +397,7 @@ export class TaskSubscription {
392
397
  this.#queue = [];
393
398
  this.#epoch = 0;
394
399
  this.#disposed = false;
395
- /** Reconciliation supplements the RFC snapshot/cursor/iterable contract. */
400
+ /** Reconciliation supplements the RFC snapshot/cursor/iterable contract with the events it applied. */
396
401
  this.onReconcile = () => { };
397
402
  this.lease = new SubscriptionCapability();
398
403
  Object.freeze(this.lease);
@@ -482,7 +487,7 @@ export class TaskSubscription {
482
487
  }
483
488
  if (drained.value.snapshot || events.length) {
484
489
  try {
485
- this.#resource.runInAsyncScope(this.onReconcile, undefined, this.#snapshot);
490
+ this.#resource.runInAsyncScope(this.onReconcile, undefined, this.#snapshot, events);
486
491
  }
487
492
  catch (error) {
488
493
  this.#failure = new Error(rejectionMessage(error));
@@ -604,7 +609,7 @@ export class TaskSupervisor {
604
609
  if (failure)
605
610
  throw failure;
606
611
  };
607
- watched.value.onReconcile(watched.value.snapshot);
612
+ watched.value.onReconcile(watched.value.snapshot, []);
608
613
  return owner;
609
614
  }, ownerErrors);
610
615
  }
@@ -723,6 +728,7 @@ export class TaskSupervisor {
723
728
  ref: reference(taskState.ref),
724
729
  signal: taskState.controller.signal,
725
730
  bindTranscript: (session) => {
731
+ taskState.inheritedEntryCount ??= session.getEntries().length;
726
732
  taskState.transcript = session;
727
733
  },
728
734
  reportActivity: (report) => mapped(this.#native.reportTaskActivity(runner.value, report), reportReceipt, reportErrors),