toolroll 0.9.133 → 0.9.135

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 (377) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/acp-agents.js +1 -1
  3. package/dist/acp-check-repo-schema.js +52 -0
  4. package/dist/acp-check.js +1 -1
  5. package/dist/acp-client.js +3 -3
  6. package/dist/acp-inspect.js +2 -1
  7. package/dist/acp-providers-schema.js +1 -1
  8. package/dist/agent-detect.js +1 -1
  9. package/dist/agent-fence.js +4 -4
  10. package/dist/agent-handoff.js +11 -0
  11. package/dist/agent-thread/acp-chat.js +1 -0
  12. package/dist/agent-thread/acp-turn.js +4 -0
  13. package/dist/agent-thread/chat-credential.js +1 -0
  14. package/dist/agent-thread/chat-home.js +1 -0
  15. package/dist/agent-thread/chat-spend.js +7 -0
  16. package/dist/agent-thread/chat-tools.js +1 -0
  17. package/dist/agent-thread/chat-turn.js +4 -0
  18. package/dist/agent-thread/custody.js +1 -1
  19. package/dist/agent-thread/direct-host.js +13 -8
  20. package/dist/agent-thread/fence.js +2 -2
  21. package/dist/agent-thread/gemini-chat.js +1 -0
  22. package/dist/agent-thread/git-workspace.js +3 -3
  23. package/dist/agent-thread/guards.js +1 -1
  24. package/dist/agent-thread/openrouter-chat.js +1 -0
  25. package/dist/agent-thread/providers.js +3 -3
  26. package/dist/agent-thread/ship.js +2 -2
  27. package/dist/agentconfig.js +1 -1
  28. package/dist/agents-live.js +2 -2
  29. package/dist/approval-decision.js +1 -0
  30. package/dist/approval-password.js +1 -1
  31. package/dist/approval-summary.js +1 -1
  32. package/dist/assignment.js +1 -1
  33. package/dist/attest.js +1 -1
  34. package/dist/batch-checks.js +2 -2
  35. package/dist/boot-identity.js +1 -1
  36. package/dist/bounded-spawn.js +2 -2
  37. package/dist/brief-fence.js +3 -1
  38. package/dist/browser/{chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +5 -5
  39. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.br +0 -0
  40. package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.gz +0 -0
  41. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js +2 -0
  42. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.br +0 -0
  43. package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.gz +0 -0
  44. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js +4 -0
  45. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.br +0 -0
  46. package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.gz +0 -0
  47. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js +116 -0
  48. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.br +0 -0
  49. package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.gz +0 -0
  50. package/dist/browser/{chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js → chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js} +7 -7
  51. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.br +0 -0
  52. package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.gz +0 -0
  53. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js +4 -0
  54. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.br +0 -0
  55. package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.gz +0 -0
  56. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js +6 -0
  57. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.br +0 -0
  58. package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.gz +0 -0
  59. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js +2 -0
  60. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.br +0 -0
  61. package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.gz +0 -0
  62. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js +20 -0
  63. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.br +0 -0
  64. package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.gz +0 -0
  65. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js +3 -0
  66. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.br +0 -0
  67. package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.gz +0 -0
  68. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js +2 -0
  69. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.br +0 -0
  70. package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.gz +0 -0
  71. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js +2 -0
  72. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.br +0 -0
  73. package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.gz +0 -0
  74. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js +5 -0
  75. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.br +0 -0
  76. package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.gz +0 -0
  77. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js +2 -0
  78. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.br +0 -0
  79. package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.gz +0 -0
  80. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js +2 -0
  81. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.br +0 -0
  82. package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.gz +0 -0
  83. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js +2 -0
  84. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.br +0 -0
  85. package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.gz +0 -0
  86. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js +4 -0
  87. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.br +0 -0
  88. package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.gz +0 -0
  89. package/dist/browser/{chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js → chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js} +1 -1
  90. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.br +0 -0
  91. package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.gz +0 -0
  92. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js +2 -0
  93. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.br +0 -0
  94. package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.gz +0 -0
  95. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js +2 -0
  96. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.br +0 -0
  97. package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.gz +0 -0
  98. package/dist/browser/manifest.json +204 -204
  99. package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js} +1 -1
  100. package/dist/browser/terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.br +0 -0
  101. package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.gz → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.gz} +0 -0
  102. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css +4 -0
  103. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.br +0 -0
  104. package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.gz +0 -0
  105. package/dist/browser/{workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js → workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js} +4 -4
  106. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.br +0 -0
  107. package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.gz +0 -0
  108. package/dist/browser-open.js +1 -1
  109. package/dist/build-review.js +2 -2
  110. package/dist/builder-revision.js +4 -0
  111. package/dist/builder.js +31 -17
  112. package/dist/canvas-capture.js +2 -2
  113. package/dist/canvas-freshness.js +1 -1
  114. package/dist/central-recovery-stage.js +1 -1
  115. package/dist/chat-actions.js +11 -7
  116. package/dist/chat-channel.js +1 -1
  117. package/dist/chat-decide.js +8 -4
  118. package/dist/chat-review.js +1 -1
  119. package/dist/chat-terms.js +2 -2
  120. package/dist/check-levels.js +1 -1
  121. package/dist/cli-help.js +142 -13
  122. package/dist/cli.js +4 -3
  123. package/dist/companion/bonjour.js +1 -1
  124. package/dist/companion/daemon.js +1 -1
  125. package/dist/companion/passkey-gate.js +1 -1
  126. package/dist/companion/reads.js +1 -1
  127. package/dist/companion/store.js +1 -1
  128. package/dist/companion/webauthn.js +1 -1
  129. package/dist/companion/work.js +1 -1
  130. package/dist/container-state.js +2 -2
  131. package/dist/containment.js +2 -2
  132. package/dist/contracts/chat-actions.js +1 -1
  133. package/dist/contracts/console-api.js +1 -1
  134. package/dist/contracts/engine-api.js +1 -1
  135. package/dist/contracts/lead-tools.js +1 -1
  136. package/dist/contracts/project-memory.js +1 -1
  137. package/dist/contracts/provider.js +1 -1
  138. package/dist/controller-supervisor.js +2 -2
  139. package/dist/converse.js +1 -1
  140. package/dist/credential-broker.js +1 -1
  141. package/dist/decision.js +1 -1
  142. package/dist/demo.js +2 -2
  143. package/dist/dispatch.js +2 -2
  144. package/dist/dispose.js +1 -1
  145. package/dist/easy-start.js +2 -2
  146. package/dist/egress.js +1 -1
  147. package/dist/engine-chat.js +1 -1
  148. package/dist/engine-handoff.js +1 -1
  149. package/dist/engine-reads.js +3 -3
  150. package/dist/evals.js +2 -2
  151. package/dist/every-agent-schema.js +105 -0
  152. package/dist/evidence-pack.js +1 -1
  153. package/dist/evidence.js +1 -1
  154. package/dist/exec.js +5 -4
  155. package/dist/fallback.js +1 -1
  156. package/dist/fast-owner-schema.js +33 -0
  157. package/dist/fast-start.js +1 -1
  158. package/dist/flow-unattended.js +2 -2
  159. package/dist/git-identity.js +2 -2
  160. package/dist/github-import.js +1 -1
  161. package/dist/github-read.js +1 -1
  162. package/dist/handoff-relay.js +2 -0
  163. package/dist/install-mode.js +2 -3
  164. package/dist/invoke.js +9 -7
  165. package/dist/keys.js +1 -1
  166. package/dist/laptop-background.js +1 -1
  167. package/dist/lead-capabilities.js +1 -1
  168. package/dist/lead-cli.js +2 -2
  169. package/dist/lead-contract.js +1 -1
  170. package/dist/lead-debrief.js +7 -0
  171. package/dist/lead-doors.js +1 -1
  172. package/dist/lead-tools.js +5 -5
  173. package/dist/lead.js +2 -2
  174. package/dist/live-backup-change.js +2 -2
  175. package/dist/live-backup.js +2 -2
  176. package/dist/live-records.js +3 -3
  177. package/dist/live-terminal.js +4 -4
  178. package/dist/local-checks.js +1 -1
  179. package/dist/local-landing.js +22 -3
  180. package/dist/local-owner-acts.js +2 -2
  181. package/dist/local-owner.js +1 -1
  182. package/dist/machine-identity.js +1 -1
  183. package/dist/memory-pass.js +3 -3
  184. package/dist/model-catalog.js +8 -5
  185. package/dist/model-choices.js +3 -3
  186. package/dist/model-routing.js +1 -1
  187. package/dist/models-cli.js +2 -2
  188. package/dist/names.js +1 -1
  189. package/dist/needs-you.js +1 -1
  190. package/dist/onboard.js +1 -1
  191. package/dist/openrouter-key.js +2 -0
  192. package/dist/operate-commands.js +1 -1
  193. package/dist/operate-remote-arguments.js +1 -1
  194. package/dist/operate-remote.js +1 -1
  195. package/dist/operate.js +46 -19
  196. package/dist/orphan-sweep.js +1 -1
  197. package/dist/owner-mode.js +4 -0
  198. package/dist/panels.js +6 -0
  199. package/dist/peek-cli.js +2 -2
  200. package/dist/phase-routing.js +1 -1
  201. package/dist/pi-build.js +4 -0
  202. package/dist/pi-rpc.js +10 -0
  203. package/dist/pi-tools-extension.js +4 -0
  204. package/dist/plan-login.js +2 -2
  205. package/dist/plane-review.js +1 -1
  206. package/dist/planner-source.js +2 -2
  207. package/dist/planner.js +2 -2
  208. package/dist/plugin-bundle-source.js +1 -0
  209. package/dist/plugin-bundles-schema.js +43 -0
  210. package/dist/policy.js +1 -1
  211. package/dist/pre-run-phase.js +2 -0
  212. package/dist/presence-hold.js +1 -1
  213. package/dist/process-liveness.js +1 -1
  214. package/dist/process-tree.js +1 -1
  215. package/dist/project-knowledge.js +2 -2
  216. package/dist/project-learning.js +6 -5
  217. package/dist/project-memory.js +1 -1
  218. package/dist/project-skills.js +1 -1
  219. package/dist/project-tools.js +3 -3
  220. package/dist/prompt.js +1 -1
  221. package/dist/proposal.js +1 -1
  222. package/dist/protected-storage.js +2 -2
  223. package/dist/provider-auth.js +1 -1
  224. package/dist/provider-connection.js +2 -2
  225. package/dist/provider-home.js +1 -1
  226. package/dist/provider-limits.js +1 -1
  227. package/dist/provider.js +2 -2
  228. package/dist/public-access.js +1 -1
  229. package/dist/pull-request-flow.js +2 -2
  230. package/dist/read-executor.js +1 -1
  231. package/dist/release-adapters.js +2 -2
  232. package/dist/release-carry.js +3 -3
  233. package/dist/release-resume.js +2 -2
  234. package/dist/release-start.js +1 -0
  235. package/dist/reported-usage.js +1 -1
  236. package/dist/repository-context.js +1 -1
  237. package/dist/result-follow-ups.js +2 -2
  238. package/dist/result-projection.js +1 -1
  239. package/dist/review-switch.js +1 -1
  240. package/dist/route-change.js +25 -3
  241. package/dist/run-closeout.js +2 -2
  242. package/dist/runner.js +2 -2
  243. package/dist/sandbox-launch.js +2 -2
  244. package/dist/sandbox-runtime.js +1 -1
  245. package/dist/scope.js +1 -1
  246. package/dist/scout-browser.js +1 -1
  247. package/dist/scout.js +2 -2
  248. package/dist/serve.js +3 -3
  249. package/dist/server/chat-projection.js +1 -1
  250. package/dist/server/chat.js +3 -3
  251. package/dist/server/direct-chat.js +1 -1
  252. package/dist/server/engine-api.js +1 -1
  253. package/dist/server/handoff.js +1 -0
  254. package/dist/server/http.js +1 -1
  255. package/dist/server/live.js +1 -1
  256. package/dist/server/merge-ready-view.js +1 -1
  257. package/dist/server/one-time-secret.js +1 -1
  258. package/dist/server/panels.js +1 -0
  259. package/dist/server/people-tokens.js +1 -1
  260. package/dist/server/route-table.js +1 -1
  261. package/dist/server/runtime.js +1 -1
  262. package/dist/server/send-back-build.js +1 -1
  263. package/dist/server/settings-phone.js +1 -1
  264. package/dist/server/settings-section-table.js +1 -1
  265. package/dist/server/settings-sections.js +1 -1
  266. package/dist/server/settings.js +3 -2
  267. package/dist/server/task-overview.js +1 -0
  268. package/dist/server/task-view-data.js +3 -3
  269. package/dist/server/task-views.js +1 -1
  270. package/dist/server/tasks.js +6 -6
  271. package/dist/server/terminals.js +1 -1
  272. package/dist/settings-data.js +1 -1
  273. package/dist/settings-proofs.js +1 -1
  274. package/dist/setup-guide.js +1 -1
  275. package/dist/shared-deps.js +4 -4
  276. package/dist/sign-in-page.js +2 -2
  277. package/dist/skill-library.js +13 -22
  278. package/dist/skills-manifest.js +1 -1
  279. package/dist/spend-report.js +2 -1
  280. package/dist/spend.js +6 -4
  281. package/dist/ssr-workspace.js +89 -89
  282. package/dist/staged-runtimes.js +1 -1
  283. package/dist/status-probe.js +2 -2
  284. package/dist/stop-proof.js +2 -2
  285. package/dist/storage-sweep-child.js +2 -2
  286. package/dist/storage-sweep-process.js +1 -1
  287. package/dist/storage.js +2 -2
  288. package/dist/store-baseline.js +17 -79
  289. package/dist/store.js +24 -19
  290. package/dist/structured-json.js +1 -0
  291. package/dist/structured-output.js +1 -1
  292. package/dist/subscription-chat.js +16 -4
  293. package/dist/subscription-usage.js +3 -4
  294. package/dist/surface.js +1 -1
  295. package/dist/task-outcome-cli.js +5 -2
  296. package/dist/task-overview.js +1 -0
  297. package/dist/task-review-brief.js +1 -1
  298. package/dist/task-status.js +1 -1
  299. package/dist/teardown-git.js +4 -4
  300. package/dist/test-temp.js +1 -1
  301. package/dist/text-limits.js +1 -1
  302. package/dist/tool-broker.js +1 -1
  303. package/dist/toolroll-update.js +3 -3
  304. package/dist/trusted-path.js +1 -1
  305. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  306. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  307. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  308. package/dist/tui/linux-x64/toolroll-tui +0 -0
  309. package/dist/tui-contract.js +1 -1
  310. package/dist/tui-launch.js +2 -1
  311. package/dist/verification-evidence.js +1 -1
  312. package/dist/welcome-facts.js +1 -1
  313. package/dist/work-index.js +13 -5
  314. package/package.json +2 -1
  315. package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.br +0 -0
  316. package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.gz +0 -0
  317. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js +0 -2
  318. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.br +0 -0
  319. package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.gz +0 -0
  320. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js +0 -4
  321. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.br +0 -0
  322. package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.gz +0 -0
  323. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js +0 -116
  324. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.br +0 -0
  325. package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.gz +0 -0
  326. package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.br +0 -0
  327. package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.gz +0 -0
  328. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js +0 -4
  329. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.br +0 -0
  330. package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.gz +0 -0
  331. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js +0 -6
  332. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.br +0 -0
  333. package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.gz +0 -0
  334. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js +0 -2
  335. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.br +0 -0
  336. package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.gz +0 -0
  337. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js +0 -20
  338. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.br +0 -0
  339. package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.gz +0 -0
  340. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js +0 -3
  341. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.br +0 -0
  342. package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.gz +0 -0
  343. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js +0 -2
  344. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.br +0 -0
  345. package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.gz +0 -0
  346. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js +0 -5
  347. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.br +0 -0
  348. package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.gz +0 -0
  349. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js +0 -2
  350. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.br +0 -0
  351. package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.gz +0 -0
  352. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js +0 -2
  353. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.br +0 -0
  354. package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.gz +0 -0
  355. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js +0 -2
  356. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.br +0 -0
  357. package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.gz +0 -0
  358. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js +0 -2
  359. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.br +0 -0
  360. package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.gz +0 -0
  361. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js +0 -4
  362. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.br +0 -0
  363. package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.gz +0 -0
  364. package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.br +0 -0
  365. package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.gz +0 -0
  366. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js +0 -2
  367. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.br +0 -0
  368. package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.gz +0 -0
  369. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js +0 -2
  370. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.br +0 -0
  371. package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.gz +0 -0
  372. package/dist/browser/terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.br +0 -0
  373. package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.br +0 -0
  374. package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.gz +0 -0
  375. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css +0 -4
  376. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.br +0 -0
  377. package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.gz +0 -0
@@ -1,2 +1,2 @@
1
- import{createHash}from"node:crypto";import{z}from"zod";import{chatCardSchema}from"./chat-card.js";import{parseContract}from"./contract.js";export const ENGINE_API_VERSION=1;const version=z.literal(ENGINE_API_VERSION),iso=z.string(),liveRecordSchema=z.union([z.object({k:z.literal("open"),at:iso,detail:z.enum(["base","commands"]),s:z.number().int().optional()}),z.object({k:z.literal("start"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("say"),at:iso,t:z.array(z.string()),s:z.number().int().optional()}),z.object({k:z.literal("you"),at:iso,t:z.array(z.string())}),z.object({k:z.literal("step"),at:iso,id:z.string(),kind:z.string(),target:z.string().optional(),once:z.literal(!0).optional(),s:z.number().int().optional()}),z.object({k:z.literal("done"),at:iso,id:z.string(),ok:z.boolean().nullable(),out:z.array(z.string()).optional(),s:z.number().int().optional()}),z.object({k:z.literal("cut"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("cap"),at:iso.optional(),s:z.number().int().optional()}),z.object({k:z.literal("child"),s:z.number().int(),at:iso.optional(),parent:z.string().nullable(),via:z.number().int().optional(),desc:z.string().optional()}),z.object({k:z.literal("end"),s:z.number().int(),at:iso.optional(),ok:z.boolean().nullable()}),z.object({k:z.literal("over")})]);export const liveSessionRefSchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("run"),id:z.number().int().positive(),task:z.string().nullable()}),z.object({kind:z.literal("thread"),id:z.string().regex(/^[0-9a-f]{32}$/),task:z.null()})]);const hex32=z.string().regex(/^[0-9a-f]{32}$/),flexibleLevelSchema=z.enum(["supervised","auto","full"]),answerStateSchema=z.enum(["pending","decided","sending","sent","delivered","not-sent","uncertain","withdrawn"]),threadQuestionSchema=z.object({request:hex32,kind:z.enum(["permission","question"]),title:z.string(),detail:z.string().nullable(),tool:z.string().nullable(),complete:z.boolean(),digest:z.string().regex(/^[0-9a-f]{64}$/),state:answerStateSchema,answerable:z.boolean(),parts:z.array(z.object({id:z.string(),question:z.string(),options:z.array(z.string())}))});export const threadTerminalSchema=z.strictObject({available:z.boolean(),launch:hex32,generation:z.number().int().positive(),lifecycle:z.enum(["starting","live","stopping","exited","unresolved"]),viewing:z.enum(["detached","viewing"]),control:z.enum(["none","self","other"]),protocol:z.literal(1),cols:z.number().int().min(2).max(500),rows:z.number().int().min(2).max(500)}),threadFactsSchema=z.object({version:z.string().regex(/^[0-9a-f]{16}$/),title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),agent:z.object({provider:z.string(),model:z.string()}).nullable(),turn:z.object({seq:z.number().int(),status:z.string(),costUsd:z.number().nullable(),costBasis:z.enum(["measured","estimated","unknown"]).nullable(),endWords:z.string().optional(),billing:z.enum(["subscription","api-key"]).optional()}).nullable(),questions:z.array(threadQuestionSchema),runtime:z.enum(["stream-json","interactive"]).optional(),terminal:threadTerminalSchema.optional(),ended:z.object({words:z.string(),stopPending:z.boolean()}).optional(),ship:z.object({seq:z.number().int(),state:z.string(),words:z.string()}).optional()}),liveSessionWindowSchema=z.object({version,session:liveSessionRefSchema,room:z.string(),live:z.boolean(),file:z.enum(["main","sub"]),window:z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),records:z.array(liveRecordSchema),cursor:z.string(),restarted:z.boolean(),earlier:z.boolean(),quarantined:z.number().int(),skipped:z.number().int(),more:z.boolean()}),z.object({ok:z.literal(!1),reason:z.enum(["missing","unavailable","off"])})]),thread:threadFactsSchema.optional()}),liveThreadsSchema=z.object({version,on:z.boolean().optional(),threads:z.array(z.object({id:hex32,title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),live:z.boolean(),waiting:z.number().int(),costUsd:z.number().nullable(),turn:z.string().nullable(),ended:z.boolean(),stopPending:z.boolean(),ship:z.string().nullable(),turnSeq:z.number().int().nullable(),shipSeq:z.number().int().nullable()}))});const workAskSchema=z.enum(["release","approve","answer","flow","wrong","review","setup","other"]),needRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),at:iso.optional(),state:z.enum(["needs","running","queued","done"]),ask:workAskSchema.nullable(),group:z.enum(["decide","review","unblock"]).optional(),reason:z.string().nullable(),line:z.string().nullable(),action:z.object({label:z.string(),href:z.string()}).nullable(),question:z.object({id:z.number().int(),text:z.string(),recap:z.string(),options:z.array(z.object({id:z.string(),label:z.string(),consequence:z.string(),recommended:z.boolean()}))}).nullable()});export const waitingSchema=z.object({retryAt:iso.nullable(),lastFailure:z.string().nullable(),attempt:z.enum(["build","plan"])}),WORK_ROW_GROUPS=["decide","review","unblock","building","rest"],WORK_STATUS_TONES=["attention","problem","live","ready","done","muted","neutral"],WORK_WORD_TONES=["","needs","ask","live","done","failed"];const workRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),status:z.object({label:z.string(),tone:z.enum(WORK_STATUS_TONES),token:z.string()}),word:z.object({word:z.string(),tone:z.enum(WORK_WORD_TONES)}),ask:z.string().nullable(),chip:z.string().nullable(),group:z.enum(WORK_ROW_GROUPS),rank:z.number().int(),check:z.enum(["failed","stale","unreadable"]).optional(),landed:z.string().optional(),detail:z.string().nullable(),problem:z.string().nullable(),need:needRowSchema.nullable(),waiting:waitingSchema.nullable()});export const workRowsSchema=z.object({version,project:z.string().nullable(),projectName:z.string(),needsCount:z.number().int(),groups:z.array(z.object({key:z.string(),label:z.string(),count:z.number().int()})).nullable(),rows:z.array(workRowSchema),needs:z.array(z.object({key:z.enum(["decide","review","unblock"]),label:z.string(),count:z.number().int(),rows:z.array(needRowSchema)})),next:z.string().nullable(),room:z.literal("workspace"),spend:z.object({todayUsd:z.number(),planPercent:z.number().int().nullable()}).nullable(),limits:z.array(z.object({provider:z.string(),plan:z.string().nullable(),window:z.string(),usedPercent:z.number(),reached:z.boolean(),resetsAt:z.string().nullable(),observedAt:z.string()})).nullable()}),stepCardSchema=z.object({key:z.enum(["plan","approve","build","checks","review","ready"]),label:z.string(),state:z.enum(["done","current","stuck","skipped","todo"]),mark:z.enum(["done","needs","live","wait","stuck","skipped","todo"]),sentence:z.string(),at:iso.nullable(),needsYou:z.boolean(),inChain:z.boolean(),agent:z.object({provider:z.string(),model:z.string().nullable()}).nullable(),startedAt:iso.nullable(),latestStartedAt:iso.nullable(),finishedAt:iso.nullable(),costUsd:z.number().nullable(),runs:z.array(z.number().int()),terms:z.object({key:z.string(),revision:z.string().nullable(),rows:z.array(z.object({label:z.string(),words:z.string(),lines:z.array(z.string())})),warnings:z.array(z.string()),usualLabel:z.string(),usual:z.array(z.object({label:z.string(),words:z.string()}))}).optional()}),stepCardsSchema=z.object({version,task:z.object({id:z.string(),root:z.string(),title:z.string(),state:z.string(),project:z.string().nullable()}),chain:z.enum(["plan-first","just-code"]),headline:z.string().nullable(),liveRun:z.number().int().nullable(),latestRun:z.number().int().nullable(),familyBuilds:z.array(z.number().int()).optional(),models:z.array(z.object({phase:z.string(),provider:z.string(),model:z.string(),chosen:z.enum(["recommended","override","pinned"])})).nullable(),cards:z.array(stepCardSchema).nullable(),review:z.object({run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),accept:z.object({owed:z.enum(["person-check","exception"]).nullable(),blockers:z.array(z.string()),needs:z.string().nullable()})}).nullable(),shell:z.object({run:z.number().int(),why:z.string().nullable()}).nullable(),failure:z.object({line:z.string(),failedInARow:z.number().int(),suggestion:z.string().nullable(),agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),waiting:waitingSchema.extend({agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),held:z.object({id:z.number().int(),reason:z.string(),lastFailure:z.string().nullable()}).nullable(),retry:z.object({run:z.number().int(),digest:z.string()}).nullable(),planStopped:z.object({incident:z.number().int(),kind:z.enum(["plan","question","stalled"]),line:z.string(),problems:z.array(z.string()).max(8).nullable(),agentSaid:z.array(z.string()).max(8).nullable(),again:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable()}).nullable(),plan:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable(),planQueued:z.boolean(),approval:z.object({by:z.string(),you:z.boolean(),automatic:z.boolean()}).nullable(),scopeDigest:z.string().nullable(),agentChoices:z.object({plan:z.array(z.object({provider:z.string(),model:z.string()})),build:z.array(z.object({provider:z.string(),model:z.string()}))}).nullable(),pendingAgentChange:z.object({phase:z.enum(["plan","build"]),provider:z.string(),model:z.string(),when:z.enum(["next-run","restart"]),by:z.string(),at:z.string(),problem:z.string().nullable()}).nullable(),landing:z.object({words:z.string(),reverted:z.boolean()}).nullable(),check:z.enum(["failed","stale","unreadable"]).optional(),runChecks:z.object({run:z.number().int(),level:z.enum(["quick","full"])}).optional(),behindMain:z.object({run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),main:z.string(),behind:z.number().int(),note:z.string()}).optional(),room:z.string()}),approvalCardSchema=z.object({version,task:z.string(),key:z.string().nullable(),digest:z.string().regex(/^[0-9a-f]{64}$/).nullable(),nonce:z.string().regex(/^[0-9a-f]{32}$/).nullable(),terms:z.array(z.object({label:z.string(),words:z.string()})),problem:z.string().nullable()});const diffProblemSchema=z.string().nullable();export const resultDiffSchema=z.object({version,task:z.string(),run:z.number().int().nullable(),totals:z.object({files:z.number().int(),additions:z.number().int(),deletions:z.number().int(),binary:z.number().int(),filesTruncated:z.boolean()}).nullable(),files:z.array(z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),additions:z.number().int(),deletions:z.number().int(),binary:z.boolean(),hunks:z.number().int()})),patchTruncated:z.boolean(),problem:diffProblemSchema});const diffLineSchema=z.object({kind:z.enum(["context","addition","deletion","meta"]),text:z.string(),oldLine:z.number().int().nullable(),newLine:z.number().int().nullable()});export const resultDiffFileSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),meta:z.array(z.string()),hunks:z.array(z.object({header:z.string(),lines:z.array(diffLineSchema)})),lineCount:z.number().int().nonnegative().nullable()}),linesTruncated:z.boolean()}),DIFF_CONTEXT_MAX=100,resultDiffContextSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.number().int(),from:z.number().int(),lines:z.array(z.object({newLine:z.number().int(),text:z.string()})),lineCount:z.number().int().nullable(),problem:z.string().nullable()}),agentsReadSchema=z.object({version,checkedAt:iso.nullable(),agents:z.array(z.object({id:z.string(),name:z.string(),state:z.enum(["signed-in","signed-out","unknown","not-installed"]),how:z.string().nullable(),signIn:z.string().nullable(),ready:z.boolean(),next:z.string().nullable(),setup:z.object({install:z.string().nullable(),canInstall:z.boolean(),signIn:z.string().nullable(),canSignIn:z.boolean(),key:z.string().nullable(),check:z.string().nullable(),note:z.string().nullable(),registry:z.string().nullable(),registryUnsure:z.boolean()})})),firstTask:z.object({id:z.string(),name:z.string()}).nullable(),lines:z.array(z.string())}),modelsReadSchema=z.object({version,canChange:z.boolean(),digest:z.string(),problem:z.string().nullable(),roles:z.array(z.object({key:z.enum(["plan","build","review"]),label:z.string(),current:z.string(),words:z.string(),choices:z.array(z.object({provider:z.string(),label:z.string(),models:z.array(z.object({value:z.string(),label:z.string()}))}))})),defaultAgent:z.string().nullable(),presets:z.array(z.object({agent:z.string(),name:z.string(),words:z.string(),fields:z.record(z.string(),z.string())}))}),termStateSchema=z.object({available:z.boolean(),problem:z.string().nullable(),programs:z.array(z.enum(["claude","codex","antigravity","shell"])),projects:z.array(z.object({path:z.string(),name:z.string()})),sessions:z.array(z.object({id:z.string().regex(/^[0-9a-f]{32}$/),repo:z.string(),project:z.string(),program:z.enum(["claude","codex","antigravity","shell"]),branch:z.string(),startedAt:iso,endedAt:iso.nullable(),exit:z.object({code:z.number().int().nullable(),signal:z.number().int().nullable()}).nullable(),cleanup:z.enum(["clean","uncertain"]).nullable(),task:z.string().nullable(),run:z.number().int().nullable()}))}),termStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),id:z.string().regex(/^[0-9a-f]{32}$/)}),z.object({ok:z.literal(!1),error:z.string()})]);const leadLinkSchema=z.object({label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()}),leadCardPrimarySchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("confirm"),label:z.string(),irreversible:z.boolean(),native:z.boolean()}),z.object({kind:z.literal("link"),label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()})]);export const leadChatCardSchema=z.object({id:z.number().int(),kind:z.string(),label:z.string(),state:z.enum(["pending","confirmed","refused","dismissed","expired"]),data:z.boolean(),lines:z.array(z.string()),card:chatCardSchema.nullable(),said:z.string().nullable(),note:z.string().nullable(),primary:leadCardPrimarySchema.nullable(),dismissable:z.boolean(),links:z.array(leadLinkSchema)});const leadAskSchema=z.object({turn:z.number().int(),question:z.string(),options:z.array(z.string()),open:z.boolean(),stale:z.boolean()}),leadMessageSchema=z.object({id:z.number().int(),role:z.enum(["operator","assistant"]),text:z.string(),activity:z.string().nullable(),createdAt:iso,cards:z.array(leadChatCardSchema),ask:leadAskSchema.nullable()}),leadQueuedSchema=z.object({id:z.number().int(),text:z.string(),status:z.enum(["queued","starting","cancelled","failed","uncertain"]),detail:z.string().nullable()});export const leadChatSchema=z.object({version,room:z.string(),session:z.number().int().nullable(),leadName:z.string(),canSend:z.boolean(),problem:z.string().nullable(),project:z.string().nullable(),busy:z.boolean(),pendingProposals:z.number().int(),queued:z.array(leadQueuedSchema),messages:z.array(leadMessageSchema)});const automationTriggerSchema=z.object({id:z.number().int(),kind:z.string(),words:z.string(),state:z.enum(["active","paused"]),nextAt:iso.nullable(),lastAt:iso.nullable(),lastOutcome:z.string().max(200).nullable(),failures:z.number().int(),canPress:z.boolean(),canCheck:z.boolean(),label:z.string().nullable(),questions:z.array(z.string()).nullable(),resumeRunsNow:z.boolean()});export const automationsSchema=z.object({version,canAct:z.boolean(),automations:z.array(z.object({id:z.number().int(),name:z.string(),project:z.string().nullable(),group:z.enum(["needs","running","on","paused"]),starts:z.string(),nextAt:iso.nullable(),waiting:z.number().int(),inProgress:z.number().int(),trouble:z.string().nullable(),triggers:z.array(automationTriggerSchema)}))});const namedPathSchema=z.object({name:z.string(),path:z.string()});export const projectsSchema=z.object({version,canAdd:z.boolean(),projects:z.array(namedPathSchema),found:z.array(namedPathSchema).max(40)}),directChatProviderSchema=z.enum(["claude","codex","gemini"]),directChatPostureSchema=z.object({summary:z.string(),detail:z.string(),sandboxed:z.boolean()}),directChatToolSchema=z.object({id:z.string(),ordinal:z.number().int(),name:z.string(),detail:z.string(),status:z.enum(["running","done","error"]),updatedAt:iso}),directChatArtifactSchema=z.object({id:hex32,kind:z.enum(["output","attachment"]),filename:z.string(),mimeType:z.string(),byteSize:z.number().int(),url:z.string(),sourcePath:z.string().nullable(),createdAt:iso}),directChatShipSummarySchema=z.object({id:hex32,seq:z.number().int(),mode:z.enum(["ship","keep-branch"]),branch:z.string(),candidateSha:z.string(),state:z.enum(["kept","imported","armed","completed","merging","merged","cancelled","failed"]),taskId:z.string().nullable(),prUrl:z.string().nullable(),detail:z.string().nullable(),createdAt:iso,stateAt:iso}),directChatUsageSchema=z.object({inputTokens:z.number().int(),outputTokens:z.number().int(),cacheReadTokens:z.number().int(),cacheCreationTokens:z.number().int(),thinkingTokens:z.number().int(),contextTokens:z.number().int(),contextWindow:z.number().int().nullable(),costUsd:z.number().nullable()}),directChatModelOptionSchema=z.object({provider:directChatProviderSchema,id:z.string(),label:z.string(),efforts:z.array(z.string()),defaultEffort:z.string().nullable(),contextWindow:z.number().int().nullable()}),directChatTurnSchema=z.object({id:hex32,seq:z.number().int(),userPrompt:z.string(),switchedFromProvider:directChatProviderSchema.nullable(),status:z.enum(["running","completed","stopped","failed","interrupted"]),assistantText:z.string(),errorText:z.string().nullable(),createdAt:iso,finishedAt:iso.nullable(),usage:directChatUsageSchema.nullable(),tools:z.array(directChatToolSchema),artifacts:z.array(directChatArtifactSchema)}),directChatSummarySchema=z.object({id:hex32,title:z.string(),project:z.string(),branch:z.string(),provider:directChatProviderSchema,modelId:z.string(),effort:z.string().nullable(),posture:directChatPostureSchema,running:z.boolean(),lastStatus:z.enum(["running","completed","stopped","failed","interrupted"]).nullable(),changedFilesCount:z.number().int(),mainDirtyFiles:z.array(z.string()),usage:directChatUsageSchema.nullable(),createdAt:iso,updatedAt:iso}),directChatsListSchema=z.object({version,available:z.boolean(),problem:z.string().nullable(),backgroundOn:z.boolean(),models:z.array(directChatModelOptionSchema),threads:z.array(directChatSummarySchema)}),directChatDetailSchema=z.object({version,room:z.string(),thread:directChatSummarySchema,turns:z.array(directChatTurnSchema),attachments:z.array(directChatArtifactSchema),ships:z.array(directChatShipSummarySchema),diff:z.object({changedFiles:z.array(z.string()),diffText:z.string(),dirty:z.boolean(),unread:z.literal(!0).optional()})}),directChatShipPreviewSchema=z.object({version,threadId:hex32,mode:z.enum(["ship","keep-branch"]),canAutoMerge:z.boolean(),autoMergeReason:z.string().nullable(),termsDigest:hex32,title:z.string(),goal:z.string(),baseSha:z.string(),branch:z.string(),changedFiles:z.array(z.string()),checkCommand:z.string().nullable(),githubRepo:z.string().nullable(),githubBase:z.string().nullable(),mergeSummary:z.string()}),directChatShippedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),ship:directChatShipSummarySchema,said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatAttachedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),artifact:directChatArtifactSchema,cloneRelativePath:z.string().nullable()}),z.object({ok:z.literal(!1),error:z.string()})]),directChatStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),threadId:hex32,turnId:hex32,room:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatMutatedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),taskResultReportItemSchema=z.object({title:z.string(),why:z.string(),url:z.string(),image:z.string().nullable()}),taskResultReportFollowUpSchema=z.object({title:z.string(),goal:z.string()}),taskResultReportShotSchema=z.object({file:z.string(),caption:z.string(),url:z.string(),artifactUrl:z.string().nullable(),problem:z.string().nullable()}),taskResultReportSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),title:z.string(),summary:z.string(),document:z.string(),truncated:z.boolean(),items:z.array(taskResultReportItemSchema),followUps:z.array(taskResultReportFollowUpSchema),shots:z.array(taskResultReportShotSchema)}),z.object({ok:z.literal(!1),problem:z.string()})]),taskResultHandoffSchema=z.object({conclusion:z.string(),changes:z.array(z.string()),verification:z.array(z.string()),followUps:z.array(z.string()),decisions:z.array(z.string()),assumptions:z.array(z.string()),notDone:z.array(z.string()),risks:z.array(z.string())}),taskResultScreenshotSchema=z.object({caption:z.string(),path:z.string(),url:z.string()}),taskResultSchema=z.object({version,task:z.string(),deliverable:z.enum(["code","report"]),run:z.number().int().nullable(),role:z.string().nullable(),outcome:z.string().nullable(),verdict:z.string().nullable(),summary:z.string().nullable(),report:taskResultReportSchema.nullable(),handoff:taskResultHandoffSchema.nullable(),screenshots:z.array(taskResultScreenshotSchema)}),linkRedemptionSchema=z.object({version,account:z.string(),cookie:z.object({name:z.string(),value:z.string().regex(/^[0-9a-f]{64}$/)}),csrf:z.string().regex(/^[0-9a-f]{64}$/),key:z.string().regex(/^[0-9a-f]{64}$/),epoch:z.string(),passwordSet:z.boolean().optional()}),linkRedemptionRequestSchema=z.strictObject({code:z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),ENGINE_REQUESTS={linkRedemption:{route:"POST /login/once",schema:linkRedemptionRequestSchema}},engineRefusalSchema=z.object({error:z.string()}),helloSchema=z.object({version,toolroll:z.string(),contract:z.string().regex(/^[0-9a-f]{64}$/),responses:z.array(z.string()),mode:z.enum(["solo","team"]),defaultChain:z.enum(["just-code","plan-first"])}),ENGINE_RESPONSES={liveSessionWindow:{route:"GET /agents/live/<kind>/<id>",schema:liveSessionWindowSchema},liveThreads:{route:"GET /agents/live/threads",schema:liveThreadsSchema},workRows:{route:"GET /work/rows",schema:workRowsSchema},stepCards:{route:"GET /t/<task>/steps",schema:stepCardsSchema},approvalCard:{route:"GET /t/<task>/approval",schema:approvalCardSchema},resultDiff:{route:"GET /t/<task>/diff",schema:resultDiffSchema},resultDiffFile:{route:"GET /t/<task>/diff?run=&file=",schema:resultDiffFileSchema},resultDiffContext:{route:"GET /t/<task>/diff?run=&file=&from=&count=",schema:resultDiffContextSchema},taskResult:{route:"GET /t/<task>/result",schema:taskResultSchema},linkRedemption:{route:"POST /login/once",schema:linkRedemptionSchema},refusal:{route:"every engine route's refusal",schema:engineRefusalSchema},hello:{route:"GET /engine/hello",schema:helloSchema},agents:{route:"GET /engine/agents",schema:agentsReadSchema},models:{route:"GET /engine/models",schema:modelsReadSchema},leadChat:{route:"GET /engine/chat",schema:leadChatSchema},automations:{route:"GET /engine/automations",schema:automationsSchema},projects:{route:"GET /engine/projects",schema:projectsSchema},termState:{route:"GET /term/state",schema:termStateSchema},termStarted:{route:"POST /term/start, /term/agent/sign-in, /term/agent/install",schema:termStartedSchema},directChatsList:{route:"GET /engine/direct-chats",schema:directChatsListSchema},directChatDetail:{route:"GET /engine/direct-chats/<id>",schema:directChatDetailSchema},directChatStarted:{route:"POST /engine/direct-chats, /engine/direct-chats/<id>/messages",schema:directChatStartedSchema},directChatMutated:{route:"POST /engine/direct-chats/<id>/{stop,model,delete,apply-main-edits,ship-cancel}",schema:directChatMutatedSchema},directChatShipPreview:{route:"POST /engine/direct-chats/<id>/ship-preview",schema:directChatShipPreviewSchema},directChatShipped:{route:"POST /engine/direct-chats/<id>/ship",schema:directChatShippedSchema},directChatAttached:{route:"POST /engine/direct-chats/<id>/attachments",schema:directChatAttachedSchema}};const toStderr=(route,issues)=>process.stderr.write(`engine api: ${route} disagrees with its contract: ${issues.slice(0,5).map(one=>`${one.path} ${one.kind}`).join("; ")}
1
+ import{createHash}from"node:crypto";import{z}from"zod";import{chatCardSchema}from"./chat-card.js";import{parseContract}from"./contract.js";import{PROVIDER_ID_VALUES}from"./provider.js";export const ENGINE_API_VERSION=1;const version=z.literal(ENGINE_API_VERSION),iso=z.string(),liveRecordSchema=z.union([z.object({k:z.literal("open"),at:iso,detail:z.enum(["base","commands"]),s:z.number().int().optional()}),z.object({k:z.literal("start"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("say"),at:iso,t:z.array(z.string()),s:z.number().int().optional()}),z.object({k:z.literal("you"),at:iso,t:z.array(z.string())}),z.object({k:z.literal("step"),at:iso,id:z.string(),kind:z.string(),target:z.string().optional(),once:z.literal(!0).optional(),s:z.number().int().optional()}),z.object({k:z.literal("done"),at:iso,id:z.string(),ok:z.boolean().nullable(),out:z.array(z.string()).optional(),s:z.number().int().optional()}),z.object({k:z.literal("cut"),at:iso,s:z.number().int().optional()}),z.object({k:z.literal("cap"),at:iso.optional(),s:z.number().int().optional()}),z.object({k:z.literal("child"),s:z.number().int(),at:iso.optional(),parent:z.string().nullable(),via:z.number().int().optional(),desc:z.string().optional()}),z.object({k:z.literal("end"),s:z.number().int(),at:iso.optional(),ok:z.boolean().nullable()}),z.object({k:z.literal("over")})]);export const liveSessionRefSchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("run"),id:z.number().int().positive(),task:z.string().nullable()}),z.object({kind:z.literal("thread"),id:z.string().regex(/^[0-9a-f]{32}$/),task:z.null()})]);const hex32=z.string().regex(/^[0-9a-f]{32}$/),flexibleLevelSchema=z.enum(["supervised","auto","full"]),answerStateSchema=z.enum(["pending","decided","sending","sent","delivered","not-sent","uncertain","withdrawn"]),threadQuestionSchema=z.object({request:hex32,kind:z.enum(["permission","question"]),title:z.string(),detail:z.string().nullable(),tool:z.string().nullable(),complete:z.boolean(),digest:z.string().regex(/^[0-9a-f]{64}$/),state:answerStateSchema,answerable:z.boolean(),parts:z.array(z.object({id:z.string(),question:z.string(),options:z.array(z.string())}))});export const threadTerminalSchema=z.strictObject({available:z.boolean(),launch:hex32,generation:z.number().int().positive(),lifecycle:z.enum(["starting","live","stopping","exited","unresolved"]),viewing:z.enum(["detached","viewing"]),control:z.enum(["none","self","other"]),protocol:z.literal(1),cols:z.number().int().min(2).max(500),rows:z.number().int().min(2).max(500)}),threadFactsSchema=z.object({version:z.string().regex(/^[0-9a-f]{16}$/),title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),agent:z.object({provider:z.string(),model:z.string()}).nullable(),turn:z.object({seq:z.number().int(),status:z.string(),costUsd:z.number().nullable(),costBasis:z.enum(["measured","estimated","unknown"]).nullable(),endWords:z.string().optional(),billing:z.enum(["subscription","api-key"]).optional()}).nullable(),questions:z.array(threadQuestionSchema),runtime:z.enum(["stream-json","interactive"]).optional(),terminal:threadTerminalSchema.optional(),ended:z.object({words:z.string(),stopPending:z.boolean()}).optional(),ship:z.object({seq:z.number().int(),state:z.string(),words:z.string()}).optional()}),liveSessionWindowSchema=z.object({version,session:liveSessionRefSchema,room:z.string(),live:z.boolean(),file:z.enum(["main","sub"]),window:z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),records:z.array(liveRecordSchema),cursor:z.string(),restarted:z.boolean(),earlier:z.boolean(),quarantined:z.number().int(),skipped:z.number().int(),more:z.boolean()}),z.object({ok:z.literal(!1),reason:z.enum(["missing","unavailable","off"])})]),thread:threadFactsSchema.optional()}),liveThreadsSchema=z.object({version,on:z.boolean().optional(),threads:z.array(z.object({id:hex32,title:z.string(),project:z.string().nullable(),level:flexibleLevelSchema.nullable(),live:z.boolean(),waiting:z.number().int(),costUsd:z.number().nullable(),turn:z.string().nullable(),ended:z.boolean(),stopPending:z.boolean(),ship:z.string().nullable(),turnSeq:z.number().int().nullable(),shipSeq:z.number().int().nullable()}))});const workAskSchema=z.enum(["release","approve","answer","flow","wrong","review","setup","other"]),needRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),at:iso.optional(),state:z.enum(["needs","running","queued","done"]),ask:workAskSchema.nullable(),group:z.enum(["decide","review","unblock"]).optional(),reason:z.string().nullable(),line:z.string().nullable(),action:z.object({label:z.string(),href:z.string()}).nullable(),question:z.object({id:z.number().int(),text:z.string(),recap:z.string(),options:z.array(z.object({id:z.string(),label:z.string(),consequence:z.string(),recommended:z.boolean()}))}).nullable()});export const waitingSchema=z.object({retryAt:iso.nullable(),lastFailure:z.string().nullable(),attempt:z.enum(["build","plan"])}),WORK_ROW_GROUPS=["decide","review","unblock","building","rest"],WORK_STATUS_TONES=["attention","problem","live","ready","done","muted","neutral"],WORK_WORD_TONES=["","needs","ask","live","done","failed"];const workRowSchema=z.object({id:z.string(),title:z.string(),href:z.string(),project:z.string().nullable(),age:z.string(),status:z.object({label:z.string(),tone:z.enum(WORK_STATUS_TONES),token:z.string()}),word:z.object({word:z.string(),tone:z.enum(WORK_WORD_TONES)}),ask:z.string().nullable(),chip:z.string().nullable(),group:z.enum(WORK_ROW_GROUPS),rank:z.number().int(),check:z.enum(["failed","stale","unreadable"]).optional(),landed:z.string().optional(),detail:z.string().nullable(),problem:z.string().nullable(),need:needRowSchema.nullable(),waiting:waitingSchema.nullable()});export const workRowsSchema=z.object({version,project:z.string().nullable(),projectName:z.string(),needsCount:z.number().int(),groups:z.array(z.object({key:z.string(),label:z.string(),count:z.number().int()})).nullable(),rows:z.array(workRowSchema),needs:z.array(z.object({key:z.enum(["decide","review","unblock"]),label:z.string(),count:z.number().int(),rows:z.array(needRowSchema)})),next:z.string().nullable(),room:z.literal("workspace"),spend:z.object({todayUsd:z.number(),planPercent:z.number().int().nullable()}).nullable(),limits:z.array(z.object({provider:z.string(),plan:z.string().nullable(),window:z.string(),usedPercent:z.number(),reached:z.boolean(),resetsAt:z.string().nullable(),observedAt:z.string()})).nullable()}),stepCardSchema=z.object({key:z.enum(["plan","approve","build","checks","review","ready"]),label:z.string(),state:z.enum(["done","current","stuck","skipped","todo"]),mark:z.enum(["done","needs","live","wait","stuck","skipped","todo"]),sentence:z.string(),at:iso.nullable(),needsYou:z.boolean(),inChain:z.boolean(),agent:z.object({provider:z.string(),model:z.string().nullable()}).nullable(),startedAt:iso.nullable(),latestStartedAt:iso.nullable(),finishedAt:iso.nullable(),costUsd:z.number().nullable(),runs:z.array(z.number().int()),terms:z.object({key:z.string(),revision:z.string().nullable(),rows:z.array(z.object({label:z.string(),words:z.string(),lines:z.array(z.string())})),warnings:z.array(z.string()),decision:z.object({question:z.string(),from:z.string().nullable(),summary:z.array(z.string().max(80)).max(3),planSteps:z.number().int().nonnegative().nullable(),planFiles:z.number().int().nonnegative().nullable(),agents:z.object({plan:z.string().nullable(),build:z.string().nullable(),review:z.string().nullable()}),estimateMinutes:z.number().int().nonnegative().nullable(),risk:z.object({reach:z.enum(["low","medium","high"]),undo:z.enum(["low","medium","high"]),proof:z.enum(["low","medium","high"]),secrets:z.enum(["low","medium","high"])}),unusual:z.array(z.string()),recommended:z.enum(["approve","replan"]),waiting:z.object({index:z.number().int().nonnegative(),total:z.number().int().nonnegative()})}).optional(),usualLabel:z.string(),usual:z.array(z.object({label:z.string(),words:z.string()}))}).optional()}),stepCardsSchema=z.object({version,task:z.object({id:z.string(),root:z.string(),title:z.string(),state:z.string(),project:z.string().nullable()}),chain:z.enum(["plan-first","just-code"]),headline:z.string().nullable(),liveRun:z.number().int().nullable(),latestRun:z.number().int().nullable(),familyBuilds:z.array(z.number().int()).optional(),models:z.array(z.object({phase:z.string(),provider:z.string(),model:z.string(),chosen:z.enum(["recommended","override","pinned"])})).nullable(),cards:z.array(stepCardSchema).nullable(),review:z.object({buildNow:z.boolean().optional(),run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),accept:z.object({owed:z.enum(["person-check","exception"]).nullable(),blockers:z.array(z.string()),needs:z.string().nullable()})}).nullable(),shell:z.object({run:z.number().int(),why:z.string().nullable()}).nullable(),failure:z.object({line:z.string(),failedInARow:z.number().int(),suggestion:z.string().nullable(),agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),waiting:waitingSchema.extend({agentSaid:z.array(z.string()).max(8).nullable()}).nullable(),held:z.object({id:z.number().int(),reason:z.string(),lastFailure:z.string().nullable()}).nullable(),retry:z.object({run:z.number().int(),digest:z.string()}).nullable(),planStopped:z.object({incident:z.number().int(),kind:z.enum(["plan","question","stalled"]),line:z.string(),problems:z.array(z.string()).max(8).nullable(),agentSaid:z.array(z.string()).max(8).nullable(),again:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable()}).nullable(),plan:z.object({source:z.string().regex(/^[0-9a-f]{64}$/)}).nullable(),planQueued:z.boolean(),approval:z.object({by:z.string(),you:z.boolean(),automatic:z.boolean()}).nullable(),scopeDigest:z.string().nullable(),agentChoices:z.object({plan:z.array(z.object({provider:z.string(),model:z.string()})),build:z.array(z.object({provider:z.string(),model:z.string()}))}).nullable(),pendingAgentChange:z.object({phase:z.enum(["plan","build"]),provider:z.string(),model:z.string(),when:z.enum(["next-run","restart"]),by:z.string(),at:z.string(),problem:z.string().nullable()}).nullable(),landing:z.object({words:z.string(),reverted:z.boolean()}).nullable(),check:z.enum(["failed","stale","unreadable"]).optional(),runChecks:z.object({run:z.number().int(),level:z.enum(["quick","full"])}).optional(),behindMain:z.object({run:z.number().int(),receipt:z.string().regex(/^[0-9a-f]{64}$/),source:z.string(),main:z.string(),behind:z.number().int(),note:z.string()}).optional(),room:z.string()}),approvalCardSchema=z.object({version,task:z.string(),key:z.string().nullable(),digest:z.string().regex(/^[0-9a-f]{64}$/).nullable(),nonce:z.string().regex(/^[0-9a-f]{32}$/).nullable(),terms:z.array(z.object({label:z.string(),words:z.string()})),problem:z.string().nullable()});const diffProblemSchema=z.string().nullable();export const resultDiffSchema=z.object({version,task:z.string(),run:z.number().int().nullable(),totals:z.object({files:z.number().int(),additions:z.number().int(),deletions:z.number().int(),binary:z.number().int(),filesTruncated:z.boolean()}).nullable(),files:z.array(z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),additions:z.number().int(),deletions:z.number().int(),binary:z.boolean(),hunks:z.number().int()})),patchTruncated:z.boolean(),problem:diffProblemSchema});const diffLineSchema=z.object({kind:z.enum(["context","addition","deletion","meta"]),text:z.string(),oldLine:z.number().int().nullable(),newLine:z.number().int().nullable()});export const resultDiffFileSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.object({file:z.number().int(),path:z.string(),oldPath:z.string().nullable(),meta:z.array(z.string()),hunks:z.array(z.object({header:z.string(),lines:z.array(diffLineSchema)})),lineCount:z.number().int().nonnegative().nullable()}),linesTruncated:z.boolean()}),DIFF_CONTEXT_MAX=100,resultDiffContextSchema=z.object({version,task:z.string(),run:z.number().int(),file:z.number().int(),from:z.number().int(),lines:z.array(z.object({newLine:z.number().int(),text:z.string()})),lineCount:z.number().int().nullable(),problem:z.string().nullable()});const agentUseSchema=z.object({supported:z.boolean(),ready:z.boolean(),mark:z.string().nullable(),reason:z.string().nullable(),fix:z.string().nullable()});export const agentsReadSchema=z.object({version,checkedAt:iso.nullable(),agents:z.array(z.object({id:z.string(),name:z.string(),state:z.enum(["signed-in","signed-out","unknown","not-installed"]),how:z.string().nullable(),signIn:z.string().nullable(),ready:z.boolean(),next:z.string().nullable(),setup:z.object({install:z.string().nullable(),canInstall:z.boolean(),signIn:z.string().nullable(),canSignIn:z.boolean(),key:z.string().nullable(),check:z.string().nullable(),note:z.string().nullable(),registry:z.string().nullable(),registryUnsure:z.boolean()}),chat:agentUseSchema.optional(),build:agentUseSchema.extend({roles:z.array(z.string())}).optional()})),firstTask:z.object({id:z.string(),name:z.string()}).nullable(),lines:z.array(z.string())}),modelsReadSchema=z.object({version,canChange:z.boolean(),digest:z.string(),problem:z.string().nullable(),roles:z.array(z.object({key:z.enum(["plan","build","build-light","build-strong","review"]),label:z.string(),current:z.string(),words:z.string(),choices:z.array(z.object({provider:z.string(),label:z.string(),models:z.array(z.object({value:z.string(),label:z.string()}))}))})),defaultAgent:z.string().nullable(),presets:z.array(z.object({agent:z.string(),name:z.string(),words:z.string(),fields:z.record(z.string(),z.string())}))}),termStateSchema=z.object({available:z.boolean(),problem:z.string().nullable(),programs:z.array(z.enum(["claude","codex","antigravity","shell"])),projects:z.array(z.object({path:z.string(),name:z.string()})),sessions:z.array(z.object({id:z.string().regex(/^[0-9a-f]{32}$/),repo:z.string(),project:z.string(),program:z.enum(["claude","codex","antigravity","shell"]),branch:z.string(),startedAt:iso,endedAt:iso.nullable(),exit:z.object({code:z.number().int().nullable(),signal:z.number().int().nullable()}).nullable(),cleanup:z.enum(["clean","uncertain"]).nullable(),task:z.string().nullable(),run:z.number().int().nullable()}))}),termStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),id:z.string().regex(/^[0-9a-f]{32}$/)}),z.object({ok:z.literal(!1),error:z.string()})]);const leadLinkSchema=z.object({label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()}),leadCardPrimarySchema=z.discriminatedUnion("kind",[z.object({kind:z.literal("confirm"),label:z.string(),irreversible:z.boolean(),native:z.boolean()}),z.object({kind:z.literal("link"),label:z.string(),href:z.string(),task:z.string().nullable(),tab:z.enum(["live","steps","diff"]).nullable()})]);export const leadChatCardSchema=z.object({id:z.number().int(),kind:z.string(),label:z.string(),state:z.enum(["pending","confirmed","refused","dismissed","expired"]),data:z.boolean(),lines:z.array(z.string()),card:chatCardSchema.nullable(),said:z.string().nullable(),note:z.string().nullable(),primary:leadCardPrimarySchema.nullable(),dismissable:z.boolean(),links:z.array(leadLinkSchema)});const leadAskSchema=z.object({turn:z.number().int(),question:z.string(),options:z.array(z.string()),open:z.boolean(),stale:z.boolean()}),leadMessageSchema=z.object({id:z.number().int(),role:z.enum(["operator","assistant"]),text:z.string(),activity:z.string().nullable(),createdAt:iso,cards:z.array(leadChatCardSchema),ask:leadAskSchema.nullable()}),leadQueuedSchema=z.object({id:z.number().int(),text:z.string(),status:z.enum(["queued","starting","cancelled","failed","uncertain"]),detail:z.string().nullable()});export const leadChatSchema=z.object({version,room:z.string(),session:z.number().int().nullable(),leadName:z.string(),canSend:z.boolean(),problem:z.string().nullable(),project:z.string().nullable(),busy:z.boolean(),pendingProposals:z.number().int(),queued:z.array(leadQueuedSchema),messages:z.array(leadMessageSchema)});const automationTriggerSchema=z.object({id:z.number().int(),kind:z.string(),words:z.string(),state:z.enum(["active","paused"]),nextAt:iso.nullable(),lastAt:iso.nullable(),lastOutcome:z.string().max(200).nullable(),failures:z.number().int(),canPress:z.boolean(),canCheck:z.boolean(),label:z.string().nullable(),questions:z.array(z.string()).nullable(),resumeRunsNow:z.boolean()});export const automationsSchema=z.object({version,canAct:z.boolean(),automations:z.array(z.object({id:z.number().int(),name:z.string(),project:z.string().nullable(),group:z.enum(["needs","running","on","paused"]),starts:z.string(),nextAt:iso.nullable(),waiting:z.number().int(),inProgress:z.number().int(),trouble:z.string().nullable(),triggers:z.array(automationTriggerSchema)}))});const namedPathSchema=z.object({name:z.string(),path:z.string()});export const projectsSchema=z.object({version,canAdd:z.boolean(),projects:z.array(namedPathSchema),found:z.array(namedPathSchema).max(40)}),directChatProviderSchema=z.enum(PROVIDER_ID_VALUES),directChatPostureSchema=z.object({summary:z.string(),detail:z.string(),sandboxed:z.boolean()}),directChatToolSchema=z.object({id:z.string(),ordinal:z.number().int(),name:z.string(),detail:z.string(),status:z.enum(["running","done","error"]),updatedAt:iso}),directChatArtifactSchema=z.object({id:hex32,kind:z.enum(["output","attachment"]),filename:z.string(),mimeType:z.string(),byteSize:z.number().int(),url:z.string(),sourcePath:z.string().nullable(),createdAt:iso}),directChatShipSummarySchema=z.object({id:hex32,seq:z.number().int(),mode:z.enum(["ship","keep-branch"]),branch:z.string(),candidateSha:z.string(),state:z.enum(["kept","imported","armed","completed","merging","merged","cancelled","failed"]),taskId:z.string().nullable(),prUrl:z.string().nullable(),detail:z.string().nullable(),createdAt:iso,stateAt:iso}),directChatUsageSchema=z.object({inputTokens:z.number().int(),outputTokens:z.number().int(),cacheReadTokens:z.number().int(),cacheCreationTokens:z.number().int(),thinkingTokens:z.number().int(),contextTokens:z.number().int(),contextWindow:z.number().int().nullable(),costUsd:z.number().nullable()}),directChatModelOptionSchema=z.object({provider:directChatProviderSchema,id:z.string(),label:z.string(),efforts:z.array(z.string()),defaultEffort:z.string().nullable(),contextWindow:z.number().int().nullable()}),directChatTurnSchema=z.object({id:hex32,seq:z.number().int(),userPrompt:z.string(),switchedFromProvider:directChatProviderSchema.nullable(),status:z.enum(["running","completed","stopped","failed","interrupted"]),assistantText:z.string(),errorText:z.string().nullable(),createdAt:iso,finishedAt:iso.nullable(),usage:directChatUsageSchema.nullable(),tools:z.array(directChatToolSchema),artifacts:z.array(directChatArtifactSchema)}),directChatSummarySchema=z.object({id:hex32,title:z.string(),project:z.string(),branch:z.string(),provider:directChatProviderSchema,modelId:z.string(),effort:z.string().nullable(),providerLabel:z.string().optional(),pickerProvider:directChatProviderSchema.optional(),posture:directChatPostureSchema,running:z.boolean(),lastStatus:z.enum(["running","completed","stopped","failed","interrupted"]).nullable(),changedFilesCount:z.number().int(),mainDirtyFiles:z.array(z.string()),usage:directChatUsageSchema.nullable(),createdAt:iso,updatedAt:iso}),directChatsListSchema=z.object({version,available:z.boolean(),problem:z.string().nullable(),backgroundOn:z.boolean(),models:z.array(directChatModelOptionSchema),threads:z.array(directChatSummarySchema)}),directChatDetailSchema=z.object({version,room:z.string(),thread:directChatSummarySchema,turns:z.array(directChatTurnSchema),attachments:z.array(directChatArtifactSchema),ships:z.array(directChatShipSummarySchema),diff:z.object({changedFiles:z.array(z.string()),diffText:z.string(),dirty:z.boolean(),unread:z.literal(!0).optional()})}),directChatShipPreviewSchema=z.object({version,threadId:hex32,mode:z.enum(["ship","keep-branch"]),canAutoMerge:z.boolean(),autoMergeReason:z.string().nullable(),termsDigest:hex32,title:z.string(),goal:z.string(),baseSha:z.string(),branch:z.string(),changedFiles:z.array(z.string()),checkCommand:z.string().nullable(),githubRepo:z.string().nullable(),githubBase:z.string().nullable(),mergeSummary:z.string()}),directChatShippedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),ship:directChatShipSummarySchema,said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatAttachedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),artifact:directChatArtifactSchema,cloneRelativePath:z.string().nullable()}),z.object({ok:z.literal(!1),error:z.string()})]),directChatStartedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),threadId:hex32,turnId:hex32,room:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),directChatMutatedSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),said:z.string()}),z.object({ok:z.literal(!1),error:z.string(),code:z.string().optional()})]),taskResultReportItemSchema=z.object({title:z.string(),why:z.string(),url:z.string(),image:z.string().nullable()}),taskResultReportFollowUpSchema=z.object({title:z.string(),goal:z.string()}),taskResultReportShotSchema=z.object({file:z.string(),caption:z.string(),url:z.string(),artifactUrl:z.string().nullable(),problem:z.string().nullable()}),taskResultReportSchema=z.discriminatedUnion("ok",[z.object({ok:z.literal(!0),title:z.string(),summary:z.string(),document:z.string(),truncated:z.boolean(),items:z.array(taskResultReportItemSchema),followUps:z.array(taskResultReportFollowUpSchema),shots:z.array(taskResultReportShotSchema)}),z.object({ok:z.literal(!1),problem:z.string()})]),taskResultHandoffSchema=z.object({conclusion:z.string(),changes:z.array(z.string()),verification:z.array(z.string()),followUps:z.array(z.string()),decisions:z.array(z.string()),assumptions:z.array(z.string()),notDone:z.array(z.string()),risks:z.array(z.string())}),taskResultScreenshotSchema=z.object({caption:z.string(),path:z.string(),url:z.string()}),taskResultSchema=z.object({version,task:z.string(),deliverable:z.enum(["code","report"]),run:z.number().int().nullable(),role:z.string().nullable(),outcome:z.string().nullable(),verdict:z.string().nullable(),summary:z.string().nullable(),report:taskResultReportSchema.nullable(),handoff:taskResultHandoffSchema.nullable(),screenshots:z.array(taskResultScreenshotSchema)}),linkRedemptionSchema=z.object({version,account:z.string(),cookie:z.object({name:z.string(),value:z.string().regex(/^[0-9a-f]{64}$/)}),csrf:z.string().regex(/^[0-9a-f]{64}$/),key:z.string().regex(/^[0-9a-f]{64}$/),epoch:z.string(),passwordSet:z.boolean().optional()}),linkRedemptionRequestSchema=z.strictObject({code:z.string().regex(/^[A-Za-z0-9_-]{43}$/)}),ENGINE_REQUESTS={linkRedemption:{route:"POST /login/once",schema:linkRedemptionRequestSchema}},engineRefusalSchema=z.object({error:z.string()}),helloSchema=z.object({version,toolroll:z.string(),contract:z.string().regex(/^[0-9a-f]{64}$/),responses:z.array(z.string()),mode:z.enum(["solo","team"]),defaultChain:z.enum(["just-code","plan-first"])}),ENGINE_RESPONSES={liveSessionWindow:{route:"GET /agents/live/<kind>/<id>",schema:liveSessionWindowSchema},liveThreads:{route:"GET /agents/live/threads",schema:liveThreadsSchema},workRows:{route:"GET /work/rows",schema:workRowsSchema},stepCards:{route:"GET /t/<task>/steps",schema:stepCardsSchema},approvalCard:{route:"GET /t/<task>/approval",schema:approvalCardSchema},resultDiff:{route:"GET /t/<task>/diff",schema:resultDiffSchema},resultDiffFile:{route:"GET /t/<task>/diff?run=&file=",schema:resultDiffFileSchema},resultDiffContext:{route:"GET /t/<task>/diff?run=&file=&from=&count=",schema:resultDiffContextSchema},taskResult:{route:"GET /t/<task>/result",schema:taskResultSchema},linkRedemption:{route:"POST /login/once",schema:linkRedemptionSchema},refusal:{route:"every engine route's refusal",schema:engineRefusalSchema},hello:{route:"GET /engine/hello",schema:helloSchema},agents:{route:"GET /engine/agents",schema:agentsReadSchema},models:{route:"GET /engine/models",schema:modelsReadSchema},leadChat:{route:"GET /engine/chat",schema:leadChatSchema},automations:{route:"GET /engine/automations",schema:automationsSchema},projects:{route:"GET /engine/projects",schema:projectsSchema},termState:{route:"GET /term/state",schema:termStateSchema},termStarted:{route:"POST /term/start, /term/agent/sign-in, /term/agent/install",schema:termStartedSchema},directChatsList:{route:"GET /engine/direct-chats",schema:directChatsListSchema},directChatDetail:{route:"GET /engine/direct-chats/<id>",schema:directChatDetailSchema},directChatStarted:{route:"POST /engine/direct-chats, /engine/direct-chats/<id>/messages",schema:directChatStartedSchema},directChatMutated:{route:"POST /engine/direct-chats/<id>/{stop,model,delete,apply-main-edits,ship-cancel}",schema:directChatMutatedSchema},directChatShipPreview:{route:"POST /engine/direct-chats/<id>/ship-preview",schema:directChatShipPreviewSchema},directChatShipped:{route:"POST /engine/direct-chats/<id>/ship",schema:directChatShippedSchema},directChatAttached:{route:"POST /engine/direct-chats/<id>/attachments",schema:directChatAttachedSchema}};const toStderr=(route,issues)=>process.stderr.write(`engine api: ${route} disagrees with its contract: ${issues.slice(0,5).map(one=>`${one.path} ${one.kind}`).join("; ")}
2
2
  `);export function checkEngineResponse(name,payload,report=toStderr){const{route,schema}=ENGINE_RESPONSES[name],parsed=parseContract(schema,payload);return parsed.ok||report(route,parsed.issues),payload}export function engineJsonSchemas(){const json=schema=>{const{$schema:_dialect,...rest}=z.toJSONSchema(schema,{target:"draft-2020-12",unrepresentable:"throw"});return rest};return{responses:Object.fromEntries(Object.entries(ENGINE_RESPONSES).map(([name,one])=>[name,json(one.schema)])),requests:Object.fromEntries(Object.entries(ENGINE_REQUESTS).map(([name,one])=>[name,json(one.schema)]))}}export function engineContractDigest(){return createHash("sha256").update(JSON.stringify({version:ENGINE_API_VERSION,...engineJsonSchemas()})).digest("hex")}
@@ -1,2 +1,2 @@
1
- import{z}from"zod";import{CHAT_ACTIONS}from"../chat-actions.js";import{RESULT_IMAGES_PER_TURN_CAP}from"../chat-evidence.js";import{CARD_CATALOG,CARD_SOURCES,CARD_TASK_STATES}from"../card-catalog.js";import{CHAT_CONTROLS}from"../chat-controls.js";import{CARD_CHART_TYPES,CARD_LIMITS}from"./chat-card.js";import{CHAT_TASK_ACTIONS}from"../chat-task-actions.js";import{LIMITS}from"../decision.js";import{CHECK_RESULTS,RUN_OUTCOMES,TASK_STATES}from"../lead-commitments.js";import{PERSON_ID}from"../lead-people.js";import{TASK_SIZES}from"../phase-routing.js";import{ACCEPTANCE_LIMITS}from"../scope.js";import{SUBAGENT_TEMPLATES}from"../subagents.js";import{TEXT_LIMITS}from"../text-limits.js";import{parseContract}from"./contract.js";import{FLOW_ALIASES}from"./flow.js";import{proposeFlowInputSchema}from"./flow-propose.js";import{acceptanceCriterionSchema}from"./plan.js";const enumOf=values=>z.enum(values);export const text=key=>z.string().max(TEXT_LIMITS[key]);const id=z.int().min(1),offset=z.int().min(0),planning=z.enum(["auto","required","skip"]),dcChatId=z.string().min(1).max(80),dcProvider=z.enum(["claude","codex","gemini"]),dcEffort=z.enum(["low","medium","high","xhigh","max","ultra"]);function overBy(limit,input){const count=n=>n.toLocaleString("en-US");return`over ${count(limit)} characters (it is ${typeof input=="string"?count(input.length):"longer"}): shorten it and call again`}export const taskRef=z.string().min(1).max(TEXT_LIMITS.taskRef),repoId=z.string().regex(/^r[0-9]{1,3}$/),scopeText=z.string().max(TEXT_LIMITS.goal,{error:issue=>overBy(TEXT_LIMITS.goal,issue.input)}).describe(`At most ${TEXT_LIMITS.goal.toLocaleString("en-US")} characters (UTF-16 code units) and ${TEXT_LIMITS.goalBytes.toLocaleString("en-US")} UTF-8 bytes; no control or disguised text. Longer text is refused with its length, not cut: shorten it and call again.`),touches=z.array(text("taskTouch")).max(50),acceptance=z.array(acceptanceCriterionSchema).min(1).max(ACCEPTANCE_LIMITS.criteria);const note=z.string().max(LIMITS.note,{error:issue=>overBy(LIMITS.note,issue.input)}).describe(`At most ${LIMITS.note} characters; longer is refused with its length, not cut.`);export const CODE_MAP_VIEWS=["overview","area","file","search"];const VIEW_THEME_NAME=/^[a-z][a-z0-9-]{0,31}$/,VIEW_ROLES=["paper","ink","muted","line","selection","selection-ink","ground","raised","fill","chat-bubble","chat-bubble-ink"],viewHex=z.string().regex(/^#[0-9a-fA-F]{6}$/),viewColors=z.strictObject({paper:viewHex.optional(),ink:viewHex.optional(),muted:viewHex.optional(),line:viewHex.optional(),selection:viewHex.optional(),"selection-ink":viewHex.optional(),ground:viewHex.optional(),raised:viewHex.optional(),fill:viewHex.optional(),"chat-bubble":viewHex.optional(),"chat-bubble-ink":viewHex.optional()});export const LISTED_TASK_STATES=["queued","running","done","failed","cancelled"];const ACTION_OPERATIONS=Object.keys(CHAT_ACTIONS).filter(one=>!one.startsWith("flow_")&&!one.startsWith("subagent_")&&!one.startsWith("direct_chat_")&&one!=="task_start"),cardProps=z.strictObject({source:z.enum(CARD_SOURCES).optional(),chart:z.enum(CARD_CHART_TYPES).optional(),columns:z.array(z.string().max(40)).max(CARD_LIMITS.columns).optional(),facts:z.array(z.string().max(40)).max(CARD_LIMITS.facts).optional(),repo:repoId.optional(),state:z.enum(CARD_TASK_STATES).optional(),limit:z.int().min(1).max(CARD_LIMITS.rows).optional(),flow:id.optional(),days:z.int().min(1).max(90).optional(),text:z.string().max(CARD_LIMITS.text).optional(),control:enumOf(Object.keys(CHAT_CONTROLS)).optional(),task:taskRef.optional(),run:id.optional(),proposal:id.optional()}),cardSpec=z.strictObject({root:z.string().max(40),elements:z.object({}).catchall(z.strictObject({type:enumOf(Object.keys(CARD_CATALOG.data.components)),props:cardProps,children:z.array(z.string().max(40)).max(16)}))});export const LEAD_TOOL_INPUTS={get_brief:z.strictObject({repo:repoId.optional()}),get_project_activity:z.strictObject({repo:repoId,offset:offset.optional()}),get_project_context:z.strictObject({repo:repoId,query:text("contextQuery").min(1),mode:z.enum(["search","impact"]).optional()}),get_code_map:z.strictObject({repo:repoId,version:id.optional(),view:z.enum(CODE_MAP_VIEWS),id:text("projectPath").optional(),query:text("contextQuery").optional(),cursor:z.string().max(40).optional()}),refresh_code_map:z.strictObject({repo:repoId}),get_action_status:z.strictObject({proposal:id}),get_actions:z.strictObject({}),propose_action:z.strictObject({operation:enumOf(ACTION_OPERATIONS),repo:z.string().optional(),task:taskRef.optional(),version:z.string().optional(),restore:id.optional(),sample:text("actionSample").optional(),content:text("actionContent").optional(),instructions:text("flowInstructions").optional(),title:text("actionTitle").optional(),id:z.string().optional(),run:id.optional(),note:note.optional(),catalog:text("actionName").optional(),name:text("actionName").optional(),command:text("actionCommand").optional(),args:z.array(text("actionCommand")).max(40).optional(),url:text("actionUrl").optional(),secrets:z.array(text("actionSecret")).max(12).optional(),about:text("actionAbout").optional(),on:z.boolean().optional(),finding:id.optional(),summary:text("actionAbout").optional(),file:text("actionName").optional(),line:id.optional(),pointer:z.string().max(40).optional(),revision:id.optional(),incident:id.optional(),provider:z.string().max(40).optional(),runner:text("actionName").optional(),persona:note.optional(),proposal:id.optional(),decision:z.enum(["accept","reject"]).optional(),reason:text("actionAbout").optional()}),propose_task_action:z.strictObject({task:taskRef,operation:enumOf(Object.keys(CHAT_TASK_ACTIONS)),dependency:taskRef.optional(),run:id.optional()}),get_controls:z.strictObject({}),show_control:z.strictObject({control:enumOf(Object.keys(CHAT_CONTROLS)),task:taskRef.optional(),repo:repoId.optional(),run:id.optional()}),show_card:z.strictObject({spec:cardSpec}),get_findings:z.strictObject({task:taskRef.optional(),repo:repoId.optional()}),offer_approval:z.strictObject({task:taskRef.optional(),card:id.optional()}),get_result:z.strictObject({task:taskRef,run:id.optional(),feedback_offset:offset.optional()}),get_diff:z.strictObject({task:taskRef,run:id.optional(),file:text("diffPath").min(1).optional(),offset:offset.optional()}),get_check_log:z.strictObject({task:taskRef,run:id.optional(),search:text("logSearch").min(2).optional(),offset:offset.optional()}),get_acceptance_evidence:z.strictObject({task:taskRef,run:id.optional(),offset:offset.optional()}),get_result_images:z.strictObject({task:taskRef,run:id.optional(),offset:offset.optional(),images:z.array(id).min(1).max(RESULT_IMAGES_PER_TURN_CAP).optional()}),propose_review:z.strictObject({run:id,operation:z.enum(["note","revise"]),note:z.string().max(LIMITS.note).nullable().optional(),path:text("diffPath").nullable().optional(),line:z.int().min(1).max(1e6).nullable().optional(),saved_notes:z.array(id).max(100).optional(),image:id.nullable().optional().describe("Screenshot artifact id from get_result_images; attaches the exact verified image to this feedback. null leaves off the screenshot a reply targets.")}),recap:z.strictObject({since:text("recapSince").optional()}),list_repos:z.strictObject({}),find_tools:z.strictObject({query:z.string().min(1).max(200).describe('What you want to do, in a few words ("make a flow", "add a subagent", "hold a task").')}),get_project_tools:z.strictObject({repo:repoId}),get_flows:z.strictObject({repo:repoId.optional(),flow:id.optional(),card:id.optional()}),propose_flow:proposeFlowInputSchema,get_subagents:z.strictObject({repo:repoId.optional(),subagent:id.optional()}),propose_subagent:z.strictObject({operation:z.enum(["ask","create","edit_section","edit_soul","pause","resume","remove","note","answer","use_tool","stop_tool","tool_rule","forget","edit_memory","add_routine","stop_routine","undo"]),section:text("subagentSection").optional(),schedule:text("subagentSchedule").optional(),routine:id.optional(),memory:id.optional(),tool:text("subagentTool").optional(),action:text("subagentAction").optional(),undoWith:text("subagentAction").optional(),call:id.optional(),use:z.enum(["free","ask","never"]).optional(),limitField:text("subagentAction").optional(),limitOver:z.number().min(0).optional(),repo:repoId.optional(),subagent:id.optional(),template:enumOf(SUBAGENT_TEMPLATES.map(one=>one.id)).optional(),name:text("subagentName").optional(),soul:text("subagentSoul").optional(),note:text("subagentNote").optional(),question:id.optional(),choice:text("subagentChoice").optional(),text:text("subagentText").optional()}),get_flow_insights:z.strictObject({repo:repoId.optional(),flow:id.optional(),days:z.int().min(1).max(90).optional(),card:id.optional(),entry:id.optional()}),get_skills:z.strictObject({repo:repoId,version:z.string().regex(/^[a-f0-9]{20}$/).optional(),offset:offset.optional()}),get_project_knowledge:z.strictObject({repo:repoId,reference:text("knowledgeReference").optional(),decision:id.optional()}),get_flaky_tests:z.strictObject({repo:repoId,row:text("knowledgeReference").optional()}),get_task_conversation:z.strictObject({task:taskRef,limit:z.int().min(1).max(30).optional()}),commit_to:z.strictObject({what:text("promise").min(3),when:z.enum(["task","run","check","time"]),task:taskRef.optional(),run:id.optional(),states:z.array(enumOf(TASK_STATES)).min(1).max(6).optional(),outcome:z.enum(RUN_OUTCOMES).optional(),result:z.enum(CHECK_RESULTS).optional(),at:z.string().optional(),checkAfter:z.string().optional()}),release_commitment:z.strictObject({commitment:id,reason:text("promise").min(3)}),remember:z.strictObject({repo:repoId.optional(),kind:z.enum(["decision","instruction","about-you"]),text:text("rememberText").min(3),why:text("rememberWhy").optional(),source:text("rememberSource").optional(),revision:offset.optional(),replaces:z.int().min(1).max(20).optional()}),manage_standing_directions:z.strictObject({action:z.enum(["list","add","toggle","remove"]),scope:z.string().max(256).optional(),repo:repoId.optional(),text:z.string().max(500).optional(),id:z.string().max(64).optional(),enabled:z.boolean().optional()}),get_person:z.strictObject({id:z.string().regex(PERSON_ID).optional(),name:text("personName").min(1).optional()}),get_integrations:z.strictObject({}),get_capabilities:z.strictObject({repo:repoId.optional()}),ask_owner:z.strictObject({question:text("ownerQuestion").min(3),options:z.array(text("ownerOption").min(1)).min(2).max(4)}),search_project_memory:z.strictObject({query:text("memorySearch").min(2),repo:repoId.optional()}),get_models:z.strictObject({}),list_tasks:z.strictObject({repo:repoId.optional(),state:z.enum(LISTED_TASK_STATES).optional(),limit:z.int().min(1).max(50).optional(),search:text("taskSearch").optional()}),tidy_preview:z.strictObject({days:z.int().min(1).max(365).optional()}),get_task:z.strictObject({task:taskRef}),get_agents:z.strictObject({task:taskRef}),list_decisions:z.strictObject({}),get_decision:z.strictObject({decision:id}),queue:z.strictObject({repo:repoId}),propose_task:z.strictObject({repo:repoId,title:text("taskTitle"),goal:scopeText,not:scopeText.nullable().optional(),touches:touches.optional(),acceptance,planning:planning.optional(),report:z.boolean().optional(),checks:text("checksWords").optional()}),propose_start:z.strictObject({repo:repoId,title:text("taskTitle")}),propose_sweep:z.strictObject({repo:repoId,title:text("taskTitle"),brief:scopeText,items:z.array(z.strictObject({title:text("taskTitle"),item:scopeText})).min(2).max(20),acceptance,max_parallel:z.number().int().min(1).max(8).optional()}),get_sweep:z.strictObject({sweep:id}),propose_sweep_cancel:z.strictObject({sweep:id}),propose_next:z.strictObject({task:taskRef}),propose_reserve:z.strictObject({task:taskRef,worker:text("workerName").nullable()}),propose_hold:z.strictObject({task:taskRef,reason:text("proposalReason")}),propose_unhold:z.strictObject({task:taskRef}),propose_steer:z.strictObject({task:taskRef,note:note.optional(),mode:z.enum(["note","pause","pause-and-steer","resume"]).optional(),question:z.number().int().positive().optional().describe("A running agent's open question (get_task agentQuestions): the note becomes its reply and closes it.")}),propose_dependency_repair:z.strictObject({task:taskRef,blocker:taskRef,operation:z.enum(["retry","unlink","replace"]),replacement:taskRef.optional()}),propose_scope:z.strictObject({task:taskRef,goal:scopeText,not:scopeText.nullable().optional(),touches:touches.optional(),acceptance}),propose_agents:z.strictObject({task:taskRef,size:z.enum(TASK_SIZES).optional(),risky:z.boolean().optional(),role:z.enum(["planner","builder","repair"]).optional(),agent:z.strictObject({provider:text("agentProvider"),model:text("agentModel")}).optional(),clear:z.boolean().optional(),why:text("agentWhy").optional()}),propose_answer:z.strictObject({decision:id,option:text("answerOption").min(1),rationale:text("answerRationale")}),propose_cancel:z.strictObject({task:taskRef,reason:text("proposalReason")}),toolroll_view_read:z.strictObject({}),toolroll_view_set:z.strictObject({theme:z.string().regex(VIEW_THEME_NAME).optional().describe("A built-in theme (terminal, light, dark, high-contrast) or a saved theme's name."),save_theme:z.strictObject({name:z.string().regex(VIEW_THEME_NAME).describe("Lowercase letters, digits and dashes, at most 32; not a built-in theme's name."),base:z.enum(["terminal","light","dark","high-contrast"]),colors:viewColors.optional(),use:z.boolean().optional().describe("true: switch to it now.")}).optional(),colors:viewColors.optional().describe("Role colours laid over the theme."),density:z.enum(["compact","comfortable"]).optional(),glyphs:z.enum(["unicode","ascii","nerd"]).optional(),columns:z.array(z.enum(["agent","step","age","cost","project"])).max(5).optional(),list_side:z.enum(["left","right"]).optional(),reduced_motion:z.boolean().optional(),key_bar:z.boolean().optional(),show_costs:z.boolean().optional(),notifications:z.strictObject({asks:z.boolean().optional(),finished:z.boolean().optional(),failed:z.boolean().optional()}).optional()}),list_direct_chats:z.strictObject({repo:repoId.optional(),include_archived:z.boolean().optional(),limit:z.int().min(1).max(40).optional()}),get_direct_chat:z.strictObject({chat:dcChatId,limit:z.int().min(1).max(30).optional()}),get_direct_chat_diff:z.strictObject({chat:dcChatId,max_patch_chars:z.int().min(200).max(2e4).optional()}),manage_direct_chat:z.strictObject({chat:dcChatId,operation:z.enum(["stop","archive","unarchive","set_model","rename"]),provider:dcProvider.optional(),model:z.string().min(1).max(120).optional(),effort:dcEffort.nullable().optional(),title:z.string().min(1).max(160).optional()}),get_usage_limits:z.strictObject({}),get_recent_updates:z.strictObject({repo:repoId.optional(),since:text("recapSince").optional(),hours:z.int().min(1).max(168).optional()}),get_attachment:z.strictObject({file:z.string().regex(/^[0-9]{1,15}\.[0-9]{1,2}$/),offset:z.int().min(0).max(1e8).optional()}),propose_direct_chat:z.strictObject({operation:z.enum(["start","reply","promote","ship"]),repo:repoId.optional(),chat:dcChatId.optional(),prompt:note.optional(),provider:dcProvider.optional(),model:z.string().min(1).max(120).optional(),effort:dcEffort.nullable().optional(),mode:z.enum(["ship","keep-branch"]).optional(),title:text("taskTitle").optional(),goal:scopeText.optional(),planning:planning.optional()}),propose_report_followups:z.strictObject({task:taskRef,indices:z.array(z.int().min(1).max(20)).min(1).max(5).optional(),planning:planning.optional()}),shared_browser:z.strictObject({action:z.enum(["status","open","screenshot","request_human_takeover","close"]),profile:z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/).optional(),session:z.string().min(1).max(48).optional(),url:z.string().min(1).max(2e3).optional(),reason:z.string().min(1).max(120).optional()})},LEAD_TOOL_READ_INPUTS={...LEAD_TOOL_INPUTS,list_tasks:LEAD_TOOL_INPUTS.list_tasks.extend({limit:z.unknown().optional()}),get_task_conversation:LEAD_TOOL_INPUTS.get_task_conversation.extend({limit:z.unknown().optional()}),get_flow_insights:LEAD_TOOL_INPUTS.get_flow_insights.extend({repo:repoId.nullable().optional(),days:z.unknown().optional()}),get_person:LEAD_TOOL_INPUTS.get_person.extend({id:z.unknown().optional(),name:z.unknown().optional()}),propose_agents:LEAD_TOOL_INPUTS.propose_agents.extend({agent:LEAD_TOOL_INPUTS.propose_agents.shape.agent.unwrap().strip().optional()})},LEAD_TOOL_OPTIONS={propose_flow:FLOW_ALIASES},str=z.string(),int=z.number().int(),list=z.array(z.unknown()),nullable=schema=>schema.nullable(),rows=shape=>z.array(z.looseObject(shape));const cardDrafted=z.looseObject({proposal:int,label:str,awaiting:str,executed:z.literal(!1)}),proposed=(kind,shape={})=>z.looseObject({proposal:int,kind:z.literal(kind),awaiting:str,...shape});export const codeMapOutput=z.looseObject({v:z.literal(1),ok:z.boolean()}),repositoryContextOutput=z.looseObject({version:z.literal(1),readOnly:z.boolean(),query:str,mode:z.enum(["search","impact"]),asOf:str,excerpts:list}),catchUpOutput=z.looseObject({version:z.literal(1),asOf:str,readOnly:z.literal(!0),assignments:list,projects:list,omissions:z.looseObject({})}),recapOutput=z.looseObject({since:nullable(str),repos:list,waitsOnYou:z.looseObject({decisions:list,incidents:int,scopesAwaitingApproval:list}),running:list,truncated:z.boolean()}),decisionsOutput=z.looseObject({decisions:rows({decision:int,task:str,question:str,options:list,ageHours:z.number()}),truncated:z.boolean()}),decisionOutput=z.looseObject({repo:str,decision:int,task:str,state:str,question:str,options:rows({id:str,label:str,reversible:z.boolean(),consequence:str}),ageHours:z.number()}),queueColumnsOutput={columns:rows({column:str,tasks:list})},LEAD_TOOL_OUTPUTS={get_brief:catchUpOutput,get_project_activity:z.looseObject({asOf:str,since:str,days:int,limit:int,truncated:z.boolean(),ready:z.object({count:int,oldestFinishedAgeMs:nullable(int),dated:int}),completed:z.looseObject({count:int}),families:list,familiesTotal:int,familiesOffset:int,nextOffset:nullable(int),incompleteHistory:int}),get_project_context:repositoryContextOutput,get_code_map:codeMapOutput,refresh_code_map:z.looseObject({request:z.enum(["queued","already-queued"])}),get_action_status:z.looseObject({proposal:int,operation:str,state:str,outcome:z.unknown(),finishedAt:nullable(str)}),get_actions:z.looseObject({actions:rows({operation:str,label:str,secureReview:z.boolean(),inputs:z.array(str)}),notice:str}),propose_action:cardDrafted,propose_task_action:z.looseObject({proposal:int,action:str,awaiting:str}),get_controls:z.looseObject({confirmedInChat:z.array(str),existingControls:rows({id:str,label:str,needsTask:z.boolean(),needsProject:z.boolean()}),rule:str}),show_control:z.looseObject({card:int,label:str,action:str}),show_card:z.looseObject({card:int,title:str,shows:z.array(str)}),get_findings:z.looseObject({findings:z.array(z.looseObject({finding:int,task:str,state:str})),rule:str}),offer_approval:z.looseObject({offered:z.boolean()}),get_result:z.looseObject({task:str,root:str,currentExecution:str,run:int,title:str,feedback:list,feedbackTotal:int,nextFeedbackOffset:nullable(int),changes:str,changesShortened:z.boolean(),verification:str,accepted:z.boolean(),evidenceTool:str,canRevise:z.boolean()}),get_diff:z.looseObject({task:str,run:int,files:rows({path:str,added:int,removed:int}).optional(),file:str.optional(),diff:str.optional(),nextOffset:nullable(int).optional(),notice:nullable(str)}),get_check_log:z.looseObject({task:str,run:int,log:str,notice:nullable(str)}),get_acceptance_evidence:z.looseObject({task:str,run:int}),get_result_images:z.looseObject({task:str,run:int,imageCount:int,images:rows({id:int,position:int,selected:z.boolean()}),selected:z.array(int),selectedCount:int,sendCount:int,nextImageOffset:nullable(int),nextImageIds:z.array(int),unavailable:list,delivery:str}),propose_review:proposed("review",{operation:z.enum(["note","revise"])}),recap:recapOutput,list_repos:z.looseObject({repos:rows({repo:str})}),find_tools:z.looseObject({tools:rows({name:str,summary:str}),next:str}),get_project_tools:z.looseObject({rule:str,tools:rows({name:str}),connectBySigningIn:list,commonTools:list,foundOnThisComputer:list,notice:str}),get_flows:z.union([z.looseObject({flow:int,name:str,steps:rows({id:str,title:str,kind:str}),cards:rows({card:int,title:str}),scripts:list,triggers:list,rule:str}),z.looseObject({flows:rows({flow:int,name:str,cards:int,needYou:int,triggers:int}),templates:list,scripts:list,rule:str})]),propose_flow:cardDrafted,get_subagents:z.looseObject({subagents:rows({subagent:int,name:str,working:z.boolean(),soul:str}),templates:list,rule:str}),propose_subagent:cardDrafted,get_flow_insights:z.union([z.looseObject({days:int,flows:rows({flow:int,name:str})}),z.looseObject({card:int,entry:int,state:str,log:str}),z.looseObject({runs:list,rule:str})]),get_skills:z.union([z.looseObject({version:str,instructions:str,nextOffset:nullable(int),notice:str}),z.looseObject({skills:list,nextOffset:nullable(int)})]),get_project_knowledge:z.looseObject({revision:int}),get_flaky_tests:z.looseObject({notice:z.string()}),get_task_conversation:z.looseObject({task:str,messages:rows({from:z.enum(["operator","lead"]),text:str,at:str}),notice:nullable(str)}),commit_to:z.looseObject({commitment:int,condition:str,expires:str,report:str}),release_commitment:z.looseObject({commitment:int,state:z.literal("cancelled")}),remember:z.looseObject({proposal:int,label:str,awaiting:str,executed:z.literal(!1),next:str}),manage_standing_directions:z.union([z.looseObject({action:z.literal("list"),directions:list}),z.looseObject({action:z.literal("add"),direction:z.looseObject({id:str,scope:str,text:str,enabled:z.boolean()})}),z.looseObject({action:z.literal("toggle"),direction:z.looseObject({id:str,scope:str,text:str,enabled:z.boolean()})}),z.looseObject({action:z.literal("remove"),removed:z.literal(!0),id:str})]),get_person:z.union([z.looseObject({person:z.looseObject({})}),z.looseObject({several:list,next:str})]),get_integrations:z.looseObject({integrations:rows({name:str,kind:str,state:str}),settings:str}),get_capabilities:z.looseObject({projects:rows({repo:str}),workers:z.unknown(),integrations:z.unknown(),rule:str}),ask_owner:z.looseObject({asked:str,options:z.array(str),shown:str}),search_project_memory:z.looseObject({hits:list,notice:str}),get_models:z.looseObject({roles:rows({role:str}),tools:list,newModels:list,change:str}),list_tasks:z.looseObject({tasks:rows({repo:str,task:str,execution:str,title:str,state:str,ageHours:z.number(),strikes:int}),truncated:z.boolean()}),tidy_preview:z.looseObject({count:int,days:int,groups:rows({label:str}),digest:str,apply:str}),get_task:z.looseObject({repo:str,task:str,root:str,currentExecution:str,title:str,state:str,deliverable:str,scope:str,queue:nullable(z.looseObject({position:int,of:int,column:str})),holds:list,attempts:int,decisionsOpen:int,dependencies:list}),get_agents:z.looseObject({repo:str,task:str,standing:str,agents:list,choices:z.looseObject({}),approval:str,organisationPolicy:z.looseObject({})}),list_decisions:decisionsOutput,get_decision:decisionOutput,queue:z.looseObject({repo:str,queueRevision:int,...queueColumnsOutput}),propose_task:proposed("task",{repo:str,deliverable:z.enum(["branch","report"]),planning:str}),propose_start:z.looseObject({proposal:int,kind:z.enum(["action","task"]),startsNow:z.boolean(),awaiting:str}),propose_sweep:cardDrafted,get_sweep:z.looseObject({sweep:int,title:str,line:str,table:str,maxParallel:int,items:z.array(z.looseObject({item:int,label:str,task:str,state:str}))}),propose_sweep_cancel:cardDrafted,propose_next:proposed("next",{task:str}),propose_reserve:proposed("reserve",{task:str,worker:nullable(str)}),propose_hold:proposed("hold",{task:str}),propose_unhold:proposed("unhold",{task:str}),propose_steer:proposed("steer",{task:str}),propose_dependency_repair:proposed("repair",{task:str,blocker:str,operation:z.enum(["retry","unlink","replace"])}),propose_scope:proposed("scope",{task:str}),propose_agents:proposed("agents",{task:str}),propose_answer:proposed("answer",{decision:int,option:str}),propose_cancel:proposed("cancel",{task:str}),toolroll_view_read:z.looseObject({settings:z.looseObject({}),allowed:z.looseObject({}),roles:list,themes:z.looseObject({}),guide:str}),toolroll_view_set:z.looseObject({changed:z.array(str),said:str}),list_direct_chats:z.looseObject({chats:rows({chat:str,title:str,provider:str,model:str,running:z.boolean()}),total:int}),get_direct_chat:z.looseObject({chat:str,title:str,provider:str,model:str,running:z.boolean(),turns:list}),get_direct_chat_diff:z.looseObject({chat:str,title:str,branch:str,running:z.boolean(),changedFiles:z.array(str),dirty:z.boolean(),canShip:z.boolean(),canAutoMerge:z.boolean(),recommendedMode:str}),manage_direct_chat:z.looseObject({chat:str,operation:str,said:str}),get_usage_limits:z.looseObject({summary:nullable(str),windows:list,budgets:list}),get_recent_updates:z.looseObject({since:str,headline:str,tasksReady:list,tasksCompleted:list,tasksFailed:list,directChatsUpdated:list,openDecisions:list}),get_attachment:z.looseObject({file:str,name:str,type:str,offset:int,total:int,text:str,nextOffset:nullable(int),notice:str}),propose_direct_chat:cardDrafted,propose_report_followups:z.looseObject({task:str,reportTitle:str,drafted:rows({index:int,proposal:int,title:str}),awaiting:str}),shared_browser:z.looseObject({action:z.enum(["status","open","screenshot","request_human_takeover","close"])})};export function reportToolOutput(surface,tool,schema,body){const read=parseContract(schema,body);if(read.ok)return;const line=`${surface} tool ${tool}: its result disagrees with its output schema — ${read.issues.map(one=>one.line).join("; ")}`;process.stderr.write(`${line}
1
+ import{z}from"zod";import{CHAT_ACTIONS}from"../chat-actions.js";import{RESULT_IMAGES_PER_TURN_CAP}from"../chat-evidence.js";import{CARD_CATALOG,CARD_SOURCES,CARD_TASK_STATES}from"../card-catalog.js";import{CHAT_CONTROLS}from"../chat-controls.js";import{CARD_CHART_TYPES,CARD_LIMITS}from"./chat-card.js";import{CHAT_TASK_ACTIONS}from"../chat-task-actions.js";import{LIMITS}from"../decision.js";import{CHECK_RESULTS,RUN_OUTCOMES,TASK_STATES}from"../lead-commitments.js";import{PERSON_ID}from"../lead-people.js";import{TASK_SIZES}from"../phase-routing.js";import{ACCEPTANCE_LIMITS}from"../scope.js";import{SUBAGENT_TEMPLATES}from"../subagents.js";import{TEXT_LIMITS}from"../text-limits.js";import{parseContract}from"./contract.js";import{FLOW_ALIASES}from"./flow.js";import{proposeFlowInputSchema}from"./flow-propose.js";import{acceptanceCriterionSchema}from"./plan.js";const enumOf=values=>z.enum(values);export const text=key=>z.string().max(TEXT_LIMITS[key]);const id=z.int().min(1),offset=z.int().min(0),planning=z.enum(["auto","required","skip"]),dcChatId=z.string().min(1).max(80),dcProvider=z.enum(["claude","codex","gemini"]),dcEffort=z.enum(["low","medium","high","xhigh","max","ultra"]);function overBy(limit,input){const count=n=>n.toLocaleString("en-US");return`over ${count(limit)} characters (it is ${typeof input=="string"?count(input.length):"longer"}): shorten it and call again`}export const taskRef=z.string().min(1).max(TEXT_LIMITS.taskRef),repoId=z.string().regex(/^r[0-9]{1,3}$/),scopeText=z.string().max(TEXT_LIMITS.goal,{error:issue=>overBy(TEXT_LIMITS.goal,issue.input)}).describe(`At most ${TEXT_LIMITS.goal.toLocaleString("en-US")} characters (UTF-16 code units) and ${TEXT_LIMITS.goalBytes.toLocaleString("en-US")} UTF-8 bytes; no control or disguised text. Longer text is refused with its length, not cut: shorten it and call again.`),touches=z.array(text("taskTouch")).max(50),acceptance=z.array(acceptanceCriterionSchema).min(1).max(ACCEPTANCE_LIMITS.criteria);const note=z.string().max(LIMITS.note,{error:issue=>overBy(LIMITS.note,issue.input)}).describe(`At most ${LIMITS.note} characters; longer is refused with its length, not cut.`);export const CODE_MAP_VIEWS=["overview","area","file","search"];const VIEW_THEME_NAME=/^[a-z][a-z0-9-]{0,31}$/,VIEW_ROLES=["paper","ink","muted","line","selection","selection-ink","ground","raised","fill","chat-bubble","chat-bubble-ink"],viewHex=z.string().regex(/^#[0-9a-fA-F]{6}$/),viewColors=z.strictObject({paper:viewHex.optional(),ink:viewHex.optional(),muted:viewHex.optional(),line:viewHex.optional(),selection:viewHex.optional(),"selection-ink":viewHex.optional(),ground:viewHex.optional(),raised:viewHex.optional(),fill:viewHex.optional(),"chat-bubble":viewHex.optional(),"chat-bubble-ink":viewHex.optional()});export const LISTED_TASK_STATES=["queued","running","done","failed","cancelled"];const ACTION_OPERATIONS=Object.keys(CHAT_ACTIONS).filter(one=>!one.startsWith("flow_")&&!one.startsWith("subagent_")&&!one.startsWith("direct_chat_")&&one!=="task_start"&&one!=="task_handoff"&&one!=="workflow_orchestrate"),cardProps=z.strictObject({source:z.enum(CARD_SOURCES).optional(),chart:z.enum(CARD_CHART_TYPES).optional(),columns:z.array(z.string().max(40)).max(CARD_LIMITS.columns).optional(),facts:z.array(z.string().max(40)).max(CARD_LIMITS.facts).optional(),repo:repoId.optional(),state:z.enum(CARD_TASK_STATES).optional(),limit:z.int().min(1).max(CARD_LIMITS.rows).optional(),flow:id.optional(),days:z.int().min(1).max(90).optional(),text:z.string().max(CARD_LIMITS.text).optional(),control:enumOf(Object.keys(CHAT_CONTROLS)).optional(),task:taskRef.optional(),run:id.optional(),proposal:id.optional()}),cardSpec=z.strictObject({root:z.string().max(40),elements:z.object({}).catchall(z.strictObject({type:enumOf(Object.keys(CARD_CATALOG.data.components)),props:cardProps,children:z.array(z.string().max(40)).max(16)}))});export const LEAD_TOOL_INPUTS={get_brief:z.strictObject({repo:repoId.optional()}),get_project_activity:z.strictObject({repo:repoId,offset:offset.optional()}),get_project_context:z.strictObject({repo:repoId,query:text("contextQuery").min(1),mode:z.enum(["search","impact"]).optional()}),get_code_map:z.strictObject({repo:repoId,version:id.optional(),view:z.enum(CODE_MAP_VIEWS),id:text("projectPath").optional(),query:text("contextQuery").optional(),cursor:z.string().max(40).optional()}),refresh_code_map:z.strictObject({repo:repoId}),get_action_status:z.strictObject({proposal:id}),get_actions:z.strictObject({}),propose_action:z.strictObject({operation:enumOf(ACTION_OPERATIONS),repo:z.string().optional(),task:taskRef.optional(),version:z.string().optional(),restore:id.optional(),sample:text("actionSample").optional(),content:text("actionContent").optional(),instructions:text("flowInstructions").optional(),title:text("actionTitle").optional(),id:z.string().optional(),run:id.optional(),note:note.optional(),catalog:text("actionName").optional(),name:text("actionName").optional(),command:text("actionCommand").optional(),args:z.array(text("actionCommand")).max(40).optional(),url:text("actionUrl").optional(),secrets:z.array(text("actionSecret")).max(12).optional(),about:text("actionAbout").optional(),on:z.boolean().optional(),finding:id.optional(),summary:text("actionAbout").optional(),file:text("actionName").optional(),line:id.optional(),pointer:z.string().max(40).optional(),revision:id.optional(),incident:id.optional(),provider:z.string().max(40).optional(),runner:text("actionName").optional(),persona:note.optional(),proposal:id.optional(),decision:z.enum(["accept","reject"]).optional(),reason:text("actionAbout").optional()}),propose_task_action:z.strictObject({task:taskRef,operation:enumOf(Object.keys(CHAT_TASK_ACTIONS)),dependency:taskRef.optional(),run:id.optional()}),get_controls:z.strictObject({}),show_control:z.strictObject({control:enumOf(Object.keys(CHAT_CONTROLS)),task:taskRef.optional(),repo:repoId.optional(),run:id.optional()}),show_card:z.strictObject({spec:cardSpec}),get_findings:z.strictObject({task:taskRef.optional(),repo:repoId.optional()}),offer_approval:z.strictObject({task:taskRef.optional(),card:id.optional()}),get_result:z.strictObject({task:taskRef,run:id.optional(),feedback_offset:offset.optional()}),get_diff:z.strictObject({task:taskRef,run:id.optional(),file:text("diffPath").min(1).optional(),offset:offset.optional()}),get_check_log:z.strictObject({task:taskRef,run:id.optional(),search:text("logSearch").min(2).optional(),offset:offset.optional()}),get_acceptance_evidence:z.strictObject({task:taskRef,run:id.optional(),offset:offset.optional()}),get_result_images:z.strictObject({task:taskRef,run:id.optional(),offset:offset.optional(),images:z.array(id).min(1).max(RESULT_IMAGES_PER_TURN_CAP).optional()}),propose_review:z.strictObject({run:id,operation:z.enum(["note","revise"]),build_now:z.boolean().optional(),note:z.string().max(LIMITS.note).nullable().optional(),path:text("diffPath").nullable().optional(),line:z.int().min(1).max(1e6).nullable().optional(),saved_notes:z.array(id).max(100).optional(),image:id.nullable().optional().describe("Screenshot artifact id from get_result_images; attaches the exact verified image to this feedback. null leaves off the screenshot a reply targets.")}),recap:z.strictObject({since:text("recapSince").optional()}),list_repos:z.strictObject({}),find_tools:z.strictObject({query:z.string().min(1).max(200).describe('What you want to do, in a few words ("make a flow", "add a subagent", "hold a task").')}),get_project_tools:z.strictObject({repo:repoId}),get_flows:z.strictObject({repo:repoId.optional(),flow:id.optional(),card:id.optional()}),propose_flow:proposeFlowInputSchema,get_subagents:z.strictObject({repo:repoId.optional(),subagent:id.optional()}),propose_subagent:z.strictObject({operation:z.enum(["ask","create","edit_section","edit_soul","pause","resume","remove","note","answer","use_tool","stop_tool","tool_rule","forget","edit_memory","add_routine","stop_routine","undo"]),section:text("subagentSection").optional(),schedule:text("subagentSchedule").optional(),routine:id.optional(),memory:id.optional(),tool:text("subagentTool").optional(),action:text("subagentAction").optional(),undoWith:text("subagentAction").optional(),call:id.optional(),use:z.enum(["free","ask","never"]).optional(),limitField:text("subagentAction").optional(),limitOver:z.number().min(0).optional(),repo:repoId.optional(),subagent:id.optional(),template:enumOf(SUBAGENT_TEMPLATES.map(one=>one.id)).optional(),name:text("subagentName").optional(),soul:text("subagentSoul").optional(),note:text("subagentNote").optional(),question:id.optional(),choice:text("subagentChoice").optional(),text:text("subagentText").optional()}),get_flow_insights:z.strictObject({repo:repoId.optional(),flow:id.optional(),days:z.int().min(1).max(90).optional(),card:id.optional(),entry:id.optional()}),get_skills:z.strictObject({repo:repoId,version:z.string().regex(/^[a-f0-9]{20}$/).optional(),offset:offset.optional()}),get_project_knowledge:z.strictObject({repo:repoId,reference:text("knowledgeReference").optional(),decision:id.optional()}),get_flaky_tests:z.strictObject({repo:repoId,row:text("knowledgeReference").optional()}),get_task_conversation:z.strictObject({task:taskRef,limit:z.int().min(1).max(30).optional()}),commit_to:z.strictObject({what:text("promise").min(3),when:z.enum(["task","run","check","time"]),task:taskRef.optional(),run:id.optional(),states:z.array(enumOf(TASK_STATES)).min(1).max(6).optional(),outcome:z.enum(RUN_OUTCOMES).optional(),result:z.enum(CHECK_RESULTS).optional(),at:z.string().optional(),checkAfter:z.string().optional()}),release_commitment:z.strictObject({commitment:id,reason:text("promise").min(3)}),remember:z.strictObject({repo:repoId.optional(),kind:z.enum(["decision","instruction","about-you"]),text:text("rememberText").min(3),why:text("rememberWhy").optional(),source:text("rememberSource").optional(),revision:offset.optional(),replaces:z.int().min(1).max(20).optional()}),manage_standing_directions:z.strictObject({action:z.enum(["list","add","toggle","remove"]),scope:z.string().max(256).optional(),repo:repoId.optional(),text:z.string().max(500).optional(),id:z.string().max(64).optional(),enabled:z.boolean().optional()}),get_person:z.strictObject({id:z.string().regex(PERSON_ID).optional(),name:text("personName").min(1).optional()}),get_integrations:z.strictObject({}),get_capabilities:z.strictObject({repo:repoId.optional()}),ask_owner:z.strictObject({question:text("ownerQuestion").min(3),options:z.array(text("ownerOption").min(1)).min(2).max(4)}),search_project_memory:z.strictObject({query:text("memorySearch").min(2),repo:repoId.optional()}),get_models:z.strictObject({}),list_tasks:z.strictObject({repo:repoId.optional(),state:z.enum(LISTED_TASK_STATES).optional(),limit:z.int().min(1).max(50).optional(),search:text("taskSearch").optional()}),tidy_preview:z.strictObject({days:z.int().min(1).max(365).optional()}),get_task:z.strictObject({task:taskRef}),get_agents:z.strictObject({task:taskRef}),list_decisions:z.strictObject({}),get_decision:z.strictObject({decision:id}),queue:z.strictObject({repo:repoId}),propose_task:z.strictObject({repo:repoId,title:text("taskTitle"),goal:scopeText,not:scopeText.nullable().optional(),touches:touches.optional(),acceptance,planning:planning.optional(),report:z.boolean().optional(),checks:text("checksWords").optional()}),propose_start:z.strictObject({repo:repoId,title:text("taskTitle")}),propose_sweep:z.strictObject({repo:repoId,title:text("taskTitle"),brief:scopeText,items:z.array(z.strictObject({title:text("taskTitle"),item:scopeText})).min(2).max(20),acceptance,max_parallel:z.number().int().min(1).max(8).optional()}),get_sweep:z.strictObject({sweep:id}),propose_sweep_cancel:z.strictObject({sweep:id}),propose_next:z.strictObject({task:taskRef}),propose_reserve:z.strictObject({task:taskRef,worker:text("workerName").nullable()}),propose_hold:z.strictObject({task:taskRef,reason:text("proposalReason")}),propose_unhold:z.strictObject({task:taskRef}),propose_steer:z.strictObject({task:taskRef,note:note.optional(),mode:z.enum(["note","pause","pause-and-steer","resume"]).optional(),question:z.number().int().positive().optional().describe("A running agent's open question (get_task agentQuestions): the note becomes its reply and closes it.")}),propose_dependency_repair:z.strictObject({task:taskRef,blocker:taskRef,operation:z.enum(["retry","unlink","replace"]),replacement:taskRef.optional()}),propose_scope:z.strictObject({task:taskRef,goal:scopeText,not:scopeText.nullable().optional(),touches:touches.optional(),acceptance}),propose_agents:z.strictObject({task:taskRef,size:z.enum(TASK_SIZES).optional(),risky:z.boolean().optional(),role:z.enum(["planner","builder","repair"]).optional(),agent:z.strictObject({provider:text("agentProvider"),model:text("agentModel")}).optional(),clear:z.boolean().optional(),why:text("agentWhy").optional()}),propose_answer:z.strictObject({decision:id,option:text("answerOption").min(1),rationale:text("answerRationale")}),propose_cancel:z.strictObject({task:taskRef,reason:text("proposalReason")}),toolroll_view_read:z.strictObject({}),toolroll_view_set:z.strictObject({theme:z.string().regex(VIEW_THEME_NAME).optional().describe("A built-in theme (terminal, light, dark, high-contrast) or a saved theme's name."),save_theme:z.strictObject({name:z.string().regex(VIEW_THEME_NAME).describe("Lowercase letters, digits and dashes, at most 32; not a built-in theme's name."),base:z.enum(["terminal","light","dark","high-contrast"]),colors:viewColors.optional(),use:z.boolean().optional().describe("true: switch to it now.")}).optional(),colors:viewColors.optional().describe("Role colours laid over the theme."),density:z.enum(["compact","comfortable"]).optional(),glyphs:z.enum(["unicode","ascii","nerd"]).optional(),columns:z.array(z.enum(["agent","step","age","cost","project"])).max(5).optional(),list_side:z.enum(["left","right"]).optional(),reduced_motion:z.boolean().optional(),key_bar:z.boolean().optional(),show_costs:z.boolean().optional(),notifications:z.strictObject({asks:z.boolean().optional(),finished:z.boolean().optional(),failed:z.boolean().optional()}).optional()}),list_direct_chats:z.strictObject({repo:repoId.optional(),include_archived:z.boolean().optional(),limit:z.int().min(1).max(40).optional()}),get_direct_chat:z.strictObject({chat:dcChatId,limit:z.int().min(1).max(30).optional()}),get_direct_chat_diff:z.strictObject({chat:dcChatId,max_patch_chars:z.int().min(200).max(2e4).optional()}),manage_direct_chat:z.strictObject({chat:dcChatId,operation:z.enum(["stop","archive","unarchive","set_model","rename"]),provider:dcProvider.optional(),model:z.string().min(1).max(120).optional(),effort:dcEffort.nullable().optional(),title:z.string().min(1).max(160).optional()}),get_usage_limits:z.strictObject({}),get_recent_updates:z.strictObject({repo:repoId.optional(),since:text("recapSince").optional(),hours:z.int().min(1).max(168).optional()}),get_attachment:z.strictObject({file:z.string().regex(/^[0-9]{1,15}\.[0-9]{1,2}$/),offset:z.int().min(0).max(1e8).optional()}),propose_direct_chat:z.strictObject({operation:z.enum(["start","reply","promote","ship"]),repo:repoId.optional(),chat:dcChatId.optional(),prompt:note.optional(),provider:dcProvider.optional(),model:z.string().min(1).max(120).optional(),effort:dcEffort.nullable().optional(),mode:z.enum(["ship","keep-branch"]).optional(),title:text("taskTitle").optional(),goal:scopeText.optional(),planning:planning.optional()}),propose_report_followups:z.strictObject({task:taskRef,indices:z.array(z.int().min(1).max(20)).min(1).max(5).optional(),planning:planning.optional()}),shared_browser:z.strictObject({action:z.enum(["status","open","screenshot","request_human_takeover","close"]),profile:z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/).optional(),session:z.string().min(1).max(48).optional(),url:z.string().min(1).max(2e3).optional(),reason:z.string().min(1).max(120).optional()}),handoff_task:z.strictObject({task:taskRef,toAgent:text("agentProvider"),toModel:text("agentModel").optional(),note:note.optional()}),orchestrate_workflow:z.strictObject({repo:repoId,title:text("taskTitle"),mode:z.enum(["sequential","parallel"]).optional(),goal:scopeText,steps:z.array(z.strictObject({title:text("taskTitle"),agent:text("agentProvider"),model:text("agentModel").optional(),role:z.enum(["build","review","test","research"]).optional(),instructions:scopeText,handoffFromPrevious:z.boolean().optional()})).min(2).max(8),acceptance:acceptance.optional()})},LEAD_TOOL_READ_INPUTS={...LEAD_TOOL_INPUTS,list_tasks:LEAD_TOOL_INPUTS.list_tasks.extend({limit:z.unknown().optional()}),get_task_conversation:LEAD_TOOL_INPUTS.get_task_conversation.extend({limit:z.unknown().optional()}),get_flow_insights:LEAD_TOOL_INPUTS.get_flow_insights.extend({repo:repoId.nullable().optional(),days:z.unknown().optional()}),get_person:LEAD_TOOL_INPUTS.get_person.extend({id:z.unknown().optional(),name:z.unknown().optional()}),propose_agents:LEAD_TOOL_INPUTS.propose_agents.extend({agent:LEAD_TOOL_INPUTS.propose_agents.shape.agent.unwrap().strip().optional()})},LEAD_TOOL_OPTIONS={propose_flow:FLOW_ALIASES},str=z.string(),int=z.number().int(),list=z.array(z.unknown()),nullable=schema=>schema.nullable(),rows=shape=>z.array(z.looseObject(shape));const cardDrafted=z.looseObject({proposal:int,label:str,awaiting:str,executed:z.literal(!1)}),proposed=(kind,shape={})=>z.looseObject({proposal:int,kind:z.literal(kind),awaiting:str,...shape});export const codeMapOutput=z.looseObject({v:z.literal(1),ok:z.boolean()}),repositoryContextOutput=z.looseObject({version:z.literal(1),readOnly:z.boolean(),query:str,mode:z.enum(["search","impact"]),asOf:str,excerpts:list}),catchUpOutput=z.looseObject({version:z.literal(1),asOf:str,readOnly:z.literal(!0),assignments:list,projects:list,omissions:z.looseObject({})}),recapOutput=z.looseObject({since:nullable(str),repos:list,waitsOnYou:z.looseObject({decisions:list,incidents:int,scopesAwaitingApproval:list}),running:list,truncated:z.boolean()}),decisionsOutput=z.looseObject({decisions:rows({decision:int,task:str,question:str,options:list,ageHours:z.number()}),truncated:z.boolean()}),decisionOutput=z.looseObject({repo:str,decision:int,task:str,state:str,question:str,options:rows({id:str,label:str,reversible:z.boolean(),consequence:str}),ageHours:z.number()}),queueColumnsOutput={columns:rows({column:str,tasks:list})},LEAD_TOOL_OUTPUTS={get_brief:catchUpOutput,get_project_activity:z.looseObject({asOf:str,since:str,days:int,limit:int,truncated:z.boolean(),ready:z.object({count:int,oldestFinishedAgeMs:nullable(int),dated:int}),completed:z.looseObject({count:int}),families:list,familiesTotal:int,familiesOffset:int,nextOffset:nullable(int),incompleteHistory:int}),get_project_context:repositoryContextOutput,get_code_map:codeMapOutput,refresh_code_map:z.looseObject({request:z.enum(["queued","already-queued"])}),get_action_status:z.looseObject({proposal:int,operation:str,state:str,outcome:z.unknown(),finishedAt:nullable(str)}),get_actions:z.looseObject({actions:rows({operation:str,label:str,secureReview:z.boolean(),inputs:z.array(str)}),notice:str}),propose_action:cardDrafted,propose_task_action:z.looseObject({proposal:int,action:str,awaiting:str}),get_controls:z.looseObject({confirmedInChat:z.array(str),existingControls:rows({id:str,label:str,needsTask:z.boolean(),needsProject:z.boolean()}),rule:str}),show_control:z.looseObject({card:int,label:str,action:str}),show_card:z.looseObject({card:int,title:str,shows:z.array(str)}),get_findings:z.looseObject({findings:z.array(z.looseObject({finding:int,task:str,state:str})),rule:str}),offer_approval:z.looseObject({offered:z.boolean()}),get_result:z.looseObject({task:str,root:str,currentExecution:str,run:int,title:str,feedback:list,feedbackTotal:int,nextFeedbackOffset:nullable(int),changes:str,changesShortened:z.boolean(),verification:str,accepted:z.boolean(),evidenceTool:str,canRevise:z.boolean()}),get_diff:z.looseObject({task:str,run:int,files:rows({path:str,added:int,removed:int}).optional(),file:str.optional(),diff:str.optional(),nextOffset:nullable(int).optional(),notice:nullable(str)}),get_check_log:z.looseObject({task:str,run:int,log:str,notice:nullable(str)}),get_acceptance_evidence:z.looseObject({task:str,run:int}),get_result_images:z.looseObject({task:str,run:int,imageCount:int,images:rows({id:int,position:int,selected:z.boolean()}),selected:z.array(int),selectedCount:int,sendCount:int,nextImageOffset:nullable(int),nextImageIds:z.array(int),unavailable:list,delivery:str}),propose_review:proposed("review",{operation:z.enum(["note","revise"])}),recap:recapOutput,list_repos:z.looseObject({repos:rows({repo:str})}),find_tools:z.looseObject({tools:rows({name:str,summary:str}),next:str}),get_project_tools:z.looseObject({rule:str,tools:rows({name:str}),connectBySigningIn:list,commonTools:list,foundOnThisComputer:list,notice:str}),get_flows:z.union([z.looseObject({flow:int,name:str,steps:rows({id:str,title:str,kind:str}),cards:rows({card:int,title:str}),scripts:list,triggers:list,rule:str}),z.looseObject({flows:rows({flow:int,name:str,cards:int,needYou:int,triggers:int}),templates:list,scripts:list,rule:str})]),propose_flow:cardDrafted,get_subagents:z.looseObject({subagents:rows({subagent:int,name:str,working:z.boolean(),soul:str}),templates:list,rule:str}),propose_subagent:cardDrafted,get_flow_insights:z.union([z.looseObject({days:int,flows:rows({flow:int,name:str})}),z.looseObject({card:int,entry:int,state:str,log:str}),z.looseObject({runs:list,rule:str})]),get_skills:z.union([z.looseObject({version:str,instructions:str,nextOffset:nullable(int),notice:str}),z.looseObject({skills:list,nextOffset:nullable(int)})]),get_project_knowledge:z.looseObject({revision:int}),get_flaky_tests:z.looseObject({notice:z.string()}),get_task_conversation:z.looseObject({task:str,messages:rows({from:z.enum(["operator","lead"]),text:str,at:str}),notice:nullable(str)}),commit_to:z.looseObject({commitment:int,condition:str,expires:str,report:str}),release_commitment:z.looseObject({commitment:int,state:z.literal("cancelled")}),remember:z.looseObject({proposal:int,label:str,awaiting:str,executed:z.literal(!1),next:str}),manage_standing_directions:z.union([z.looseObject({action:z.literal("list"),directions:list}),z.looseObject({action:z.literal("add"),direction:z.looseObject({id:str,scope:str,text:str,enabled:z.boolean()})}),z.looseObject({action:z.literal("toggle"),direction:z.looseObject({id:str,scope:str,text:str,enabled:z.boolean()})}),z.looseObject({action:z.literal("remove"),removed:z.literal(!0),id:str})]),get_person:z.union([z.looseObject({person:z.looseObject({})}),z.looseObject({several:list,next:str})]),get_integrations:z.looseObject({integrations:rows({name:str,kind:str,state:str}),settings:str}),get_capabilities:z.looseObject({projects:rows({repo:str}),workers:z.unknown(),integrations:z.unknown(),rule:str}),ask_owner:z.looseObject({asked:str,options:z.array(str),shown:str}),search_project_memory:z.looseObject({hits:list,notice:str}),get_models:z.looseObject({roles:rows({role:str}),tools:list,newModels:list,change:str}),list_tasks:z.looseObject({tasks:rows({repo:str,task:str,execution:str,title:str,state:str,ageHours:z.number(),strikes:int}),truncated:z.boolean()}),tidy_preview:z.looseObject({count:int,days:int,groups:rows({label:str}),digest:str,apply:str}),get_task:z.looseObject({repo:str,task:str,root:str,currentExecution:str,title:str,state:str,deliverable:str,scope:str,queue:nullable(z.looseObject({position:int,of:int,column:str})),holds:list,attempts:int,decisionsOpen:int,dependencies:list}),get_agents:z.looseObject({repo:str,task:str,standing:str,agents:list,choices:z.looseObject({}),approval:str,organisationPolicy:z.looseObject({})}),list_decisions:decisionsOutput,get_decision:decisionOutput,queue:z.looseObject({repo:str,queueRevision:int,...queueColumnsOutput}),propose_task:proposed("task",{repo:str,deliverable:z.enum(["branch","report"]),planning:str}),propose_start:z.looseObject({proposal:int,kind:z.enum(["action","task"]),startsNow:z.boolean(),awaiting:str}),propose_sweep:cardDrafted,get_sweep:z.looseObject({sweep:int,title:str,line:str,table:str,maxParallel:int,items:z.array(z.looseObject({item:int,label:str,task:str,state:str}))}),propose_sweep_cancel:cardDrafted,propose_next:proposed("next",{task:str}),propose_reserve:proposed("reserve",{task:str,worker:nullable(str)}),propose_hold:proposed("hold",{task:str}),propose_unhold:proposed("unhold",{task:str}),propose_steer:proposed("steer",{task:str}),propose_dependency_repair:proposed("repair",{task:str,blocker:str,operation:z.enum(["retry","unlink","replace"])}),propose_scope:proposed("scope",{task:str}),propose_agents:proposed("agents",{task:str}),propose_answer:proposed("answer",{decision:int,option:str}),propose_cancel:proposed("cancel",{task:str}),toolroll_view_read:z.looseObject({settings:z.looseObject({}),allowed:z.looseObject({}),roles:list,themes:z.looseObject({}),guide:str}),toolroll_view_set:z.looseObject({changed:z.array(str),said:str}),list_direct_chats:z.looseObject({chats:rows({chat:str,title:str,provider:str,model:str,running:z.boolean()}),total:int}),get_direct_chat:z.looseObject({chat:str,title:str,provider:str,model:str,running:z.boolean(),turns:list}),get_direct_chat_diff:z.looseObject({chat:str,title:str,branch:str,running:z.boolean(),changedFiles:z.array(str),dirty:z.boolean(),canShip:z.boolean(),canAutoMerge:z.boolean(),recommendedMode:str}),manage_direct_chat:z.looseObject({chat:str,operation:str,said:str}),get_usage_limits:z.looseObject({summary:nullable(str),windows:list,budgets:list}),get_recent_updates:z.looseObject({since:str,headline:str,tasksReady:list,tasksCompleted:list,tasksFailed:list,directChatsUpdated:list,openDecisions:list}),get_attachment:z.looseObject({file:str,name:str,type:str,offset:int,total:int,text:str,nextOffset:nullable(int),notice:str}),propose_direct_chat:cardDrafted,propose_report_followups:z.looseObject({task:str,reportTitle:str,drafted:rows({index:int,proposal:int,title:str}),awaiting:str}),shared_browser:z.looseObject({action:z.enum(["status","open","screenshot","request_human_takeover","close"])}),handoff_task:cardDrafted,orchestrate_workflow:cardDrafted};export function reportToolOutput(surface,tool,schema,body){const read=parseContract(schema,body);if(read.ok)return;const line=`${surface} tool ${tool}: its result disagrees with its output schema — ${read.issues.map(one=>one.line).join("; ")}`;process.stderr.write(`${line}
2
2
  `)}
@@ -1 +1 @@
1
- import{z}from"zod";import{limited,versioned}from"./contract.js";const DECISION_STATUSES=["active","superseded","retired"],DECISION_SOURCES=["conversation","task","result","manual","backward-pass"],written=limited,saved=()=>z.string(),recordShape=text=>({repo:z.string(),revision:z.int().min(1),claim:text("decision","decisionClaimBytes"),why:text("reason","decisionWhyBytes"),status:z.enum(DECISION_STATUSES),supersedes:z.int().nullable(),decidedBy:z.string(),decidedAt:z.string(),sourceKind:z.enum(DECISION_SOURCES),sourceRef:text("source","decisionSourceBytes").nullable(),recordedBy:z.string()});export const decisionRecordSchema=z.strictObject(recordShape(written)),decisionSchema=z.strictObject({id:z.int(),...recordShape(saved)});const decisionDraftSchema=z.strictObject({claim:z.string(),why:z.string(),decidedBy:z.string().optional(),decidedAt:z.string().optional(),sourceKind:z.enum(DECISION_SOURCES).optional(),sourceRef:z.string().nullable().optional(),supersedes:z.int().nullable().optional()});export const decisionLineSchema=z.strictObject({id:z.int(),claim:z.string(),decidedAt:z.string(),revision:z.int().min(1).optional()}),DECISION_CHANGE_VERSION=1,decisionChangeSchema=z.union([versioned(DECISION_CHANGE_VERSION,recordShape(written)),versioned(DECISION_CHANGE_VERSION,{reason:limited("reason","decisionRetireBytes")})]);
1
+ import{z}from"zod";import{limited,versioned}from"./contract.js";const DECISION_STATUSES=["active","superseded","retired"],DECISION_SOURCES=["conversation","task","result","manual","backward-pass"],written=limited,saved=()=>z.string(),recordShape=text=>({repo:z.string(),revision:z.int().min(1),claim:text("decision","decisionClaimBytes"),why:text("reason","decisionWhyBytes"),status:z.enum(DECISION_STATUSES),supersedes:z.int().nullable(),decidedBy:z.string(),decidedAt:z.string(),sourceKind:z.enum(DECISION_SOURCES),sourceRef:text("source","decisionSourceBytes").nullable(),recordedBy:z.string()});export const decisionRecordSchema=z.strictObject(recordShape(written)),decisionSchema=z.strictObject({id:z.int(),...recordShape(saved)});const decisionDraftSchema=z.strictObject({claim:z.string(),why:z.string(),decidedBy:z.string().optional(),decidedAt:z.string().optional(),sourceKind:z.enum(DECISION_SOURCES).optional(),sourceRef:z.string().nullable().optional(),supersedes:z.int().nullable().optional()});export const decisionLineSchema=z.strictObject({id:z.int(),claim:z.string(),why:z.string().optional(),decidedAt:z.string(),revision:z.int().min(1).optional()}),DECISION_CHANGE_VERSION=1,decisionChangeSchema=z.union([versioned(DECISION_CHANGE_VERSION,recordShape(written)),versioned(DECISION_CHANGE_VERSION,{reason:limited("reason","decisionRetireBytes")})]);
@@ -1 +1 @@
1
- import{z}from"zod";export const PROVIDER_ID_VALUES=["claude","codex","openrouter","gemini","opencode","cursor","cline","qwen","goose","antigravity","grok","copilot","kiro","amp","droid"],providerIdSchema=z.enum(PROVIDER_ID_VALUES),MODEL_ID=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/,modelIdSchema=z.string().regex(MODEL_ID),agentSpecSchema=z.object({provider:providerIdSchema,model:modelIdSchema.nullable()});
1
+ import{z}from"zod";export const PROVIDER_ID_VALUES=["claude","codex","openrouter","gemini","opencode","cursor","cline","qwen","goose","antigravity","grok","copilot","kiro","amp","droid","pi"],providerIdSchema=z.enum(PROVIDER_ID_VALUES),MODEL_ID=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/,modelIdSchema=z.string().regex(MODEL_ID),agentSpecSchema=z.object({provider:providerIdSchema,model:modelIdSchema.nullable()});
@@ -1,5 +1,5 @@
1
- import{spawn}from"node:child_process";import{performance}from"node:perf_hooks";import{stopProcessTree}from"./process-tree.js";export async function superviseController(args){const retryMs=args.retryMs??1e3,maxRetryMs=args.maxRetryMs??3e4,stableMs=args.stableMs??3e4,shutdownMs=args.shutdownMs??45e3;for(const value of[retryMs,maxRetryMs,stableMs,shutdownMs])if(!Number.isSafeInteger(value)||value<1||value>2147483647)throw new Error("Invalid controller supervision interval.");if(maxRetryMs<retryMs)throw new Error("Controller restart ceiling must cover its initial delay.");let generation=0,failures=0,child=null,escalation=null;const emit=state=>{try{args.onState?.(state)}catch{process.stderr.write(`Controller supervisor could not record its status.
2
- `)}},stop=()=>{const owned=child;owned===null||owned.exitCode!==null||owned.signalCode!==null||(owned.kill("SIGTERM"),escalation===null&&(escalation=setTimeout(()=>{owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},shutdownMs)))};args.signal.addEventListener("abort",stop);try{for(;!args.signal.aborted;){generation++;const started=performance.now();if(emit({phase:"starting",generation,controllerPid:null}),args.signal.aborted)break;const exited=await new Promise(done=>{const output=args.label===void 0?"inherit":"pipe",owned=spawn(args.file,[...args.argv],{...args.cwd===void 0?{}:{cwd:args.cwd},...args.env===void 0?{}:{env:args.env},stdio:args.ipc===!0?["ignore",output,output,"ipc"]:args.label===void 0?"inherit":["ignore","pipe","pipe"],windowsHide:!0});if(child=owned,args.label!==void 0)for(const stream of[owned.stdout,owned.stderr])labelLines(stream,args.label);try{args.onSpawn?.(owned,generation)}catch{process.stderr.write(`Controller supervisor could not attach to its controller.
1
+ import{spawn}from"node:child_process";import{performance}from"node:perf_hooks";import{withoutLeadTokenEnv}from"./names.js";import{stopProcessTree}from"./process-tree.js";export async function superviseController(args){const retryMs=args.retryMs??1e3,maxRetryMs=args.maxRetryMs??3e4,stableMs=args.stableMs??3e4,shutdownMs=args.shutdownMs??45e3;for(const value of[retryMs,maxRetryMs,stableMs,shutdownMs])if(!Number.isSafeInteger(value)||value<1||value>2147483647)throw new Error("Invalid controller supervision interval.");if(maxRetryMs<retryMs)throw new Error("Controller restart ceiling must cover its initial delay.");let generation=0,failures=0,child=null,escalation=null;const emit=state=>{try{args.onState?.(state)}catch{process.stderr.write(`Controller supervisor could not record its status.
2
+ `)}},stop=()=>{const owned=child;owned===null||owned.exitCode!==null||owned.signalCode!==null||(owned.kill("SIGTERM"),escalation===null&&(escalation=setTimeout(()=>{owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},shutdownMs)))};args.signal.addEventListener("abort",stop);try{for(;!args.signal.aborted;){generation++;const started=performance.now();if(emit({phase:"starting",generation,controllerPid:null}),args.signal.aborted)break;const exited=await new Promise(done=>{const output=args.label===void 0?"inherit":"pipe",owned=spawn(args.file,[...args.argv],{...args.cwd===void 0?{}:{cwd:args.cwd},env:withoutLeadTokenEnv(args.env??process.env),stdio:args.ipc===!0?["ignore",output,output,"ipc"]:args.label===void 0?"inherit":["ignore","pipe","pipe"],windowsHide:!0});if(child=owned,args.label!==void 0)for(const stream of[owned.stdout,owned.stderr])labelLines(stream,args.label);try{args.onSpawn?.(owned,generation)}catch{process.stderr.write(`Controller supervisor could not attach to its controller.
3
3
  `)}owned.once("spawn",()=>{emit({phase:"running",generation,controllerPid:owned.pid??null}),args.signal.aborted&&stop()}),owned.once("error",()=>{}),owned.once("close",(code,signal)=>done({code,signal})),args.signal.aborted&&stop()});if(child=null,escalation!==null&&(clearTimeout(escalation),escalation=null),args.signal.aborted)break;failures=performance.now()-started>=stableMs?0:Math.min(failures+1,20);const delay=Math.min(maxRetryMs,retryMs*2**Math.max(0,failures-1));emit({phase:"backoff",generation,controllerPid:null,exit:exited,retryMs:delay}),await new Promise(done=>{let timer;const finish=()=>{clearTimeout(timer),args.signal.removeEventListener("abort",finish),done()};timer=setTimeout(finish,delay),args.signal.addEventListener("abort",finish,{once:!0}),args.signal.aborted&&finish()})}}finally{args.signal.removeEventListener("abort",stop),escalation!==null&&clearTimeout(escalation),emit({phase:"stopped",generation,controllerPid:null})}}function labelLines(stream,label){if(stream===null)return;const prefix=label===""?"":`${label} `;let pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{const lines=(pending+chunk).split(`
4
4
  `);pending=lines.pop()??"",pending.length>64*1024&&(lines.push(pending),pending="");for(const line of lines)process.stderr.write(`${prefix}${line}
5
5
  `)}),stream.on("end",()=>{pending!==""&&process.stderr.write(`${prefix}${pending}
package/dist/converse.js CHANGED
@@ -1,4 +1,4 @@
1
- import{takeEvalDispatch}from"./eval-gate.js";import{TASK_TEXT_LIMITS}from"./task-text.js";import{createHash}from"node:crypto";import{hasForbiddenControls,hasDisguisedText}from"./decision.js";import{parseAcceptanceCriteria}from"./scope.js";import{reportedCostUsdOf,reportedModelOf}from"./reported-usage.js";const WRAPPER_CAP_BYTES=262144,ENVELOPE_CAP_BYTES=65536;export const REPLY_CAP_BYTES=32768;const MAX_PROPOSALS=3;export const MAX_DEPTH=6,MAX_OUTPUT_TOKENS=2048,TURN_WALL_CLOCK_MS=12e4;const PRICES={"claude-sonnet-5":{inMicrousd:3,outMicrousd:15},"claude-opus-5":{inMicrousd:15,outMicrousd:75},"claude-haiku-4-5":{inMicrousd:1,outMicrousd:5},"anthropic/claude-sonnet-5":{inMicrousd:3,outMicrousd:15},"openai/gpt-5.2":{inMicrousd:2,outMicrousd:8}};export function priceOf(model){return PRICES[model]??null}export const PRICED_MODELS=Object.keys(PRICES);function toMicrousd(dollarsPerToken){return!Number.isFinite(dollarsPerToken)||dollarsPerToken<0?null:dollarsPerToken===0?0:Math.max(1,Math.ceil(dollarsPerToken*1e6))}export async function fetchOpenRouterCatalog(key,fetcher=fetch,signal){let response;try{response=await fetcher("https://openrouter.ai/api/v1/models",{headers:{authorization:`Bearer ${key}`},redirect:"error",...signal===void 0?{}:{signal}})}catch{return{ok:!1,problem:"network"}}if(response.status!==200)return{ok:!1,problem:`status-${response.status}`};const body=await readCappedBody(response,4194304);if(body===null)return{ok:!1,problem:"over-size"};let text;try{text=new TextDecoder("utf-8",{fatal:!0}).decode(body)}catch{return{ok:!1,problem:"not-utf8"}}let parsed;try{parsed=JSON.parse(text)}catch{return{ok:!1,problem:"not-json"}}const rows=parsed?.data;if(!Array.isArray(rows))return{ok:!1,problem:"wrong-shape"};const models=[];for(const row of rows){const id=row?.id,pricing=row?.pricing;if(typeof id!="string"||id.length>128||pricing===void 0)continue;const inMicrousd=toMicrousd(Number(pricing.prompt)),outMicrousd=toMicrousd(Number(pricing.completion));if(!(inMicrousd===null||outMicrousd===null)&&(models.push({id,price:{inMicrousd,outMicrousd}}),models.length>=500))break}return models.sort((a,b)=>a.id.localeCompare(b.id)),{ok:!0,models}}export function priceForConfig(config){return config.priceInMicrousd!==null&&config.priceOutMicrousd!==null?{inMicrousd:config.priceInMicrousd,outMicrousd:config.priceOutMicrousd}:priceOf(config.model)}export function worstCaseForPrice(price,promptBytes){return Math.ceil(promptBytes/3)*price.inMicrousd+MAX_OUTPUT_TOKENS*price.outMicrousd}export function settleForPrice(price,tokensIn,tokensOut){return tokensIn*price.inMicrousd+tokensOut*price.outMicrousd}export const DIRECT_CHAT_PROVIDERS=["anthropic-api","openrouter-api"];const SUBSCRIPTION_CHAT_PROVIDERS=["claude-subscription","codex-subscription"];export function isDirectChatProvider(provider){return DIRECT_CHAT_PROVIDERS.includes(provider)}export function isSubscriptionChatProvider(provider){return SUBSCRIPTION_CHAT_PROVIDERS.includes(provider)}export const CHAT_KEY_ENV={"anthropic-api":"ANTHROPIC_API_KEY","openrouter-api":"OPENROUTER_API_KEY"};export function credentialKeyOf(provider,key){return createHash("sha256").update(`standing-orders/chat/v1\0${provider}\0${key}`).digest("hex")}export function subscriptionCredentialKey(provider){return credentialKeyOf(provider,"cached-membership-login")}const KEY_SHAPES={"anthropic-api":/^sk-[A-Za-z0-9_-]{20,200}$/,"openrouter-api":/^sk-[A-Za-z0-9_-]{20,200}$/};export function plausibleChatKey(provider,key){return KEY_SHAPES[provider].test(key.trim())}export function strictJsonParse(bytes,maxBytes,maxDepth=MAX_DEPTH){if(bytes.length>maxBytes)return{ok:!1,problem:"over-size"};let text;try{text=new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}catch{return{ok:!1,problem:"not-utf8"}}const scanned=scan(text,maxDepth);if(scanned!==null)return{ok:!1,problem:scanned};try{return{ok:!0,value:JSON.parse(text)}}catch{return{ok:!1,problem:"not-json"}}}function scan(text,maxDepth){const stack=[];let index=0;const length=text.length,readString=()=>{let out="";for(index++;index<length;){const ch=text[index];if(ch==='"')return out;if(ch==="\\"){index+=2,out+="?";continue}out+=ch,index++}return null};for(;index<length;){const ch=text[index];if(ch==="{"){if(stack.push({kind:"obj",keys:new Set,expectKey:!0}),stack.length>maxDepth)return"too-deep"}else if(ch==="["){if(stack.push({kind:"arr"}),stack.length>maxDepth)return"too-deep"}else if(ch==="}"||ch==="]")stack.pop();else if(ch==='"'){const top=stack[stack.length-1];if(top!==void 0&&top.kind==="obj"&&top.expectKey){const key=readString();if(key===null)return"not-json";if(top.keys.has(key))return"duplicate-key";top.keys.add(key),top.expectKey=!1}else if(readString()===null)return"not-json"}else if(ch===","){const top=stack[stack.length-1];top!==void 0&&top.kind==="obj"&&(top.expectKey=!0)}index++}return null}const REPO_ID=/^r[0-9]{1,3}$/;function honest(text,maxChars,maxBytes){return text.length<=maxChars&&Buffer.byteLength(text,"utf8")<=maxBytes&&!hasForbiddenControls(text)&&!hasDisguisedText(text)}function exactKeys(value,keys){const present=Object.keys(value);return present.length===keys.length&&keys.every(key=>present.includes(key))}function readDraft(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return null;const body=raw,kind=body.kind;if(kind!=="task"||!exactKeys(body,["kind","repoId","title","goal","outOfScope","touches","acceptance"]))return null;const repoId=body.repoId,goal=body.goal,outOfScope=body.outOfScope,touches=body.touches;if(typeof repoId!="string"||!REPO_ID.test(repoId)||typeof goal!="string"||goal.trim()===""||!honest(goal,TASK_TEXT_LIMITS.text,TASK_TEXT_LIMITS.textBytes)||outOfScope!==null&&(typeof outOfScope!="string"||!honest(outOfScope,TASK_TEXT_LIMITS.text,TASK_TEXT_LIMITS.textBytes))||!Array.isArray(touches)||touches.length>50)return null;for(const one of touches)if(typeof one!="string"||one.trim()===""||!honest(one,200,800))return null;const acceptanceParse=parseAcceptanceCriteria(body.acceptance);if(acceptanceParse.problems.length>0||acceptanceParse.criteria.length===0)return null;const acceptance=acceptanceParse.criteria,title=body.title;return typeof title!="string"||title.trim()===""||!honest(title,200,800)?null:{kind,repoId,title,goal,outOfScope,touches,acceptance}}export function parseAssistantEnvelope(text){const parsed=strictJsonParse(Buffer.from(text,"utf8"),ENVELOPE_CAP_BYTES);if(!parsed.ok)return{ok:!1,problem:parsed.problem};const value=parsed.value;if(typeof value!="object"||value===null||Array.isArray(value))return{ok:!1,problem:"not-an-object"};const body=value;if(!exactKeys(body,["chatEnvelope","reply","proposals"]))return{ok:!1,problem:"wrong-keys"};if(body.chatEnvelope!==1)return{ok:!1,problem:"wrong-version"};const reply=body.reply;if(typeof reply!="string"||Buffer.byteLength(reply,"utf8")>REPLY_CAP_BYTES)return{ok:!1,problem:"bad-reply"};const rawProposals=body.proposals;if(!Array.isArray(rawProposals)||rawProposals.length>MAX_PROPOSALS)return{ok:!1,problem:"bad-proposals"};const drafts=[];let discarded=!1;for(const raw of rawProposals){const draft=readDraft(raw);if(draft===null){discarded=!0;break}drafts.push(draft)}return{ok:!0,envelope:{reply,proposals:discarded?[]:drafts},proposalsDiscarded:discarded}}export function tokenCount(value){return Number.isSafeInteger(value)&&value>=0&&value<=1e9}export const LEAD_MAX_STEPS=8,LEAD_MAX_CALLS_PER_STEP=4,LEAD_TOOL_RESULT_CAP_BYTES=16384,LEAD_TOOL_CALL_CAP_BYTES=2048,LEAD_TOOL_CALL_ID_CAP_BYTES=64,LEAD_STEP_TEXT_CAP_BYTES=8192;export function leadWorstCaseForPrice(price,baseBytes,caps={}){const S=caps.steps??LEAD_MAX_STEPS,M=caps.callsPerStep??LEAD_MAX_CALLS_PER_STEP,R=caps.resultCap??LEAD_TOOL_RESULT_CAP_BYTES,C=caps.callCap??LEAD_TOOL_CALL_CAP_BYTES,T=caps.textCap??LEAD_STEP_TEXT_CAP_BYTES,tokens=bytes=>Math.ceil(bytes/3);let input=0;for(let s=1;s<=S;s++)input+=tokens(baseBytes+(s-1)*(M*2*(R+C)+2*T));return input*price.inMicrousd+S*MAX_OUTPUT_TOKENS*price.outMicrousd}const CACHE_WRITE_RATIO=1.25,CACHE_READ_RATIO=.1;export function cacheWorstPrice(price){return{inMicrousd:Math.ceil(price.inMicrousd*CACHE_WRITE_RATIO),outMicrousd:price.outMicrousd}}export function settleWithCache(price,answer){const write=answer.cacheWriteTokens??0,read=answer.cacheReadTokens??0;return(answer.tokensIn-write-read)*price.inMicrousd+write*Math.ceil(price.inMicrousd*CACHE_WRITE_RATIO)+read*Math.ceil(price.inMicrousd*CACHE_READ_RATIO)+answer.tokensOut*price.outMicrousd}const LEAD_IMAGE_MEDIA_TYPES=new Set(["image/png","image/jpeg","image/webp","image/gif"]);export const LEAD_MAX_IMAGES_PER_MESSAGE=4;const LEAD_MAX_IMAGE_BYTES=4*1024*1024;function imageMagicMatches(mediaType,bytes){return bytes.length<12?!1:mediaType==="image/png"?bytes[0]===137&&bytes[1]===80&&bytes[2]===78&&bytes[3]===71:mediaType==="image/jpeg"?bytes[0]===255&&bytes[1]===216&&bytes[2]===255:mediaType==="image/gif"?bytes.subarray(0,6).toString("ascii")==="GIF89a"||bytes.subarray(0,6).toString("ascii")==="GIF87a":mediaType==="image/webp"?bytes.subarray(0,4).toString("ascii")==="RIFF"&&bytes.subarray(8,12).toString("ascii")==="WEBP":!1}export function parseLeadImagesField(raw){if(typeof raw!="string"||raw.trim()==="")return[];let parsed;try{parsed=JSON.parse(raw)}catch{return[]}if(!Array.isArray(parsed))return[];const out=[];for(const item of parsed.slice(0,LEAD_MAX_IMAGES_PER_MESSAGE)){if(typeof item!="object"||item===null||Array.isArray(item))continue;const rec=item,mediaType=rec.mediaType,dataBase64=rec.dataBase64;if(typeof mediaType!="string"||!LEAD_IMAGE_MEDIA_TYPES.has(mediaType)||typeof dataBase64!="string"||dataBase64.length===0||dataBase64.length>Math.ceil(LEAD_MAX_IMAGE_BYTES*1.4)||!/^[A-Za-z0-9+/=\s]+$/.test(dataBase64))continue;const cleanB64=dataBase64.replace(/\s+/g,""),bytes=Buffer.from(cleanB64,"base64");if(bytes.length===0||bytes.length>LEAD_MAX_IMAGE_BYTES||!imageMagicMatches(mediaType,bytes))continue;const filename=typeof rec.filename=="string"?rec.filename.trim().slice(0,120):void 0;out.push({mediaType,dataBase64:cleanB64,...filename?{filename}:{}})}return out}export function parseLeadProviderWrapper(provider,bytes){const parsed=strictJsonParse(bytes,WRAPPER_CAP_BYTES,14);if(!parsed.ok)return{ok:!1,problem:parsed.problem};const body=parsed.value;if(typeof body!="object"||body===null)return{ok:!1,problem:"not-an-object"};const readArgs=raw=>{const text2=typeof raw=="string"?raw:JSON.stringify(raw??null);if(Buffer.byteLength(text2,"utf8")>LEAD_TOOL_CALL_CAP_BYTES)return null;const inner=strictJsonParse(Buffer.from(text2,"utf8"),LEAD_TOOL_CALL_CAP_BYTES,6);return!inner.ok||typeof inner.value!="object"||inner.value===null||Array.isArray(inner.value)?null:inner.value},readCall=(id,name,rawArgs)=>{if(typeof id!="string"||id===""||Buffer.byteLength(id,"utf8")>LEAD_TOOL_CALL_ID_CAP_BYTES||typeof name!="string"||name===""||name.length>64)return null;const args=readArgs(rawArgs);if(args===null)return null;const call={id,name,args};return Buffer.byteLength(JSON.stringify(call),"utf8")>LEAD_TOOL_CALL_CAP_BYTES?null:call},usageOf=(usage2,inKey,outKey)=>{if(typeof usage2!="object"||usage2===null)return null;const tokensIn=usage2[inKey],tokensOut=usage2[outKey];return typeof tokensIn!="number"||typeof tokensOut!="number"||!tokenCount(tokensIn)||!tokenCount(tokensOut)||tokensOut>MAX_OUTPUT_TOKENS?null:{tokensIn,tokensOut}};if(provider==="anthropic-api"){if(body.type!=="message")return{ok:!1,problem:"wrong-type"};const content=body.content;if(!Array.isArray(content)||content.length===0||content.length>LEAD_MAX_CALLS_PER_STEP+1)return{ok:!1,problem:"bad-content"};let text2="";const calls2=[];for(const raw of content){const block=raw;if(typeof block!="object"||block===null)return{ok:!1,problem:"not-a-block"};if(block.type==="text"&&typeof block.text=="string")text2+=block.text;else if(block.type==="tool_use"){const call=readCall(block.id,block.name,block.input);if(call===null)return{ok:!1,problem:"bad-tool-call"};calls2.push(call)}else return{ok:!1,problem:"bad-block"}}if(calls2.length>LEAD_MAX_CALLS_PER_STEP)return{ok:!1,problem:"too-many-calls"};if(Buffer.byteLength(text2,"utf8")>LEAD_STEP_TEXT_CAP_BYTES)return{ok:!1,problem:"text-over-cap"};const usage2=usageOf(body.usage,"input_tokens","output_tokens");if(usage2===null)return{ok:!1,problem:"no-usage"};const cache=key=>{const value=body.usage[key];return value===void 0?void 0:typeof value=="number"&&tokenCount(value)?value:null},write=cache("cache_creation_input_tokens"),read=cache("cache_read_input_tokens");return write===null||read===null?{ok:!1,problem:"no-usage"}:{ok:!0,answer:{text:text2,calls:calls2,tokensIn:usage2.tokensIn+(write??0)+(read??0),tokensOut:usage2.tokensOut,reportedCostMicrousd:null,modelReported:reportedModelOf(body.model),providerTurns:null,reportedCostUsd:null,...write===void 0?{}:{cacheWriteTokens:write},...read===void 0?{}:{cacheReadTokens:read}}}}const choices=body.choices;if(!Array.isArray(choices)||choices.length!==1)return{ok:!1,problem:"not-one-choice"};const message=choices[0]?.message;if(message===void 0)return{ok:!1,problem:"not-text"};const text=typeof message.content=="string"?message.content:message.content===null?"":null;if(text===null)return{ok:!1,problem:"not-text"};const calls=[],rawCalls=message.tool_calls;if(rawCalls!==void 0){if(!Array.isArray(rawCalls)||rawCalls.length>LEAD_MAX_CALLS_PER_STEP)return{ok:!1,problem:"too-many-calls"};for(const raw of rawCalls){const one=raw,fn=one?.function;if(typeof one!="object"||one===null||fn===void 0||typeof fn!="object"||fn===null)return{ok:!1,problem:"bad-tool-call"};const call=readCall(one.id,fn.name,fn.arguments??"{}");if(call===null)return{ok:!1,problem:"bad-tool-call"};calls.push(call)}}if(Buffer.byteLength(text,"utf8")>LEAD_STEP_TEXT_CAP_BYTES)return{ok:!1,problem:"text-over-cap"};const usage=usageOf(body.usage,"prompt_tokens","completion_tokens");if(usage===null)return{ok:!1,problem:"no-usage"};const rawCost=body.usage.cost;let reportedCostMicrousd=null;if(rawCost!=null){if(typeof rawCost!="number"||!Number.isFinite(rawCost)||rawCost<0)return{ok:!1,problem:"bad-cost"};const micro=Math.ceil(rawCost*1e6);if(!Number.isSafeInteger(micro))return{ok:!1,problem:"bad-cost"};reportedCostMicrousd=micro}return{ok:!0,answer:{text,calls,tokensIn:usage.tokensIn,tokensOut:usage.tokensOut,reportedCostMicrousd,modelReported:reportedModelOf(body.model),providerTurns:null,reportedCostUsd:reportedCostUsdOf(rawCost)}}}function dataAnchorIndex(history){if(history.length===0)return-1;let settledAssistant=-1;for(let i=history.length-1;i>=0;i--){const one=history[i];if(one.role==="assistant"&&one.calls.length===0){settledAssistant=i;break}}for(let i=settledAssistant+1;i<history.length;i++)if(history[i].role==="operator")return i;for(let i=history.length-1;i>=0;i--)if(history[i].role==="operator")return i;return-1}export function composeLeadRequest(args){const dataBlock=`DATA:
1
+ import{takeEvalDispatch}from"./eval-gate.js";import{TASK_TEXT_LIMITS}from"./task-text.js";import{createHash}from"node:crypto";import{hasForbiddenControls,hasDisguisedText}from"./decision.js";import{parseAcceptanceCriteria}from"./scope.js";import{reportedCostUsdOf,reportedModelOf}from"./reported-usage.js";const WRAPPER_CAP_BYTES=262144,ENVELOPE_CAP_BYTES=65536;export const REPLY_CAP_BYTES=32768;const MAX_PROPOSALS=3;export const MAX_DEPTH=6,MAX_OUTPUT_TOKENS=2048,TURN_WALL_CLOCK_MS=24e4;const PRICES={"claude-sonnet-5":{inMicrousd:3,outMicrousd:15},"claude-opus-5":{inMicrousd:15,outMicrousd:75},"claude-haiku-4-5":{inMicrousd:1,outMicrousd:5},"anthropic/claude-sonnet-5":{inMicrousd:3,outMicrousd:15},"openai/gpt-5.2":{inMicrousd:2,outMicrousd:8}};export function priceOf(model){return PRICES[model]??null}export const PRICED_MODELS=Object.keys(PRICES);function toMicrousd(dollarsPerToken){return!Number.isFinite(dollarsPerToken)||dollarsPerToken<0?null:dollarsPerToken===0?0:Math.max(1,Math.ceil(dollarsPerToken*1e6))}export async function fetchOpenRouterCatalog(key,fetcher=fetch,signal){let response;try{response=await fetcher("https://openrouter.ai/api/v1/models",{headers:{authorization:`Bearer ${key}`},redirect:"error",...signal===void 0?{}:{signal}})}catch{return{ok:!1,problem:"network"}}if(response.status!==200)return{ok:!1,problem:`status-${response.status}`};const body=await readCappedBody(response,4194304);if(body===null)return{ok:!1,problem:"over-size"};let text;try{text=new TextDecoder("utf-8",{fatal:!0}).decode(body)}catch{return{ok:!1,problem:"not-utf8"}}let parsed;try{parsed=JSON.parse(text)}catch{return{ok:!1,problem:"not-json"}}const rows=parsed?.data;if(!Array.isArray(rows))return{ok:!1,problem:"wrong-shape"};const models=[];for(const row of rows){const id=row?.id,pricing=row?.pricing;if(typeof id!="string"||id.length>128||pricing===void 0)continue;const inMicrousd=toMicrousd(Number(pricing.prompt)),outMicrousd=toMicrousd(Number(pricing.completion));if(!(inMicrousd===null||outMicrousd===null)&&(models.push({id,price:{inMicrousd,outMicrousd}}),models.length>=500))break}return models.sort((a,b)=>a.id.localeCompare(b.id)),{ok:!0,models}}export function priceForConfig(config){return config.priceInMicrousd!==null&&config.priceOutMicrousd!==null?{inMicrousd:config.priceInMicrousd,outMicrousd:config.priceOutMicrousd}:priceOf(config.model)}export function worstCaseForPrice(price,promptBytes){return Math.ceil(promptBytes/3)*price.inMicrousd+MAX_OUTPUT_TOKENS*price.outMicrousd}export function settleForPrice(price,tokensIn,tokensOut){return tokensIn*price.inMicrousd+tokensOut*price.outMicrousd}export const DIRECT_CHAT_PROVIDERS=["anthropic-api","openrouter-api"];const SUBSCRIPTION_CHAT_PROVIDERS=["claude-subscription","codex-subscription","gemini-subscription","grok-subscription"];export function isDirectChatProvider(provider){return DIRECT_CHAT_PROVIDERS.includes(provider)}export function isSubscriptionChatProvider(provider){return SUBSCRIPTION_CHAT_PROVIDERS.includes(provider)}export const CHAT_KEY_ENV={"anthropic-api":"ANTHROPIC_API_KEY","openrouter-api":"OPENROUTER_API_KEY"};export function credentialKeyOf(provider,key){return createHash("sha256").update(`standing-orders/chat/v1\0${provider}\0${key}`).digest("hex")}export function subscriptionCredentialKey(provider){return credentialKeyOf(provider,"cached-membership-login")}const KEY_SHAPES={"anthropic-api":/^sk-[A-Za-z0-9_-]{20,200}$/,"openrouter-api":/^sk-[A-Za-z0-9_-]{20,200}$/};export function plausibleChatKey(provider,key){return KEY_SHAPES[provider].test(key.trim())}export function strictJsonParse(bytes,maxBytes,maxDepth=MAX_DEPTH){if(bytes.length>maxBytes)return{ok:!1,problem:"over-size"};let text;try{text=new TextDecoder("utf-8",{fatal:!0}).decode(bytes)}catch{return{ok:!1,problem:"not-utf8"}}const scanned=scan(text,maxDepth);if(scanned!==null)return{ok:!1,problem:scanned};try{return{ok:!0,value:JSON.parse(text)}}catch{return{ok:!1,problem:"not-json"}}}function scan(text,maxDepth){const stack=[];let index=0;const length=text.length,readString=()=>{let out="";for(index++;index<length;){const ch=text[index];if(ch==='"')return out;if(ch==="\\"){index+=2,out+="?";continue}out+=ch,index++}return null};for(;index<length;){const ch=text[index];if(ch==="{"){if(stack.push({kind:"obj",keys:new Set,expectKey:!0}),stack.length>maxDepth)return"too-deep"}else if(ch==="["){if(stack.push({kind:"arr"}),stack.length>maxDepth)return"too-deep"}else if(ch==="}"||ch==="]")stack.pop();else if(ch==='"'){const top=stack[stack.length-1];if(top!==void 0&&top.kind==="obj"&&top.expectKey){const key=readString();if(key===null)return"not-json";if(top.keys.has(key))return"duplicate-key";top.keys.add(key),top.expectKey=!1}else if(readString()===null)return"not-json"}else if(ch===","){const top=stack[stack.length-1];top!==void 0&&top.kind==="obj"&&(top.expectKey=!0)}index++}return null}const REPO_ID=/^r[0-9]{1,3}$/;function honest(text,maxChars,maxBytes){return text.length<=maxChars&&Buffer.byteLength(text,"utf8")<=maxBytes&&!hasForbiddenControls(text)&&!hasDisguisedText(text)}function exactKeys(value,keys){const present=Object.keys(value);return present.length===keys.length&&keys.every(key=>present.includes(key))}function readDraft(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return null;const body=raw,kind=body.kind;if(kind!=="task"||!exactKeys(body,["kind","repoId","title","goal","outOfScope","touches","acceptance"]))return null;const repoId=body.repoId,goal=body.goal,outOfScope=body.outOfScope,touches=body.touches;if(typeof repoId!="string"||!REPO_ID.test(repoId)||typeof goal!="string"||goal.trim()===""||!honest(goal,TASK_TEXT_LIMITS.text,TASK_TEXT_LIMITS.textBytes)||outOfScope!==null&&(typeof outOfScope!="string"||!honest(outOfScope,TASK_TEXT_LIMITS.text,TASK_TEXT_LIMITS.textBytes))||!Array.isArray(touches)||touches.length>50)return null;for(const one of touches)if(typeof one!="string"||one.trim()===""||!honest(one,200,800))return null;const acceptanceParse=parseAcceptanceCriteria(body.acceptance);if(acceptanceParse.problems.length>0||acceptanceParse.criteria.length===0)return null;const acceptance=acceptanceParse.criteria,title=body.title;return typeof title!="string"||title.trim()===""||!honest(title,200,800)?null:{kind,repoId,title,goal,outOfScope,touches,acceptance}}export function parseAssistantEnvelope(text){const parsed=strictJsonParse(Buffer.from(text,"utf8"),ENVELOPE_CAP_BYTES);if(!parsed.ok)return{ok:!1,problem:parsed.problem};const value=parsed.value;if(typeof value!="object"||value===null||Array.isArray(value))return{ok:!1,problem:"not-an-object"};const body=value;if(!exactKeys(body,["chatEnvelope","reply","proposals"]))return{ok:!1,problem:"wrong-keys"};if(body.chatEnvelope!==1)return{ok:!1,problem:"wrong-version"};const reply=body.reply;if(typeof reply!="string"||Buffer.byteLength(reply,"utf8")>REPLY_CAP_BYTES)return{ok:!1,problem:"bad-reply"};const rawProposals=body.proposals;if(!Array.isArray(rawProposals)||rawProposals.length>MAX_PROPOSALS)return{ok:!1,problem:"bad-proposals"};const drafts=[];let discarded=!1;for(const raw of rawProposals){const draft=readDraft(raw);if(draft===null){discarded=!0;break}drafts.push(draft)}return{ok:!0,envelope:{reply,proposals:discarded?[]:drafts},proposalsDiscarded:discarded}}export function tokenCount(value){return Number.isSafeInteger(value)&&value>=0&&value<=1e9}export const LEAD_MAX_STEPS=8,LEAD_MAX_CALLS_PER_STEP=4,LEAD_TOOL_RESULT_CAP_BYTES=16384,LEAD_TOOL_CALL_CAP_BYTES=2048,LEAD_TOOL_CALL_ID_CAP_BYTES=64,LEAD_STEP_TEXT_CAP_BYTES=8192;export function leadWorstCaseForPrice(price,baseBytes,caps={}){const S=caps.steps??LEAD_MAX_STEPS,M=caps.callsPerStep??LEAD_MAX_CALLS_PER_STEP,R=caps.resultCap??LEAD_TOOL_RESULT_CAP_BYTES,C=caps.callCap??LEAD_TOOL_CALL_CAP_BYTES,T=caps.textCap??LEAD_STEP_TEXT_CAP_BYTES,tokens=bytes=>Math.ceil(bytes/3);let input=0;for(let s=1;s<=S;s++)input+=tokens(baseBytes+(s-1)*(M*2*(R+C)+2*T));return input*price.inMicrousd+S*MAX_OUTPUT_TOKENS*price.outMicrousd}const CACHE_WRITE_RATIO=1.25,CACHE_READ_RATIO=.1;export function cacheWorstPrice(price){return{inMicrousd:Math.ceil(price.inMicrousd*CACHE_WRITE_RATIO),outMicrousd:price.outMicrousd}}export function settleWithCache(price,answer){const write=answer.cacheWriteTokens??0,read=answer.cacheReadTokens??0;return(answer.tokensIn-write-read)*price.inMicrousd+write*Math.ceil(price.inMicrousd*CACHE_WRITE_RATIO)+read*Math.ceil(price.inMicrousd*CACHE_READ_RATIO)+answer.tokensOut*price.outMicrousd}const LEAD_IMAGE_MEDIA_TYPES=new Set(["image/png","image/jpeg","image/webp","image/gif"]);export const LEAD_MAX_IMAGES_PER_MESSAGE=4;const LEAD_MAX_IMAGE_BYTES=4*1024*1024;function imageMagicMatches(mediaType,bytes){return bytes.length<12?!1:mediaType==="image/png"?bytes[0]===137&&bytes[1]===80&&bytes[2]===78&&bytes[3]===71:mediaType==="image/jpeg"?bytes[0]===255&&bytes[1]===216&&bytes[2]===255:mediaType==="image/gif"?bytes.subarray(0,6).toString("ascii")==="GIF89a"||bytes.subarray(0,6).toString("ascii")==="GIF87a":mediaType==="image/webp"?bytes.subarray(0,4).toString("ascii")==="RIFF"&&bytes.subarray(8,12).toString("ascii")==="WEBP":!1}export function parseLeadImagesField(raw){if(typeof raw!="string"||raw.trim()==="")return[];let parsed;try{parsed=JSON.parse(raw)}catch{return[]}if(!Array.isArray(parsed))return[];const out=[];for(const item of parsed.slice(0,LEAD_MAX_IMAGES_PER_MESSAGE)){if(typeof item!="object"||item===null||Array.isArray(item))continue;const rec=item,mediaType=rec.mediaType,dataBase64=rec.dataBase64;if(typeof mediaType!="string"||!LEAD_IMAGE_MEDIA_TYPES.has(mediaType)||typeof dataBase64!="string"||dataBase64.length===0||dataBase64.length>Math.ceil(LEAD_MAX_IMAGE_BYTES*1.4)||!/^[A-Za-z0-9+/=\s]+$/.test(dataBase64))continue;const cleanB64=dataBase64.replace(/\s+/g,""),bytes=Buffer.from(cleanB64,"base64");if(bytes.length===0||bytes.length>LEAD_MAX_IMAGE_BYTES||!imageMagicMatches(mediaType,bytes))continue;const filename=typeof rec.filename=="string"?rec.filename.trim().slice(0,120):void 0;out.push({mediaType,dataBase64:cleanB64,...filename?{filename}:{}})}return out}export function parseLeadProviderWrapper(provider,bytes){const parsed=strictJsonParse(bytes,WRAPPER_CAP_BYTES,14);if(!parsed.ok)return{ok:!1,problem:parsed.problem};const body=parsed.value;if(typeof body!="object"||body===null)return{ok:!1,problem:"not-an-object"};const readArgs=raw=>{const text2=typeof raw=="string"?raw:JSON.stringify(raw??null);if(Buffer.byteLength(text2,"utf8")>LEAD_TOOL_CALL_CAP_BYTES)return null;const inner=strictJsonParse(Buffer.from(text2,"utf8"),LEAD_TOOL_CALL_CAP_BYTES,6);return!inner.ok||typeof inner.value!="object"||inner.value===null||Array.isArray(inner.value)?null:inner.value},readCall=(id,name,rawArgs)=>{if(typeof id!="string"||id===""||Buffer.byteLength(id,"utf8")>LEAD_TOOL_CALL_ID_CAP_BYTES||typeof name!="string"||name===""||name.length>64)return null;const args=readArgs(rawArgs);if(args===null)return null;const call={id,name,args};return Buffer.byteLength(JSON.stringify(call),"utf8")>LEAD_TOOL_CALL_CAP_BYTES?null:call},usageOf=(usage2,inKey,outKey)=>{if(typeof usage2!="object"||usage2===null)return null;const tokensIn=usage2[inKey],tokensOut=usage2[outKey];return typeof tokensIn!="number"||typeof tokensOut!="number"||!tokenCount(tokensIn)||!tokenCount(tokensOut)||tokensOut>MAX_OUTPUT_TOKENS?null:{tokensIn,tokensOut}};if(provider==="anthropic-api"){if(body.type!=="message")return{ok:!1,problem:"wrong-type"};const content=body.content;if(!Array.isArray(content)||content.length===0||content.length>LEAD_MAX_CALLS_PER_STEP+1)return{ok:!1,problem:"bad-content"};let text2="";const calls2=[];for(const raw of content){const block=raw;if(typeof block!="object"||block===null)return{ok:!1,problem:"not-a-block"};if(block.type==="text"&&typeof block.text=="string")text2+=block.text;else if(block.type==="tool_use"){const call=readCall(block.id,block.name,block.input);if(call===null)return{ok:!1,problem:"bad-tool-call"};calls2.push(call)}else return{ok:!1,problem:"bad-block"}}if(calls2.length>LEAD_MAX_CALLS_PER_STEP)return{ok:!1,problem:"too-many-calls"};if(Buffer.byteLength(text2,"utf8")>LEAD_STEP_TEXT_CAP_BYTES)return{ok:!1,problem:"text-over-cap"};const usage2=usageOf(body.usage,"input_tokens","output_tokens");if(usage2===null)return{ok:!1,problem:"no-usage"};const cache=key=>{const value=body.usage[key];return value===void 0?void 0:typeof value=="number"&&tokenCount(value)?value:null},write=cache("cache_creation_input_tokens"),read=cache("cache_read_input_tokens");return write===null||read===null?{ok:!1,problem:"no-usage"}:{ok:!0,answer:{text:text2,calls:calls2,tokensIn:usage2.tokensIn+(write??0)+(read??0),tokensOut:usage2.tokensOut,reportedCostMicrousd:null,modelReported:reportedModelOf(body.model),providerTurns:null,reportedCostUsd:null,...write===void 0?{}:{cacheWriteTokens:write},...read===void 0?{}:{cacheReadTokens:read}}}}const choices=body.choices;if(!Array.isArray(choices)||choices.length!==1)return{ok:!1,problem:"not-one-choice"};const message=choices[0]?.message;if(message===void 0)return{ok:!1,problem:"not-text"};const text=typeof message.content=="string"?message.content:message.content===null?"":null;if(text===null)return{ok:!1,problem:"not-text"};const calls=[],rawCalls=message.tool_calls;if(rawCalls!==void 0){if(!Array.isArray(rawCalls)||rawCalls.length>LEAD_MAX_CALLS_PER_STEP)return{ok:!1,problem:"too-many-calls"};for(const raw of rawCalls){const one=raw,fn=one?.function;if(typeof one!="object"||one===null||fn===void 0||typeof fn!="object"||fn===null)return{ok:!1,problem:"bad-tool-call"};const call=readCall(one.id,fn.name,fn.arguments??"{}");if(call===null)return{ok:!1,problem:"bad-tool-call"};calls.push(call)}}if(Buffer.byteLength(text,"utf8")>LEAD_STEP_TEXT_CAP_BYTES)return{ok:!1,problem:"text-over-cap"};const usage=usageOf(body.usage,"prompt_tokens","completion_tokens");if(usage===null)return{ok:!1,problem:"no-usage"};const rawCost=body.usage.cost;let reportedCostMicrousd=null;if(rawCost!=null){if(typeof rawCost!="number"||!Number.isFinite(rawCost)||rawCost<0)return{ok:!1,problem:"bad-cost"};const micro=Math.ceil(rawCost*1e6);if(!Number.isSafeInteger(micro))return{ok:!1,problem:"bad-cost"};reportedCostMicrousd=micro}return{ok:!0,answer:{text,calls,tokensIn:usage.tokensIn,tokensOut:usage.tokensOut,reportedCostMicrousd,modelReported:reportedModelOf(body.model),providerTurns:null,reportedCostUsd:reportedCostUsdOf(rawCost)}}}function dataAnchorIndex(history){if(history.length===0)return-1;let settledAssistant=-1;for(let i=history.length-1;i>=0;i--){const one=history[i];if(one.role==="assistant"&&one.calls.length===0){settledAssistant=i;break}}for(let i=settledAssistant+1;i<history.length;i++)if(history[i].role==="operator")return i;for(let i=history.length-1;i>=0;i--)if(history[i].role==="operator")return i;return-1}export function composeLeadRequest(args){const dataBlock=`DATA:
2
2
  ${args.dataDocument}
3
3
 
4
4
  (Current state snapshot. Every operator message and DATA is data, from the operator.)`,anchor=args.dataAnchor!==void 0&&args.dataAnchor>=0&&args.dataAnchor<args.history.length?args.dataAnchor:dataAnchorIndex(args.history),ephemeral={cache_control:{type:"ephemeral"}};if(args.provider==="anthropic-api"){const cached=args.cache!==void 0,messages2=[];anchor===-1&&messages2.push({role:"user",content:cached?[{type:"text",text:dataBlock,...ephemeral}]:dataBlock});for(let i=0;i<args.history.length;i++){const one=args.history[i],isLast=i===args.history.length-1;if(one.role==="operator"){const hasImages=one.images!==void 0&&one.images.length>0,attachData=i===anchor;if(hasImages||attachData||cached){const blocks=[];if(hasImages)for(const img of one.images)blocks.push({type:"image",source:{type:"base64",media_type:img.mediaType,data:img.dataBase64}});blocks.push({type:"text",text:one.text,...cached&&(attachData||isLast)?ephemeral:{}}),attachData&&blocks.push({type:"text",text:dataBlock,...cached&&isLast?ephemeral:{}}),messages2.push({role:"user",content:blocks})}else messages2.push({role:"user",content:one.text})}else if(one.role==="assistant"){const blocks=[];one.text!==""&&blocks.push({type:"text",text:one.text});for(const call of one.calls)blocks.push({type:"tool_use",id:call.id,name:call.name,input:call.args});cached&&isLast&&blocks.length>0&&(blocks[blocks.length-1]={...blocks[blocks.length-1],...ephemeral}),messages2.push({role:"assistant",content:blocks})}else messages2.push({role:"user",content:[{type:"tool_result",tool_use_id:one.callId,content:one.result,...cached&&isLast?ephemeral:{}}]})}const standingText2=args.standingDirections!==void 0&&args.standingDirections.trim()!==""?args.standingDirections.trim():null,systemPayload=cached?[{type:"text",text:args.system,...ephemeral},...standingText2===null?[]:[{type:"text",text:standingText2}]]:standingText2===null?args.system:`${args.system}
@@ -1 +1 @@
1
- import{execFile}from"node:child_process";import{statSync}from"node:fs";import{join}from"node:path";import{parse}from"tldts";const OP_TIMEOUT_MS=15e3,LIST_CACHE_TTL_MS=15e3,ITEM_ID=/^[A-Za-z0-9_-]{8,64}$/;function findOpCli(){const dirs=["/opt/homebrew/bin","/usr/local/bin","/usr/bin",...(process.env.PATH??"").split(":")];for(const d of dirs){if(!d)continue;const candidate=join(d,"op");try{if(statSync(candidate).isFile())return candidate}catch{}}return null}function normalizeDomain(raw){const trimmed=raw.trim().toLowerCase();if(!trimmed)return null;try{const host=(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname.replace(/\.$/,"");return/^\[[0-9a-f:.]+\]$/.test(host)?host:!host||host.includes("..")||!/^[a-z0-9.-]+$/.test(host)?null:host}catch{return null}}function registrableDomain(host){const parsed=parse(host,{allowPrivateDomains:!0});return parsed.isIp!==!1||!(parsed.isIcann||parsed.isPrivate)||parsed.hostname!==host?null:parsed.domain}export function domainMatchesOrigin(currentOrigin,itemDomains){let url;try{url=new URL(currentOrigin)}catch{return!1}const host=url.hostname.replace(/\.$/,""),isLocal=host==="localhost"||host==="127.0.0.1"||host==="[::1]";if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLocal))return!1;const hostRoot=registrableDomain(host);return itemDomains.some(raw=>{const allowed=normalizeDomain(raw);if(allowed===null)return!1;const root=registrableDomain(allowed);return host===allowed||root!==null&&root===hostRoot})}function defaultExecOp(opBin){return(args,timeoutMs)=>new Promise((resolveRun,rejectRun)=>{execFile(opBin,[...args],{timeout:timeoutMs,maxBuffer:4*1024*1024},(err,stdout,stderr)=>{if(err){const msg=stderr?.trim()||err.message||"1Password CLI failed";rejectRun(new Error(msg));return}resolveRun(stdout)})})}export class CredentialBroker{opPath;execOpOverride;nowMs;cachedList=null;constructor(deps={}){this.opPath=deps.opPath??findOpCli,this.execOpOverride=deps.execOp,this.nowMs=deps.nowMs??Date.now}isAvailable(){return this.execOpOverride!==void 0||this.opPath()!==null}async runOp(args){if(this.execOpOverride)return this.execOpOverride(args,OP_TIMEOUT_MS);const bin=this.opPath();if(!bin)throw Object.assign(new Error("1Password CLI (op) isn't installed on your Mac."),{code:"unavailable"});return defaultExecOp(bin)(args,OP_TIMEOUT_MS)}async listAll(){const now=this.nowMs();if(this.cachedList&&now-this.cachedList.at<LIST_CACHE_TTL_MS)return this.cachedList.items;const rawText=await this.runOp(["item","list","--categories","Login","--format","json"]);let parsed;try{parsed=JSON.parse(rawText)}catch{throw new Error("Couldn't read 1Password login list.")}if(!Array.isArray(parsed))return[];const items=[];for(const entry of parsed){if(!entry||typeof entry!="object"||Array.isArray(entry))continue;const rec=entry,id=typeof rec.id=="string"?rec.id:"",title=typeof rec.title=="string"?rec.title:"";if(!ITEM_ID.test(id)||!title)continue;const vaultObj=rec.vault,vault=vaultObj&&typeof vaultObj=="object"&&typeof vaultObj.name=="string"?String(vaultObj.name):"Personal",domains=[];if(Array.isArray(rec.urls))for(const u of rec.urls){const href=u&&typeof u=="object"?u.href:null,d=typeof href=="string"?normalizeDomain(href):null;d&&!domains.includes(d)&&domains.push(d)}items.push({id,title:title.slice(0,120),vault:vault.slice(0,80),domains,hasOtp:!0})}return this.cachedList={at:now,items},items}async listMatching(currentOrigin){return this.isAvailable()?(await this.listAll()).filter(item=>domainMatchesOrigin(currentOrigin,item.domains)):[]}async fetchFieldForOrigin(itemId,currentOrigin,field){if(!ITEM_ID.test(itemId))throw Object.assign(new Error("Invalid 1Password item id."),{code:"invalid_params"});const item=(await this.listAll()).find(one=>one.id===itemId);if(!item)throw Object.assign(new Error("That 1Password login wasn't found."),{code:"not_found"});if(!domainMatchesOrigin(currentOrigin,item.domains))throw Object.assign(new Error(`Refused: "${item.title}" doesn't match the current page's origin (${currentOrigin}).`),{code:"origin_mismatch"});if(field==="otp"){const code=(await this.runOp(["item","get",itemId,"--otp"])).trim();if(!code)throw Object.assign(new Error("No one-time code is set up on that 1Password item."),{code:"not_found"});return code}const raw=await this.runOp(["item","get",itemId,"--fields",`type=${field==="password"?"concealed":"text"},purpose=${field.toUpperCase()}`,"--reveal","--format","json"]);let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}const extract=node=>{if(!node||typeof node!="object")return null;if(Array.isArray(node)){for(const item2 of node){const found=extract(item2);if(found)return found}return null}const rec=node;return typeof rec.value=="string"&&rec.value.length>0?rec.value:null},value=extract(parsed);if(value)return value;const fallback=(await this.runOp(["item","get",itemId,"--fields",`label=${field}`,"--reveal"])).trim();if(!fallback)throw Object.assign(new Error(`No ${field} stored on "${item.title}".`),{code:"not_found"});return fallback}}
1
+ import{execFile}from"node:child_process";import{statSync}from"node:fs";import{join}from"node:path";import{parse}from"tldts";import{withoutLeadTokenEnv}from"./names.js";const OP_TIMEOUT_MS=15e3,LIST_CACHE_TTL_MS=15e3,ITEM_ID=/^[A-Za-z0-9_-]{8,64}$/;function findOpCli(){const dirs=["/opt/homebrew/bin","/usr/local/bin","/usr/bin",...(process.env.PATH??"").split(":")];for(const d of dirs){if(!d)continue;const candidate=join(d,"op");try{if(statSync(candidate).isFile())return candidate}catch{}}return null}function normalizeDomain(raw){const trimmed=raw.trim().toLowerCase();if(!trimmed)return null;try{const host=(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname.replace(/\.$/,"");return/^\[[0-9a-f:.]+\]$/.test(host)?host:!host||host.includes("..")||!/^[a-z0-9.-]+$/.test(host)?null:host}catch{return null}}function registrableDomain(host){const parsed=parse(host,{allowPrivateDomains:!0});return parsed.isIp!==!1||!(parsed.isIcann||parsed.isPrivate)||parsed.hostname!==host?null:parsed.domain}export function domainMatchesOrigin(currentOrigin,itemDomains){let url;try{url=new URL(currentOrigin)}catch{return!1}const host=url.hostname.replace(/\.$/,""),isLocal=host==="localhost"||host==="127.0.0.1"||host==="[::1]";if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLocal))return!1;const hostRoot=registrableDomain(host);return itemDomains.some(raw=>{const allowed=normalizeDomain(raw);if(allowed===null)return!1;const root=registrableDomain(allowed);return host===allowed||root!==null&&root===hostRoot})}function defaultExecOp(opBin){return(args,timeoutMs)=>new Promise((resolveRun,rejectRun)=>{execFile(opBin,[...args],{timeout:timeoutMs,maxBuffer:4*1024*1024,env:withoutLeadTokenEnv(process.env)},(err,stdout,stderr)=>{if(err){const msg=stderr?.trim()||err.message||"1Password CLI failed";rejectRun(new Error(msg));return}resolveRun(stdout)})})}export class CredentialBroker{opPath;execOpOverride;nowMs;cachedList=null;constructor(deps={}){this.opPath=deps.opPath??findOpCli,this.execOpOverride=deps.execOp,this.nowMs=deps.nowMs??Date.now}isAvailable(){return this.execOpOverride!==void 0||this.opPath()!==null}async runOp(args){if(this.execOpOverride)return this.execOpOverride(args,OP_TIMEOUT_MS);const bin=this.opPath();if(!bin)throw Object.assign(new Error("1Password CLI (op) isn't installed on your Mac."),{code:"unavailable"});return defaultExecOp(bin)(args,OP_TIMEOUT_MS)}async listAll(){const now=this.nowMs();if(this.cachedList&&now-this.cachedList.at<LIST_CACHE_TTL_MS)return this.cachedList.items;const rawText=await this.runOp(["item","list","--categories","Login","--format","json"]);let parsed;try{parsed=JSON.parse(rawText)}catch{throw new Error("Couldn't read 1Password login list.")}if(!Array.isArray(parsed))return[];const items=[];for(const entry of parsed){if(!entry||typeof entry!="object"||Array.isArray(entry))continue;const rec=entry,id=typeof rec.id=="string"?rec.id:"",title=typeof rec.title=="string"?rec.title:"";if(!ITEM_ID.test(id)||!title)continue;const vaultObj=rec.vault,vault=vaultObj&&typeof vaultObj=="object"&&typeof vaultObj.name=="string"?String(vaultObj.name):"Personal",domains=[];if(Array.isArray(rec.urls))for(const u of rec.urls){const href=u&&typeof u=="object"?u.href:null,d=typeof href=="string"?normalizeDomain(href):null;d&&!domains.includes(d)&&domains.push(d)}items.push({id,title:title.slice(0,120),vault:vault.slice(0,80),domains,hasOtp:!0})}return this.cachedList={at:now,items},items}async listMatching(currentOrigin){return this.isAvailable()?(await this.listAll()).filter(item=>domainMatchesOrigin(currentOrigin,item.domains)):[]}async fetchFieldForOrigin(itemId,currentOrigin,field){if(!ITEM_ID.test(itemId))throw Object.assign(new Error("Invalid 1Password item id."),{code:"invalid_params"});const item=(await this.listAll()).find(one=>one.id===itemId);if(!item)throw Object.assign(new Error("That 1Password login wasn't found."),{code:"not_found"});if(!domainMatchesOrigin(currentOrigin,item.domains))throw Object.assign(new Error(`Refused: "${item.title}" doesn't match the current page's origin (${currentOrigin}).`),{code:"origin_mismatch"});if(field==="otp"){const code=(await this.runOp(["item","get",itemId,"--otp"])).trim();if(!code)throw Object.assign(new Error("No one-time code is set up on that 1Password item."),{code:"not_found"});return code}const raw=await this.runOp(["item","get",itemId,"--fields",`type=${field==="password"?"concealed":"text"},purpose=${field.toUpperCase()}`,"--reveal","--format","json"]);let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}const extract=node=>{if(!node||typeof node!="object")return null;if(Array.isArray(node)){for(const item2 of node){const found=extract(item2);if(found)return found}return null}const rec=node;return typeof rec.value=="string"&&rec.value.length>0?rec.value:null},value=extract(parsed);if(value)return value;const fallback=(await this.runOp(["item","get",itemId,"--fields",`label=${field}`,"--reveal"])).trim();if(!fallback)throw Object.assign(new Error(`No ${field} stored on "${item.title}".`),{code:"not_found"});return fallback}}
package/dist/decision.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readDecisionPayload}from"./contracts/decision.js";import{TEXT_LIMITS}from"./text-limits.js";export const LIMITS={payload:64*1024,note:TEXT_LIMITS.note},NOTE_BYTE_CAP=TEXT_LIMITS.noteBytes;export function closedQuestionReason(reason){return reason==="scope-changed"?"The scope changed, so planning started again.":"The task was cancelled."}export function closedQuestionWords(reason){return`Closed without an answer. ${closedQuestionReason(reason)}`}const FORBIDDEN_INVISIBLES=/[\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/;export function validateNote(raw){const note=raw.trim();return note===""?{ok:!1,problem:"an empty note says nothing"}:note.length>LIMITS.note?{ok:!1,problem:`a note is at most ${LIMITS.note} characters`}:Buffer.byteLength(note,"utf8")>NOTE_BYTE_CAP?{ok:!1,problem:`a note is at most ${NOTE_BYTE_CAP} bytes`}:hasForbiddenControls(note)||FORBIDDEN_INVISIBLES.test(note)?{ok:!1,problem:"control and direction-override characters do not travel"}:{ok:!0,note}}const FORBIDDEN_MULTILINE=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/,FORBIDDEN_SINGLE_LINE=/[\u0000-\u001F\u007F-\u009F]/;export function hasForbiddenControls(text){return FORBIDDEN_MULTILINE.test(text)}export function hasDisguisedText(text){return FORBIDDEN_MULTILINE.test(text)||FORBIDDEN_INVISIBLES.test(text)}export function parseDecision(raw){if(Buffer.byteLength(raw,"utf8")>LIMITS.payload)return refuse("too-large",`payload: over ${LIMITS.payload} bytes — one screen does not need that`);let parsed;try{parsed=JSON.parse(raw)}catch(error){return refuse("not-json",`the payload is not JSON: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return refuse("not-an-object","payload: must be one JSON object");const read=readDecisionPayload(parsed),contract=read.ok?[]:read.issues.map(decisionProblemOf),body=parsed,problems=[...contract,...decisionRuleProblems(body,contract)];if(!read.ok||problems.length>0)return{ok:!1,problems};const payload=read.value;return{ok:!0,decision:{urgency:payload.urgency,recap:payload.recap.trim(),question:payload.question.trim(),options:payload.options.map(option=>({id:option.id,label:option.label.trim(),consequence:option.consequence.trim(),reversible:option.reversible})),recommendation:recommendedId(payload.recommendation),assignee:payload.assignee===void 0||payload.assignee===null?null:payload.assignee.trim(),deadline:payload.deadline===void 0||payload.deadline===null?null:new Date(Date.parse(payload.deadline)).toISOString()}}}function decisionReasonOf(issue){const at=issue.path,text=field=>issue.kind==="too-long"?`${field}-too-long`:`missing-${field}`;switch(at){case"urgency":return"bad-urgency";case"options":return issue.kind==="too-few"?"too-few-options":issue.kind==="too-many"?"too-many-options":"no-options";case"recommendation":return issue.kind==="too-long"?"bad-recommendation":"missing-recommendation";case"deadline":return"bad-deadline"}const option=/^options\[(\d+)\](?:\.(\w+))?$/.exec(at);if(option!==null){const[,index,field]=option;return field===void 0?"bad-option":field==="id"?"bad-option-id":field==="reversible"?"missing-reversible":text(`option-${index}-${field}`)}return text(at)}const decisionProblemOf=issue=>({reason:decisionReasonOf(issue),message:issue.line}),touched=(problems,field)=>problems.some(problem=>problem.message.startsWith(`${field}:`)||problem.message.startsWith(`${field}[`)||problem.message.startsWith(`${field}.`));function decisionRuleProblems(body,contract){const problems=[],text=(value,path,slug,oneLine)=>{typeof value!="string"||touched(contract,path)||(value.trim()===""?problems.push({reason:`missing-${slug}`,message:`${path}: must not be blank`}):(oneLine?FORBIDDEN_SINGLE_LINE:FORBIDDEN_MULTILINE).test(value)&&problems.push({reason:`${slug}-control-characters`,message:`${path}: ${oneLine?"must be one line with no control characters":"contains control characters — text only"}`}))};text(body.recap,"recap","recap",!1),text(body.question,"question","question",!1);const options=Array.isArray(body.options)?body.options:[],seen=new Set;options.forEach((entry,index)=>{if(typeof entry!="object"||entry===null||Array.isArray(entry))return;const option=entry,id=option.id;typeof id=="string"&&!touched(contract,`options[${index}].id`)&&(seen.has(id)&&problems.push({reason:"duplicate-option-id",message:`options[${index}].id: "${id}" appears twice`}),seen.add(id)),text(option.label,`options[${index}].label`,`option-${index}-label`,!0),text(option.consequence,`options[${index}].consequence`,`option-${index}-consequence`,!1)});const recommendation=body.recommendation;typeof recommendation=="string"&&!touched(contract,"recommendation")&&!touched(contract,"options")&&!options.some(option=>typeof option=="object"&&option!==null&&option.id===recommendedId(recommendation))&&problems.push({reason:"bad-recommendation",message:`recommendation: "${truncate(recommendation,60)}" does not match any option id`}),body.assignee!==null&&text(body.assignee,"assignee","assignee",!0);const deadline=body.deadline;return typeof deadline=="string"&&!touched(contract,"deadline")&&Number.isNaN(Date.parse(deadline))&&problems.push({reason:"bad-deadline",message:`deadline: must be an ISO 8601 timestamp (got ${describe(deadline)})`}),problems}function recommendedId(recommendation){const colon=recommendation.indexOf(":");return(colon===-1?recommendation:recommendation.slice(0,colon)).trim()}function refuse(reason,message){return{ok:!1,problems:[{reason,message}]}}function describe(value){return value===void 0?"nothing":typeof value=="string"?`"${truncate(value,40)}"`:typeof value}function truncate(text,at){return text.length<=at?text:`${text.slice(0,at)}…`}export const HANDOFF_VERSION=2,HANDOFF_CONCLUSION_CAP=600,HANDOFF_PAYLOAD_CAP=16*1024,HANDOFF_LIST_CAP=8,HANDOFF_ITEM_CAP=240,HANDOFF_REPORT_CAP=5,HANDOFF_REPORT_FIELDS=["decisions","assumptions","notDone","risks"];function compactHandoffText(value,cap){const clean=value.replace(/\s+/g," ").trim();if(clean.length<=cap)return clean;const room=Math.max(1,cap-1),candidate=clean.slice(0,room),sentence=Math.max(candidate.lastIndexOf(". "),candidate.lastIndexOf("! "),candidate.lastIndexOf("? ")),word=candidate.lastIndexOf(" "),cut=sentence>=Math.floor(room*.55)?sentence+1:word>=Math.floor(room*.55)?word:room;return`${candidate.slice(0,cut).trimEnd()}…`}function handoffList(value){return Array.isArray(value)?value.filter(one=>typeof one=="string"&&one.trim()!==""&&!FORBIDDEN_MULTILINE.test(one)).slice(0,HANDOFF_LIST_CAP).map(one=>compactHandoffText(one,HANDOFF_ITEM_CAP)):[]}export function handoffReportList(value){return Array.isArray(value)?value.filter(one=>typeof one=="string"&&one.trim()!==""&&!hasDisguisedText(one)).slice(0,HANDOFF_REPORT_CAP).map(one=>compactHandoffText(one,HANDOFF_ITEM_CAP)):[]}export function handoffReportOf(handoff){return Object.fromEntries(HANDOFF_REPORT_FIELDS.filter(field=>handoff[field].length>0).map(field=>[field,[...handoff[field]]]))}export function parseHandoff(raw){if(Buffer.byteLength(raw,"utf8")>HANDOFF_PAYLOAD_CAP)return{ok:!1,problems:[{reason:"too-large",message:`the handoff is over ${HANDOFF_PAYLOAD_CAP} bytes`}]};let parsed;try{parsed=JSON.parse(raw)}catch(error){return{ok:!1,problems:[{reason:"not-json",message:`the handoff is not JSON: ${error instanceof Error?error.message:String(error)}`}]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{ok:!1,problems:[{reason:"not-an-object",message:"the handoff must be one JSON object"}]};const body=parsed,problems=[];body.version!==1&&body.version!==HANDOFF_VERSION&&problems.push({reason:"bad-version",message:`version must be 1 or ${HANDOFF_VERSION} (got ${describe(body.version)})`});const status=body.status;status!=="completed"&&status!=="no-change"&&status!=="failed"&&problems.push({reason:"bad-status",message:`status must be "completed", "no-change", or "failed" (got ${describe(status)})`});const rawConclusion=body.conclusion;let conclusion=null;return typeof rawConclusion!="string"||rawConclusion.trim()===""?problems.push({reason:"missing-conclusion",message:"conclusion is required"}):FORBIDDEN_MULTILINE.test(rawConclusion)?problems.push({reason:"conclusion-control-characters",message:"conclusion contains control characters — text only"}):conclusion=compactHandoffText(rawConclusion,HANDOFF_CONCLUSION_CAP),problems.length>0?{ok:!1,problems}:{ok:!0,handoff:{status,conclusion,changes:handoffList(body.changes),verification:handoffList(body.verification),followUps:handoffList(body.followUps),decisions:handoffReportList(body.decisions),assumptions:handoffReportList(body.assumptions),notDone:handoffReportList(body.notDone),risks:handoffReportList(body.risks)}}}export const HEADLESS_RULE=["- You run headless: run every command in the foreground and wait for it,"," however long it takes. Never background a command to wait on it, and"," never schedule a wakeup, cron job, monitor or loop. Your turn ending"," ends the run, so write the handoff before you stop."];export function repairPrompt(problems,mailbox){return[`Your parked decision in ${mailbox} failed validation:`,...problems.map(problem=>`- ${problem.message} (${problem.reason})`),"",`Rewrite ${mailbox} only — change no other file, run no commands, and do not`,"reconsider the decision itself. Re-emit the same judgement call as valid",'JSON: { urgency: "blocking", recap, question, options: [{ id, label,',"consequence, reversible }], recommendation } — at least two options, every","option's reversible stated explicitly, recommendation naming an option id.",...HEADLESS_RULE].join(`
1
+ import{normalizeStructuredJson}from"./structured-json.js";import{readDecisionPayload}from"./contracts/decision.js";import{TEXT_LIMITS}from"./text-limits.js";export const LIMITS={payload:64*1024,note:TEXT_LIMITS.note},NOTE_BYTE_CAP=TEXT_LIMITS.noteBytes;export function closedQuestionReason(reason){return reason==="scope-changed"?"The scope changed, so planning started again.":"The task was cancelled."}export function closedQuestionWords(reason){return`Closed without an answer. ${closedQuestionReason(reason)}`}const FORBIDDEN_INVISIBLES=/[\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/;export function validateNote(raw){const note=raw.trim();return note===""?{ok:!1,problem:"an empty note says nothing"}:note.length>LIMITS.note?{ok:!1,problem:`a note is at most ${LIMITS.note} characters`}:Buffer.byteLength(note,"utf8")>NOTE_BYTE_CAP?{ok:!1,problem:`a note is at most ${NOTE_BYTE_CAP} bytes`}:hasForbiddenControls(note)||FORBIDDEN_INVISIBLES.test(note)?{ok:!1,problem:"control and direction-override characters do not travel"}:{ok:!0,note}}const FORBIDDEN_MULTILINE=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/,FORBIDDEN_SINGLE_LINE=/[\u0000-\u001F\u007F-\u009F]/;export function hasForbiddenControls(text){return FORBIDDEN_MULTILINE.test(text)}export function hasDisguisedText(text){return FORBIDDEN_MULTILINE.test(text)||FORBIDDEN_INVISIBLES.test(text)}export function parseDecision(raw){if(Buffer.byteLength(raw,"utf8")>LIMITS.payload)return refuse("too-large",`payload: over ${LIMITS.payload} bytes — one screen does not need that`);let parsed;try{parsed=JSON.parse(raw)}catch(error){return refuse("not-json",`the payload is not JSON: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return refuse("not-an-object","payload: must be one JSON object");const read=readDecisionPayload(parsed),contract=read.ok?[]:read.issues.map(decisionProblemOf),body=parsed,problems=[...contract,...decisionRuleProblems(body,contract)];if(!read.ok||problems.length>0)return{ok:!1,problems};const payload=read.value;return{ok:!0,decision:{urgency:payload.urgency,recap:payload.recap.trim(),question:payload.question.trim(),options:payload.options.map(option=>({id:option.id,label:option.label.trim(),consequence:option.consequence.trim(),reversible:option.reversible})),recommendation:recommendedId(payload.recommendation),assignee:payload.assignee===void 0||payload.assignee===null?null:payload.assignee.trim(),deadline:payload.deadline===void 0||payload.deadline===null?null:new Date(Date.parse(payload.deadline)).toISOString()}}}function decisionReasonOf(issue){const at=issue.path,text=field=>issue.kind==="too-long"?`${field}-too-long`:`missing-${field}`;switch(at){case"urgency":return"bad-urgency";case"options":return issue.kind==="too-few"?"too-few-options":issue.kind==="too-many"?"too-many-options":"no-options";case"recommendation":return issue.kind==="too-long"?"bad-recommendation":"missing-recommendation";case"deadline":return"bad-deadline"}const option=/^options\[(\d+)\](?:\.(\w+))?$/.exec(at);if(option!==null){const[,index,field]=option;return field===void 0?"bad-option":field==="id"?"bad-option-id":field==="reversible"?"missing-reversible":text(`option-${index}-${field}`)}return text(at)}const decisionProblemOf=issue=>({reason:decisionReasonOf(issue),message:issue.line}),touched=(problems,field)=>problems.some(problem=>problem.message.startsWith(`${field}:`)||problem.message.startsWith(`${field}[`)||problem.message.startsWith(`${field}.`));function decisionRuleProblems(body,contract){const problems=[],text=(value,path,slug,oneLine)=>{typeof value!="string"||touched(contract,path)||(value.trim()===""?problems.push({reason:`missing-${slug}`,message:`${path}: must not be blank`}):(oneLine?FORBIDDEN_SINGLE_LINE:FORBIDDEN_MULTILINE).test(value)&&problems.push({reason:`${slug}-control-characters`,message:`${path}: ${oneLine?"must be one line with no control characters":"contains control characters — text only"}`}))};text(body.recap,"recap","recap",!1),text(body.question,"question","question",!1);const options=Array.isArray(body.options)?body.options:[],seen=new Set;options.forEach((entry,index)=>{if(typeof entry!="object"||entry===null||Array.isArray(entry))return;const option=entry,id=option.id;typeof id=="string"&&!touched(contract,`options[${index}].id`)&&(seen.has(id)&&problems.push({reason:"duplicate-option-id",message:`options[${index}].id: "${id}" appears twice`}),seen.add(id)),text(option.label,`options[${index}].label`,`option-${index}-label`,!0),text(option.consequence,`options[${index}].consequence`,`option-${index}-consequence`,!1)});const recommendation=body.recommendation;typeof recommendation=="string"&&!touched(contract,"recommendation")&&!touched(contract,"options")&&!options.some(option=>typeof option=="object"&&option!==null&&option.id===recommendedId(recommendation))&&problems.push({reason:"bad-recommendation",message:`recommendation: "${truncate(recommendation,60)}" does not match any option id`}),body.assignee!==null&&text(body.assignee,"assignee","assignee",!0);const deadline=body.deadline;return typeof deadline=="string"&&!touched(contract,"deadline")&&Number.isNaN(Date.parse(deadline))&&problems.push({reason:"bad-deadline",message:`deadline: must be an ISO 8601 timestamp (got ${describe(deadline)})`}),problems}function recommendedId(recommendation){const colon=recommendation.indexOf(":");return(colon===-1?recommendation:recommendation.slice(0,colon)).trim()}function refuse(reason,message){return{ok:!1,problems:[{reason,message}]}}function describe(value){return value===void 0?"nothing":typeof value=="string"?`"${truncate(value,40)}"`:typeof value}function truncate(text,at){return text.length<=at?text:`${text.slice(0,at)}…`}export const HANDOFF_VERSION=2,HANDOFF_CONCLUSION_CAP=600,HANDOFF_PAYLOAD_CAP=16*1024,HANDOFF_LIST_CAP=8,HANDOFF_ITEM_CAP=240,HANDOFF_REPORT_CAP=5,HANDOFF_REPORT_FIELDS=["decisions","assumptions","notDone","risks"];function compactHandoffText(value,cap){const clean=value.replace(/\s+/g," ").trim();if(clean.length<=cap)return clean;const room=Math.max(1,cap-1),candidate=clean.slice(0,room),sentence=Math.max(candidate.lastIndexOf(". "),candidate.lastIndexOf("! "),candidate.lastIndexOf("? ")),word=candidate.lastIndexOf(" "),cut=sentence>=Math.floor(room*.55)?sentence+1:word>=Math.floor(room*.55)?word:room;return`${candidate.slice(0,cut).trimEnd()}…`}function handoffList(value){return Array.isArray(value)?value.filter(one=>typeof one=="string"&&one.trim()!==""&&!FORBIDDEN_MULTILINE.test(one)).slice(0,HANDOFF_LIST_CAP).map(one=>compactHandoffText(one,HANDOFF_ITEM_CAP)):[]}export function handoffReportList(value){return Array.isArray(value)?value.filter(one=>typeof one=="string"&&one.trim()!==""&&!hasDisguisedText(one)).slice(0,HANDOFF_REPORT_CAP).map(one=>compactHandoffText(one,HANDOFF_ITEM_CAP)):[]}export function handoffReportOf(handoff){return Object.fromEntries(HANDOFF_REPORT_FIELDS.filter(field=>handoff[field].length>0).map(field=>[field,[...handoff[field]]]))}export function parseHandoff(raw){if(Buffer.byteLength(raw,"utf8")>HANDOFF_PAYLOAD_CAP)return{ok:!1,problems:[{reason:"too-large",message:`the handoff is over ${HANDOFF_PAYLOAD_CAP} bytes`}]};let parsed;try{parsed=JSON.parse(normalizeStructuredJson(raw).text)}catch(error){return{ok:!1,problems:[{reason:"not-json",message:`the handoff is not JSON: ${error instanceof Error?error.message:String(error)}`}]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{ok:!1,problems:[{reason:"not-an-object",message:"the handoff must be one JSON object"}]};const body=parsed,problems=[];body.version!==1&&body.version!==HANDOFF_VERSION&&problems.push({reason:"bad-version",message:`version must be 1 or ${HANDOFF_VERSION} (got ${describe(body.version)})`});const status=body.status;status!=="completed"&&status!=="no-change"&&status!=="failed"&&problems.push({reason:"bad-status",message:`status must be "completed", "no-change", or "failed" (got ${describe(status)})`});const rawConclusion=body.conclusion;let conclusion=null;return typeof rawConclusion!="string"||rawConclusion.trim()===""?problems.push({reason:"missing-conclusion",message:"conclusion is required"}):FORBIDDEN_MULTILINE.test(rawConclusion)?problems.push({reason:"conclusion-control-characters",message:"conclusion contains control characters — text only"}):conclusion=compactHandoffText(rawConclusion,HANDOFF_CONCLUSION_CAP),problems.length>0?{ok:!1,problems}:{ok:!0,handoff:{status,conclusion,changes:handoffList(body.changes),verification:handoffList(body.verification),followUps:handoffList(body.followUps),decisions:handoffReportList(body.decisions),assumptions:handoffReportList(body.assumptions),notDone:handoffReportList(body.notDone),risks:handoffReportList(body.risks)}}}export const HEADLESS_RULE=["- You run headless: run every command in the foreground and wait for it,"," however long it takes. Never background a command to wait on it, and"," never schedule a wakeup, cron job, monitor or loop. Your turn ending"," ends the run, so write the handoff before you stop."];export function repairPrompt(problems,mailbox){return[`Your parked decision in ${mailbox} failed validation:`,...problems.map(problem=>`- ${problem.message} (${problem.reason})`),"",`Rewrite ${mailbox} only — change no other file, run no commands, and do not`,"reconsider the decision itself. Re-emit the same judgement call as valid",'JSON: { urgency: "blocking", recap, question, options: [{ id, label,',"consequence, reversible }], recommendation } — at least two options, every","option's reversible stated explicitly, recommendation naming an option id.",...HEADLESS_RULE].join(`
2
2
  `)}
package/dist/demo.js CHANGED
@@ -1,4 +1,4 @@
1
- import{execFileSync}from"node:child_process";import{mkdirSync,mkdtempSync,realpathSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,join}from"node:path";import{randomBytes}from"node:crypto";import{openStore}from"./store.js";import{addApprover,propose,approve}from"./scope.js";import{legOf,routeDigestOf}from"./phase-routing.js";import{acquire,release}from"./claim.js";import{register}from"./runner.js";import{createScheduledFlow}from"./flow-schedule.js";import{fileTaskProposal}from"./proposal.js";import{storeEvidence,budgetedStatJson,imageDimensions}from"./evidence.js";import{parseProof,adjudicate}from"./proof.js";import{sealVerificationReceipt}from"./verification-evidence.js";import{HANDOFF_VERSION,readHandoffArtifact}from"./contracts/handoff.js";import{parseExecutionPlanDocument,milestonesOf}from"./plan.js";import{maybeTriggerRepair}from"./dispose.js";import{deflateSync}from"node:zlib";import{FLOW_TEMPLATES}from"./flows.js";const DEMO_PROFILE={provider:"claude",model:"sonnet",permissionArgv:"auto",maxTurns:1e3,repairMaxTurns:4,timeoutSeconds:1200,timeoutKind:"idle",repairTimeoutSeconds:300,repairModel:"inherit"};function presentedRoute(store,taskRef,role,spend={provider:"claude",model:null}){const authority=store.routeAuthorityFor(taskRef,role)??store.routeAuthorityFor(taskRef,role,spend);if(authority===null||!authority.ok)throw new Error(`demo seed: ${authority===null?"no task":authority.problem}`);return{route:authority.stamp}}const DEMO_PATCH=`diff --git a/src/payout.ts b/src/payout.ts
1
+ import{execFileSync}from"node:child_process";import{mkdirSync,mkdtempSync,realpathSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,join}from"node:path";import{randomBytes}from"node:crypto";import{openStore}from"./store.js";import{addApprover,propose,approve}from"./scope.js";import{legOf,routeDigestOf}from"./phase-routing.js";import{acquire,release}from"./claim.js";import{register}from"./runner.js";import{createScheduledFlow}from"./flow-schedule.js";import{fileTaskProposal}from"./proposal.js";import{storeEvidence,budgetedStatJson,imageDimensions}from"./evidence.js";import{parseProof,adjudicate}from"./proof.js";import{withoutLeadTokenEnv}from"./names.js";import{sealVerificationReceipt}from"./verification-evidence.js";import{HANDOFF_VERSION,readHandoffArtifact}from"./contracts/handoff.js";import{parseExecutionPlanDocument,milestonesOf}from"./plan.js";import{maybeTriggerRepair}from"./dispose.js";import{deflateSync}from"node:zlib";import{FLOW_TEMPLATES}from"./flows.js";const DEMO_PROFILE={provider:"claude",model:"sonnet",permissionArgv:"auto",maxTurns:1e3,repairMaxTurns:4,timeoutSeconds:1200,timeoutKind:"idle",repairTimeoutSeconds:300,repairModel:"inherit"};function presentedRoute(store,taskRef,role,spend={provider:"claude",model:null}){const authority=store.routeAuthorityFor(taskRef,role)??store.routeAuthorityFor(taskRef,role,spend);if(authority===null||!authority.ok)throw new Error(`demo seed: ${authority===null?"no task":authority.problem}`);return{route:authority.stamp}}const DEMO_PATCH=`diff --git a/src/payout.ts b/src/payout.ts
2
2
  index 3f1c2aa..9e07b41 100644
3
3
  --- a/src/payout.ts
4
4
  +++ b/src/payout.ts
@@ -72,7 +72,7 @@ ${b.check.stdout}
72
72
  `),DEMO_BUILDING_PLAN_V1=["## Approach","Add a per-endpoint token-bucket limiter and enforce it before dispatch, reusing the existing webhook queue.","## Milestones","1. Add a per-endpoint token-bucket limiter.","2. Enforce the limiter before dispatch.","3. Add timeout budgets per endpoint.","4. Cover the limiter and budget interaction with load tests.","## Dependencies","- The existing webhook queue exposes a stable per-endpoint key.","## Risks","- A shared limiter could starve a burst-y but healthy endpoint; scope it per-endpoint from the start.","## Proof","- c1 — load-test one slow and one healthy endpoint together.",""].join(`
73
73
  `),DEMO_BUILDING_PLAN_V2=["## Approach","Derive a stable per-endpoint key from the normalized webhook URL host, since the queue has none; add a per-endpoint token-bucket limiter keyed on it and enforce it before dispatch.","## Milestones","1. Derive a stable per-endpoint key from the normalized URL host.","2. Add a per-endpoint token-bucket limiter.","3. Enforce the limiter before dispatch.","4. Confirm the dispatch feature flag is enabled in every deploy target.","5. Add timeout budgets per endpoint.","6. Cover the limiter and budget interaction with load tests.","## Dependencies","- None found — the per-endpoint key is now derived, not assumed.","## Risks","- A shared limiter could starve a burst-y but healthy endpoint; scope it per-endpoint from the start.","## Proof","- c1 — load-test one slow and one healthy endpoint together.",""].join(`
74
74
  `),DEMO_BUILDING_REVISION_REASON="The webhook queue has no stable per-endpoint key (src/webhooks/queue.ts) — the planned limiter needed one, so this revision derives it from the normalized URL host instead.",DEMO_BUILDING_REVISION_EVIDENCE="src/webhooks/queue.ts";function encodeDemoPng(width,height,rgb){const pixels=Buffer.alloc(width*height*3);for(let y=0;y<height;y++){const shade=Math.round(y/Math.max(1,height-1)*40);for(let x=0;x<width;x++)for(let c=0;c<3;c++)pixels[(y*width+x)*3+c]=Math.min(255,rgb[c]+shade)}return encodePngPixels(width,height,pixels)}function pngOf(width,height,raw){const crcTable=Array.from({length:256},(_,n)=>{let c=n;for(let k=0;k<8;k++)c=c&1?3988292384^c>>>1:c>>>1;return c>>>0}),crc32=buf=>{let c=4294967295;for(const byte of buf)c=crcTable[(c^byte)&255]^c>>>8;return(c^4294967295)>>>0},chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length,0);const typed=Buffer.concat([Buffer.from(type,"ascii"),data]),crc=Buffer.alloc(4);return crc.writeUInt32BE(crc32(typed),0),Buffer.concat([len,typed,crc])},ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0),ihdr.writeUInt32BE(height,4),ihdr[8]=8,ihdr[9]=2;const idat=deflateSync(raw);return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk("IHDR",ihdr),chunk("IDAT",idat),chunk("IEND",Buffer.alloc(0))])}const DEMO_SCREENSHOT_PNG=encodeDemoPng(640,400,[16,24,32]);export function seedDemo(store,repos,evidenceRoot,now){if(!store.isDemo())throw new Error("seedDemo refuses an unfenced database — stamp it demo first");const password=`demo-${randomBytes(9).toString("base64url")}`,added=addApprover(store,"demo",now,void 0,void 0,{},password);if(!added.ok)throw new Error(`demo approver: ${added.reason}`);const token=password,hoursAgo=hours=>new Date(now.getTime()-hours*36e5);store.setPhaseConfig("installation","build","claude","sonnet","demo",now),store.setPhaseConfig("installation","plan","claude","sonnet","demo",now),store.setPhaseConfig("installation","review","claude","sonnet","demo",now),store.setPhaseTierConfig("installation","build","strong","claude","opus","demo",now),store.setPhaseTierConfig("installation","review","strong","codex","gpt-5-codex","demo",now);const nightShift=register(store,{name:"night-shift-1",host:"demo",capacity:2,repos:[repos.api,repos.web],now:hoursAgo(30)});store.recordProviderReadiness("night-shift-1",[{provider:"claude",state:"unknown",reason:"installed (claude 2.1.0); no non-spending login check exists — a real run is the proof",probe:"version"},{provider:"codex",state:"ready",reason:"installed (codex 0.62.0); logged in as demo@standing-orders.dev",probe:"identity"},{provider:"openrouter",state:"unavailable",reason:"OPENROUTER_API_KEY is absent from this runner's environment",probe:"key"},{provider:"gemini",state:"unavailable",reason:"`gemini` is not installed on this runner's PATH",probe:"version"}],hoursAgo(.2));const genericAcceptance=[{id:"c1",statement:"The described change is made and verified.",how:null,evidence:["manual-review"]}],task=(id,title,repo,goal,acceptance=genericAcceptance)=>{const made=fileTaskProposal(store,{id,title,repo,...goal===void 0?{}:{goal,acceptance},filedVia:"demo"},hoursAgo(30));if(!made.ok)throw new Error(`seed task ${id}: ${made.reason}`);return made.id},run=(ref,role,leaseId,branch,worktree,at)=>store.startRun({taskRef:ref,leaseId,runner:"night-shift-1",...role==="planner"?{role}:{},branch,worktree,now:hoursAgo(at),...presentedRoute(store,ref,role)}),plannerDraft=(ref,taskId,leaseId,worktree,at,doneAt,plan)=>{const planner=run(ref,"planner",leaseId,`toolroll-plan/${taskId}`,worktree,at),artifact=storeEvidence(store,evidenceRoot,planner,"plan","plan.md",Buffer.from(plan,"utf8"),"planner handoff (verified tree) [demo: synthetic]",hoursAgo(doneAt));return store.finishRun(planner,{outcome:"built",reason:"plan-drafted",now:hoursAgo(doneAt)}),artifact},planned=task("rotate-log-format","Rotate the request-log format to JSON lines",repos.web,"Switch the request logger to JSON lines so the collector stops parsing free text. Keep the human console formatter for local dev. Migrate the two dashboards that grep the old format."),plannedRef=store.refFor("built-in",planned).id;store.editTaskRoute(plannedRef,{by:"demo",authenticate:()=>({ok:!0}),size:{size:"large",risky:!1}},hoursAgo(3.5)),store.editTaskRoute(plannedRef,{by:"demo",authenticate:()=>({ok:!0}),override:{phase:"review",provider:"claude",model:"opus"}},hoursAgo(3.2)),store.setPlanState(plannedRef,"drafted"),plannerDraft(plannedRef,planned,"demo-lease-plan",join(repos.web,".demo-worktree-plan"),3,2.8,DEMO_EXECUTION_PLAN);const asking=task("choose-retry-policy","Choose the webhook retry policy",repos.api,"Give outbound webhooks a bounded retry policy with dead-lettering.");approve(store,asking,"demo",hoursAgo(3),store.getScope(asking)?.digest??"",token);const askingRun=run(store.refFor("built-in",asking).id,"builder","demo-lease-ask",`toolroll/${asking}`,join(repos.api,".demo-worktree"),2);store.saveDecision({run:askingRun,urgency:"blocking",recap:"Retries currently hammer failing endpoints forever. The collector at partner X was down 40 minutes yesterday and we sent 8,400 attempts.",question:"How should webhook retries back off?",options:[{id:"exp",label:"Exponential, cap 1h, dead-letter after 24h",consequence:"Slowest to give up; partners see at most ~30 attempts/day.",reversible:!0},{id:"fixed",label:"Fixed 5-minute retries, dead-letter after 2h",consequence:"Faster surrender; brief outages on their side can drop events.",reversible:!0}],recommendation:"exp"},hoursAgo(1));const buildingGoal="Add per-endpoint concurrency caps and timeout budgets to webhook delivery.",building=task("harden-webhook-retries","Harden webhook delivery against slow consumers",repos.api,buildingGoal),proposedBuilding=propose(store,{profile:DEMO_PROFILE,taskId:building,goal:buildingGoal,outOfScope:"No changes to the public webhook payload shape.",touches:["src/webhooks/"],acceptance:[{id:"c1",statement:"Slow consumers cannot starve other endpoints' delivery.",how:"Load-test one slow and one healthy endpoint together.",evidence:["check"]}],now:hoursAgo(21)});approve(store,building,"demo",hoursAgo(20),proposedBuilding.digest,token);const buildingRef=store.refFor("built-in",building).id,buildingRev1Artifact=plannerDraft(buildingRef,building,"demo-lease-plan-2",join(repos.api,".demo-worktree-plan-2"),19,18.9,DEMO_BUILDING_PLAN_V1),buildingPriorRun=run(buildingRef,"builder","demo-lease-prior",`toolroll/${building}`,join(repos.api,".demo-worktree-1"),2),buildingRev2Artifact=storeEvidence(store,evidenceRoot,buildingPriorRun,"plan","revision.md",Buffer.from(DEMO_BUILDING_PLAN_V2,"utf8"),"builder-filed revision proposal [demo: synthetic]",hoursAgo(1.6)),buildingRev2Id=store.insertPlanRevision({taskRef:buildingRef,revision:2,artifact:buildingRev2Artifact,parentHash:store.getArtifact(buildingRev1Artifact)?.sha256??null,reason:DEMO_BUILDING_REVISION_REASON,evidenceLink:DEMO_BUILDING_REVISION_EVIDENCE,author:`builder:${buildingPriorRun}`,originRun:buildingPriorRun,kind:"builder-proposal",authorityKind:"plan-only",authorityDigest:"demo-authority-digest-unchanged",changedFields:[],status:"applied"},hoursAgo(1.6));store.setRunPlanRevision(buildingPriorRun,buildingRev2Id,"demo-authority-digest-unchanged"),store.finishRun(buildingPriorRun,{outcome:"refused",reason:"plan-revised",now:hoursAgo(1.6)});const liveClaim=acquire(store,buildingRef,"night-shift-1",{now:hoursAgo(.4),token:nightShift.token,ttlMs:4*36e5}),liveRun=run(buildingRef,"builder",liveClaim.ok?liveClaim.claim.leaseId:"demo-lease-live",`toolroll/${building}`,join(repos.api,".demo-worktree-2"),.4);store.setRunPlanRevision(liveRun,buildingRev2Id,"demo-authority-digest-unchanged");const buildingRev2Parsed=parseExecutionPlanDocument(DEMO_BUILDING_PLAN_V2);if(!buildingRev2Parsed.ok)throw new Error("demo building revision 2 plan is malformed");const milestoneStates=["completed","completed","current","blocked"];store.insertRunCheckpoint({run:liveRun,taskRef:buildingRef,planRevision:buildingRev2Id,snapshot:{revisionHash:store.getArtifact(buildingRev2Artifact)?.sha256??"",milestones:milestonesOf(buildingRev2Parsed.document).map((one,index)=>({id:one.id,state:milestoneStates[index]??"pending",note:index===3?"the flag is off in the staging deploy target — confirming before enforcing":null}))}},hoursAgo(.1)),store.setRunPhase(liveRun,"agent-running"),store.setTaskState(building,"running",hoursAgo(.4));const filed=(id,title,repo,scope,proposedAt,approvedAt)=>{const taskId=task(id,title,repo,scope.goal),proposed=propose(store,{profile:DEMO_PROFILE,taskId,...scope,now:hoursAgo(proposedAt)});return approve(store,taskId,"demo",hoursAgo(approvedAt),proposed.digest,token),{taskId,ref:store.refFor("built-in",taskId).id,digest:proposed.digest}},startBuild=(t,leaseId,runner,worktree,at,sealed=!1)=>{const run2=store.startRun({taskRef:t.ref,leaseId,runner,branch:`toolroll/${t.taskId}`,worktree,now:hoursAgo(at),...sealed?sealedRoute(store,t.taskId):presentedRoute(store,t.ref,"builder")});return store.stampRun(run2,{baseRevision:ZERO_TREE,scopeDigest:t.digest}),run2},times=(...hours)=>hours.map(hoursAgo),done=filed("fix-payout-rounding","Fix the payout rounding drift",repos.api,{goal:"Find and fix the half-cent drift in payout settlement; prove it with ledger-fixture tests.",outOfScope:"No ledger schema changes.",touches:["src/payout.ts","src/payout.test.ts"],acceptance:[{id:"c1",statement:"Ledger-fixture tests demonstrate the half-cent drift is gone.",how:null,evidence:["check","changed-path"]},{id:"c2",statement:"The human console formatter still renders payout dashboards.",how:null,evidence:["screenshot"]}]},27,26),doneCheck=store.setVerifyCommand({repo:store.refFor("built-in",done.taskId).repo??repos.api,command:DEMO_CHECK_COMMAND,timeoutMs:12e4,approvedBy:"demo"},hoursAgo(26)),doneRun=startBuild(done,"demo-lease-done","night-shift-2",join(repos.api,".demo-worktree-3"),9,!0);recordDemoBuild(store,evidenceRoot,doneRun,done.taskId,{head:DONE_HEAD,patch:DEMO_PATCH,files:[["src/payout.ts",4,1],["src/payout.test.ts",9,0]],handoff:built({conclusion:"Fixed the payout rounding drift: settle() now rounds at cent precision instead of accumulating half-cent errors. Added boundary tests against the ledger fixtures. All 214 tests pass.",changes:["Rounded settlement values at cent precision in src/payout.ts.","Added ledger-fixture coverage for half-cent boundaries."],verification:["All 214 tests pass, including the new rounding boundary cases."],decisions:["Rounded each line at cent precision in settle(), not when the total is displayed."],assumptions:["The ledger fixtures cover every currency payouts are made in."],risks:["Totals for settlements already paid at the old precision are not recalculated."]}),proof:proofOf([met("c1","Ledger-fixture tests demonstrate the half-cent drift is gone.","Added and ran boundary tests against the ledger fixtures.",[["check","npm test"],["changed-path","src/payout.ts"],["changed-path","src/payout.test.ts"]]),met("c2","The human console formatter still renders payout dashboards.","Ran the dashboard's own snapshot tests.",[["screenshot","evidence/payout-dashboard.png"]])],["src/payout.ts","src/payout.test.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed, including the new rounding boundary cases."}],screenshots:[{path:"evidence/payout-dashboard.png",caption:"Payout dashboard after the fix — totals match the ledger."}]}),at:times(8.5,8.4,8.4),facts:{handoff:!0},verified:!0,screenshot:{png:DEMO_SCREENSHOT_PNG,claimed:"evidence/payout-dashboard.png",file:"screenshot-demo.png"},check:{stdout:`214 tests passed.
75
- `,command:doneCheck}}),store.addRunNote(doneRun,"demo","Reviewed the diff — the fixture numbers check out. Shipping.",hoursAgo(3));const failed=filed("retire-legacy-flag","Retire the legacy payout feature flag",repos.api,{goal:"Remove LEGACY_PAYOUT and every branch behind it.",acceptance:[{id:"c1",statement:"No reference to LEGACY_PAYOUT remains in the codebase.",how:null,evidence:["changed-path"]}]},16,15);recordDemoBuild(store,evidenceRoot,startBuild(failed,"demo-lease-failed","night-shift-2",join(repos.api,".demo-worktree-4"),6),failed.taskId,{head:"5a1f0c7e2b9d4e6f8a0b1c2d3e4f5a6b7c8d9e0f",patch:DEMO_FAILED_PATCH,files:[["src/payout.ts",1,5],["src/config.ts",0,2]],handoff:built({conclusion:"Removed LEGACY_PAYOUT from settlement and config. The admin override still reads it, so one reference remains.",changes:["Dropped the legacy settlement branch in src/payout.ts.","Removed the LEGACY_PAYOUT flag from src/config.ts."],verification:["Searched the codebase for LEGACY_PAYOUT after the change."]}),proof:proofOf([met("c1","No reference to LEGACY_PAYOUT remains in the codebase.","Removed the flag and the settlement branch behind it.",[["changed-path","src/payout.ts"],["changed-path","src/config.ts"]])],["src/payout.ts","src/config.ts"],{caveats:["c1: src/admin/overrides.ts still reads LEGACY_PAYOUT for the per-merchant override toggle, so one reference remains."]}),at:times(5.6,5.6,5.5),facts:{},failed:!0});const copy=filed("confirm-empty-state-copy","Confirm the new inbox empty-state copy reads well",repos.web,{goal:"Rewrite the inbox's empty-state copy so it explains why nothing is there yet.",acceptance:[{id:"c1",statement:"The new empty-state copy reads clearly.",how:"Open the inbox pane with zero items and read it.",evidence:["manual-review"]}]},10,9);recordDemoBuild(store,evidenceRoot,startBuild(copy,"demo-lease-copy","night-shift-1",join(repos.web,".demo-worktree-5"),4),copy.taskId,{head:"1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe99",patch:DEMO_COPY_PATCH,files:[["src/inbox-copy.ts",3,1]],handoff:built({conclusion:"Rewrote the inbox's empty-state copy so it explains why the list is empty instead of just saying so.",changes:["Replaced the empty-state body copy in src/inbox-copy.ts."],verification:["Opened the inbox pane with zero items and read the new copy."],decisions:["Kept the copy to one sentence and a link to filters, with no illustration."],assumptions:["An empty inbox usually means a filter is on, not that there is no mail."],notDone:["The copy is English only; the other locales still show the old line."]}),proof:proofOf([met("c1","The new empty-state copy reads clearly.","Opened the inbox pane with zero items and read the new copy aloud.",[["manual-review","read the new copy in src/inbox-copy.ts"]])],["src/inbox-copy.ts"]),at:times(3.6,3.5,3.5),facts:{handoff:!0}});const reviewed=filed("guard-payout-limiter","Guard the payout limiter against concurrent settlement",repos.api,{goal:"Add a per-account concurrency guard so two settlements never race the same payout limiter.",outOfScope:"No changes to the limiter's public API.",touches:["src/payout-limiter.ts"],acceptance:[{id:"c1",statement:"Two concurrent settlements for the same account cannot both pass the limiter.",how:"Read the guard; an independent reviewer confirms it actually locks.",evidence:["manual-review"]},{id:"c2",statement:"The existing limiter tests still pass.",how:null,evidence:["check"]}]},6,5.8),reviewedRun=startBuild(reviewed,"demo-lease-reviewed","night-shift-1",join(repos.api,".demo-worktree-4"),5),reviewedArtifacts=recordDemoBuild(store,evidenceRoot,reviewedRun,reviewed.taskId,{head:"aa11bb22cc33dd44ee55ff6600112233445566aa",patch:DEMO_REPAIR_PATCH,files:[["src/payout-limiter.ts",1,0]],handoff:built({conclusion:"Added a TODO comment marking the per-account lock — ran out of turns before wiring the actual guard.",changes:["Marked the per-account lock in src/payout-limiter.ts."],verification:[]}),proof:proofOf([met("c1","Two concurrent settlements for the same account cannot both pass the limiter.","Added the lock.",[["manual-review","see src/payout-limiter.ts"]]),met("c2","The existing limiter tests still pass.","npm test",[["check","npm test"]])],["src/payout-limiter.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed."}]}),at:times(4.6,4.5,4.4),captureStatus:!0,verified:!0}),reviewAsked=store.requestReview(reviewedRun,"alex",hoursAgo(3.95));if(!reviewAsked.ok)throw new Error(`demo: the seeded review could not be requested (${reviewAsked.reason})`);const reviewerRun=store.startRun({taskRef:reviewed.ref,leaseId:"demo-lease-reviewer",runner:"night-shift-1",role:"reviewer",parentRun:reviewedRun,request:reviewAsked.id,provider:"codex",now:hoursAgo(3.9),...presentedRoute(store,reviewed.ref,"reviewer")}),reviewedProofSha=store.getArtifact(reviewedArtifacts.proof)?.sha256??null;store.stampProviderStart(reviewerRun,hoursAgo(3.9));const{folded}=store.ingestReview({reviewerRunId:reviewerRun,runId:reviewedRun,artifactId:reviewedArtifacts.diff,author:"reviewer:codex",comments:[{path:"src/payout-limiter.ts",line:1,note:"This is a TODO, not a lock — two concurrent calls both still read the same rate before either settles.",severity:"problem"}],judgements:[{id:"c1",judgement:"contradicts",note:"The diff adds a TODO comment, not an actual lock — two concurrent settlements still race the limiter."},{id:"c2",judgement:"upholds",note:"The stored check log supports that the existing limiter test suite still passes."}],bindings:{diffSha:store.getArtifact(reviewedArtifacts.diff)?.sha256??"",scopeDigest:reviewed.digest,headSha:store.getRun(reviewedRun)?.headRevision??store.getRun(reviewedRun)?.baseRevision??null,proof:reviewedProofSha===null?null:{artifactId:reviewedArtifacts.proof,sha256:reviewedProofSha},checkLog:null,screenshots:[]}},hoursAgo(3.9));if(folded===null)throw new Error("seed reviewed+repaired: the fold produced nothing");const repairTrigger=maybeTriggerRepair(store,repos.api,evidenceRoot,reviewedRun,folded.verdict,hoursAgo(3.9));if(repairTrigger.kind!=="drafted")throw new Error(`seed reviewed+repaired: expected a draft, got ${repairTrigger.kind}`);task("design-tokens","Extract the design tokens package",repos.web),task("ship-dark-mode","Ship dark mode",repos.web),store.addEdge("ship-dark-mode","design-tokens",{}),store.cancelTask("design-tokens",hoursAgo(10),"the token package was superseded");const held=task("migrate-billing","Migrate billing exports to the new vendor",repos.api);store.hold(store.refFor("built-in",held).id,"waiting on the vendor sandbox account",null,hoursAgo(12));const nightly=createScheduledFlow(store,{repo:realpathSync(repos.api),name:"Nightly dependency refresh",stem:"nightly-deps",schedule:"daily:03:30",by:"demo",terms:{goal:"Refresh the lockfile within existing ranges, run the suite, summarize anything notable.",outOfScope:"No major version bumps.",touches:[],requirements:[],budgetPerRunMicrousd:null,costCeilingUsd:null,acceptance:[{id:"c1",statement:"The full test suite passes against the refreshed lockfile.",how:null,evidence:["check"]}]}},hoursAgo(70));if(!nightly.ok)throw new Error(`seed scheduled flow: ${nightly.message}`);const pub=store.createPublicationIntent({run:doneRun,taskRef:done.ref,githubRepo:"acme/payments-api",remote:"origin",base:"main",head:`toolroll/${done.taskId}`,headSha:DONE_HEAD,bodyHash:"demo",draft:!1},hoursAgo(8.3));return store.markPublicationPushed(pub,hoursAgo(8.2)),store.markPublicationOpened(pub,47,"https://github.com/acme/payments-api/pull/47",hoursAgo(8.1)),store.recordPublicationCheckState(pub,"passing",hoursAgo(1.5)),seedDemoFlows(store,repos.web,now),{login:{name:"demo",password},repos:[repos.api,repos.web]}}export function makeDemoRepos(root){const make=(name,files)=>{const dir=join(root,name);mkdirSync(join(dir,"src"),{recursive:!0});for(const[file,content]of Object.entries(files))mkdirSync(dirname(join(dir,file)),{recursive:!0}),writeFileSync(join(dir,file),content);try{for(const args of[["init","-q","-b","main"],["add","-A"],["-c","user.email=demo@localhost","-c","user.name=demo","commit","-q","-m","seed"]])execFileSync("git",args,{cwd:dir,stdio:"ignore",timeout:3e4})}catch{}return dir};return{api:make("payments-api",{"package.json":JSON.stringify({name:"payments-api",private:!0},null,2),"src/payout.ts":`export function settle(cents: number, rate: number): number {
75
+ `,command:doneCheck}}),store.addRunNote(doneRun,"demo","Reviewed the diff — the fixture numbers check out. Shipping.",hoursAgo(3));const failed=filed("retire-legacy-flag","Retire the legacy payout feature flag",repos.api,{goal:"Remove LEGACY_PAYOUT and every branch behind it.",acceptance:[{id:"c1",statement:"No reference to LEGACY_PAYOUT remains in the codebase.",how:null,evidence:["changed-path"]}]},16,15);recordDemoBuild(store,evidenceRoot,startBuild(failed,"demo-lease-failed","night-shift-2",join(repos.api,".demo-worktree-4"),6),failed.taskId,{head:"5a1f0c7e2b9d4e6f8a0b1c2d3e4f5a6b7c8d9e0f",patch:DEMO_FAILED_PATCH,files:[["src/payout.ts",1,5],["src/config.ts",0,2]],handoff:built({conclusion:"Removed LEGACY_PAYOUT from settlement and config. The admin override still reads it, so one reference remains.",changes:["Dropped the legacy settlement branch in src/payout.ts.","Removed the LEGACY_PAYOUT flag from src/config.ts."],verification:["Searched the codebase for LEGACY_PAYOUT after the change."]}),proof:proofOf([met("c1","No reference to LEGACY_PAYOUT remains in the codebase.","Removed the flag and the settlement branch behind it.",[["changed-path","src/payout.ts"],["changed-path","src/config.ts"]])],["src/payout.ts","src/config.ts"],{caveats:["c1: src/admin/overrides.ts still reads LEGACY_PAYOUT for the per-merchant override toggle, so one reference remains."]}),at:times(5.6,5.6,5.5),facts:{},failed:!0});const copy=filed("confirm-empty-state-copy","Confirm the new inbox empty-state copy reads well",repos.web,{goal:"Rewrite the inbox's empty-state copy so it explains why nothing is there yet.",acceptance:[{id:"c1",statement:"The new empty-state copy reads clearly.",how:"Open the inbox pane with zero items and read it.",evidence:["manual-review"]}]},10,9);recordDemoBuild(store,evidenceRoot,startBuild(copy,"demo-lease-copy","night-shift-1",join(repos.web,".demo-worktree-5"),4),copy.taskId,{head:"1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe99",patch:DEMO_COPY_PATCH,files:[["src/inbox-copy.ts",3,1]],handoff:built({conclusion:"Rewrote the inbox's empty-state copy so it explains why the list is empty instead of just saying so.",changes:["Replaced the empty-state body copy in src/inbox-copy.ts."],verification:["Opened the inbox pane with zero items and read the new copy."],decisions:["Kept the copy to one sentence and a link to filters, with no illustration."],assumptions:["An empty inbox usually means a filter is on, not that there is no mail."],notDone:["The copy is English only; the other locales still show the old line."]}),proof:proofOf([met("c1","The new empty-state copy reads clearly.","Opened the inbox pane with zero items and read the new copy aloud.",[["manual-review","read the new copy in src/inbox-copy.ts"]])],["src/inbox-copy.ts"]),at:times(3.6,3.5,3.5),facts:{handoff:!0}});const reviewed=filed("guard-payout-limiter","Guard the payout limiter against concurrent settlement",repos.api,{goal:"Add a per-account concurrency guard so two settlements never race the same payout limiter.",outOfScope:"No changes to the limiter's public API.",touches:["src/payout-limiter.ts"],acceptance:[{id:"c1",statement:"Two concurrent settlements for the same account cannot both pass the limiter.",how:"Read the guard; an independent reviewer confirms it actually locks.",evidence:["manual-review"]},{id:"c2",statement:"The existing limiter tests still pass.",how:null,evidence:["check"]}]},6,5.8),reviewedRun=startBuild(reviewed,"demo-lease-reviewed","night-shift-1",join(repos.api,".demo-worktree-4"),5),reviewedArtifacts=recordDemoBuild(store,evidenceRoot,reviewedRun,reviewed.taskId,{head:"aa11bb22cc33dd44ee55ff6600112233445566aa",patch:DEMO_REPAIR_PATCH,files:[["src/payout-limiter.ts",1,0]],handoff:built({conclusion:"Added a TODO comment marking the per-account lock — ran out of turns before wiring the actual guard.",changes:["Marked the per-account lock in src/payout-limiter.ts."],verification:[]}),proof:proofOf([met("c1","Two concurrent settlements for the same account cannot both pass the limiter.","Added the lock.",[["manual-review","see src/payout-limiter.ts"]]),met("c2","The existing limiter tests still pass.","npm test",[["check","npm test"]])],["src/payout-limiter.ts"],{checks:[{command:"npm test",exitCode:0,summary:"214 tests passed."}]}),at:times(4.6,4.5,4.4),captureStatus:!0,verified:!0}),reviewAsked=store.requestReview(reviewedRun,"alex",hoursAgo(3.95));if(!reviewAsked.ok)throw new Error(`demo: the seeded review could not be requested (${reviewAsked.reason})`);const reviewerRun=store.startRun({taskRef:reviewed.ref,leaseId:"demo-lease-reviewer",runner:"night-shift-1",role:"reviewer",parentRun:reviewedRun,request:reviewAsked.id,provider:"codex",now:hoursAgo(3.9),...presentedRoute(store,reviewed.ref,"reviewer")}),reviewedProofSha=store.getArtifact(reviewedArtifacts.proof)?.sha256??null;store.stampProviderStart(reviewerRun,hoursAgo(3.9));const{folded}=store.ingestReview({reviewerRunId:reviewerRun,runId:reviewedRun,artifactId:reviewedArtifacts.diff,author:"reviewer:codex",comments:[{path:"src/payout-limiter.ts",line:1,note:"This is a TODO, not a lock — two concurrent calls both still read the same rate before either settles.",severity:"problem"}],judgements:[{id:"c1",judgement:"contradicts",note:"The diff adds a TODO comment, not an actual lock — two concurrent settlements still race the limiter."},{id:"c2",judgement:"upholds",note:"The stored check log supports that the existing limiter test suite still passes."}],bindings:{diffSha:store.getArtifact(reviewedArtifacts.diff)?.sha256??"",scopeDigest:reviewed.digest,headSha:store.getRun(reviewedRun)?.headRevision??store.getRun(reviewedRun)?.baseRevision??null,proof:reviewedProofSha===null?null:{artifactId:reviewedArtifacts.proof,sha256:reviewedProofSha},checkLog:null,screenshots:[]}},hoursAgo(3.9));if(folded===null)throw new Error("seed reviewed+repaired: the fold produced nothing");const repairTrigger=maybeTriggerRepair(store,repos.api,evidenceRoot,reviewedRun,folded.verdict,hoursAgo(3.9));if(repairTrigger.kind!=="drafted")throw new Error(`seed reviewed+repaired: expected a draft, got ${repairTrigger.kind}`);task("design-tokens","Extract the design tokens package",repos.web),task("ship-dark-mode","Ship dark mode",repos.web),store.addEdge("ship-dark-mode","design-tokens",{}),store.cancelTask("design-tokens",hoursAgo(10),"the token package was superseded");const held=task("migrate-billing","Migrate billing exports to the new vendor",repos.api);store.hold(store.refFor("built-in",held).id,"waiting on the vendor sandbox account",null,hoursAgo(12));const nightly=createScheduledFlow(store,{repo:realpathSync(repos.api),name:"Nightly dependency refresh",stem:"nightly-deps",schedule:"daily:03:30",by:"demo",terms:{goal:"Refresh the lockfile within existing ranges, run the suite, summarize anything notable.",outOfScope:"No major version bumps.",touches:[],requirements:[],budgetPerRunMicrousd:null,costCeilingUsd:null,acceptance:[{id:"c1",statement:"The full test suite passes against the refreshed lockfile.",how:null,evidence:["check"]}]}},hoursAgo(70));if(!nightly.ok)throw new Error(`seed scheduled flow: ${nightly.message}`);const pub=store.createPublicationIntent({run:doneRun,taskRef:done.ref,githubRepo:"acme/payments-api",remote:"origin",base:"main",head:`toolroll/${done.taskId}`,headSha:DONE_HEAD,bodyHash:"demo",draft:!1},hoursAgo(8.3));return store.markPublicationPushed(pub,hoursAgo(8.2)),store.markPublicationOpened(pub,47,"https://github.com/acme/payments-api/pull/47",hoursAgo(8.1)),store.recordPublicationCheckState(pub,"passing",hoursAgo(1.5)),seedDemoFlows(store,repos.web,now),{login:{name:"demo",password},repos:[repos.api,repos.web]}}export function makeDemoRepos(root){const make=(name,files)=>{const dir=join(root,name);mkdirSync(join(dir,"src"),{recursive:!0});for(const[file,content]of Object.entries(files))mkdirSync(dirname(join(dir,file)),{recursive:!0}),writeFileSync(join(dir,file),content);try{for(const args of[["init","-q","-b","main"],["add","-A"],["-c","user.email=demo@localhost","-c","user.name=demo","commit","-q","-m","seed"]])execFileSync("git",args,{cwd:dir,stdio:"ignore",timeout:3e4,env:withoutLeadTokenEnv(process.env)})}catch{}return dir};return{api:make("payments-api",{"package.json":JSON.stringify({name:"payments-api",private:!0},null,2),"src/payout.ts":`export function settle(cents: number, rate: number): number {
76
76
  return Math.round(cents * rate * 100) / 100;
77
77
  }
78
78
  `,...demoLeadFiles("payments-api")}),web:make("web-console",{"package.json":JSON.stringify({name:"web-console",private:!0},null,2),"src/app.ts":`export const app = () => 'hello';