@desplega.ai/agent-swarm 2.13.0 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/dist/acp-adapter-xtj40wd8.js +17 -0
  2. package/dist/{acp-targets-86f0sh6g.js → acp-targets-n7vm5atw.js} +10 -10
  3. package/dist/{actions-zv8vcxvr.js → actions-hq6wp9xv.js} +27 -27
  4. package/dist/{agent-fs-provision-jqshb33y.js → agent-fs-provision-y0qc1rdd.js} +4 -4
  5. package/dist/{amp-adapter-gt503ywc.js → amp-adapter-1qqs6h91.js} +3 -3
  6. package/dist/{app-6t4k5rh1.js → app-7m4z44rv.js} +10 -10
  7. package/dist/{approval-notifications-fcfw063h.js → approval-notifications-8sr41gjx.js} +11 -11
  8. package/dist/{assistant-9dzybh12.js → assistant-hkczwfv6.js} +28 -28
  9. package/dist/{boot-args-schema-xzfp2feg.js → boot-args-schema-8025snev.js} +1 -1
  10. package/dist/{boot-reembed-r88wngfg.js → boot-reembed-15m87nr1.js} +1 -1
  11. package/dist/{boot-reembed-3jz0p2jk.js → boot-reembed-4bbpxjh1.js} +1 -1
  12. package/dist/{boot-scrub-sweep-scrqhw48.js → boot-scrub-sweep-eajr97e9.js} +2 -2
  13. package/dist/{boot-seeds-vb2dcrrb.js → boot-seeds-9cwy39jx.js} +4 -4
  14. package/dist/{boxd-68n75y1s.js → boxd-hr8rsxzq.js} +1 -1
  15. package/dist/{claude-adapter-h3mp9hgs.js → claude-adapter-g61wa4rt.js} +9 -9
  16. package/dist/{claude-managed-adapter-kpbyj2vb.js → claude-managed-adapter-znkk0prm.js} +3 -3
  17. package/dist/{claude-managed-setup-0efr3wkg.js → claude-managed-setup-f1wndkr2.js} +2 -2
  18. package/dist/{claude-sdk-session-03dw669q.js → claude-sdk-session-687xzf21.js} +20763 -19381
  19. package/dist/{cli-gfcv679k.js → cli-04103ryh.js} +1 -1
  20. package/dist/{cli-hbq0kwxz.js → cli-0a336ze7.js} +4 -4
  21. package/dist/{cli-1v82d2w6.js → cli-0fx95c06.js} +4 -4
  22. package/dist/{cli-wxwv3t11.js → cli-0m77n7ej.js} +3 -3
  23. package/dist/{cli-j53hpbsm.js → cli-0xwb7zpt.js} +2 -2
  24. package/dist/{cli-0dg7ytxm.js → cli-13t0smbk.js} +917 -23
  25. package/dist/{cli-0pazkmd4.js → cli-1b5axkt1.js} +4 -4
  26. package/dist/{cli-6h88mn9q.js → cli-1carhg8g.js} +4 -4
  27. package/dist/{cli-hgsxnjyg.js → cli-1dr5at77.js} +10 -10
  28. package/dist/{cli-0jkenasr.js → cli-2v4xxnx2.js} +1 -1
  29. package/dist/{cli-dnh64e8e.js → cli-32xndx6b.js} +6 -6
  30. package/dist/{cli-hpb9x72z.js → cli-3m8vqehw.js} +9 -9
  31. package/dist/{cli-ercwc8xn.js → cli-3mf04tkh.js} +1 -1
  32. package/dist/{cli-7dbhnsj9.js → cli-3zyme1wt.js} +4 -4
  33. package/dist/{cli-s6zk31gr.js → cli-43dsqhcp.js} +4 -4
  34. package/dist/{cli-t35hx078.js → cli-4h90xaet.js} +2 -2
  35. package/dist/{cli-117g15t4.js → cli-4mj5g29m.js} +8 -8
  36. package/dist/{cli-47hz21se.js → cli-4tbvndmm.js} +4 -5
  37. package/dist/{cli-tn91wc6e.js → cli-50whymxq.js} +1 -1
  38. package/dist/{cli-js10kdk7.js → cli-5basv0e7.js} +19 -5
  39. package/dist/{cli-xfjn2kyq.js → cli-5v6b2am8.js} +5 -5
  40. package/dist/{cli-49f5jyhh.js → cli-6r1dwegd.js} +3 -3
  41. package/dist/{cli-kspxjftk.js → cli-7ewre3dm.js} +15 -6
  42. package/dist/{cli-n3qe7tyr.js → cli-84xtgbn6.js} +35 -2
  43. package/dist/{cli-w14j2z4k.js → cli-8cmjkbvj.js} +2 -2
  44. package/dist/{cli-2m6yaq6b.js → cli-8fj8yfmk.js} +1 -1
  45. package/dist/{cli-9m9kyw77.js → cli-8rbkw18r.js} +2 -2
  46. package/dist/{cli-x05p2d05.js → cli-9tevdxyf.js} +1 -1
  47. package/dist/{cli-f1952kjy.js → cli-9xx36trj.js} +4 -4
  48. package/dist/{cli-hc6e4tac.js → cli-a8ts6x1n.js} +6 -6
  49. package/dist/{cli-mh7pdxe0.js → cli-aebswqmz.js} +12 -12
  50. package/dist/{cli-ex1y88j3.js → cli-at67kvnp.js} +1 -1
  51. package/dist/{cli-b2jh3dyb.js → cli-bjmq14k9.js} +4 -4
  52. package/dist/{cli-mz34pxbk.js → cli-byxsctca.js} +11 -11
  53. package/dist/{cli-dka73bak.js → cli-c0tyzt73.js} +152 -12
  54. package/dist/{cli-wv20kbr3.js → cli-c8kqmzzf.js} +5 -5
  55. package/dist/{cli-qhhb30e8.js → cli-cd9acnvd.js} +9 -9
  56. package/dist/{cli-wndegmns.js → cli-cmgdptmx.js} +3 -3
  57. package/dist/{cli-1dbv9mj9.js → cli-cn6fpa1p.js} +1 -1
  58. package/dist/{cli-wrhbym01.js → cli-cp0m07wb.js} +6 -6
  59. package/dist/{cli-3p288654.js → cli-cpkxh68d.js} +2 -2
  60. package/dist/{cli-g6j6ac3h.js → cli-cqxwjb93.js} +2 -2
  61. package/dist/{cli-8hp56wat.js → cli-d2epqm0y.js} +1 -1
  62. package/dist/{cli-qm3ntjqs.js → cli-dd57p1gd.js} +13 -13
  63. package/dist/{cli-tstj6e8e.js → cli-fn8aj7gb.js} +250 -55
  64. package/dist/{cli-bpje8n65.js → cli-fp65jdp2.js} +31 -6
  65. package/dist/{cli-2skf1mdf.js → cli-gedf48yw.js} +4 -4
  66. package/dist/{cli-c8v2yvej.js → cli-gq6qhmrr.js} +2 -2
  67. package/dist/{cli-sq913bh1.js → cli-grcc2h2g.js} +8 -8
  68. package/dist/{cli-qec9bynj.js → cli-h03j6je3.js} +3 -3
  69. package/dist/{cli-mbwmqb5w.js → cli-h0ewec3d.js} +1 -1
  70. package/dist/{cli-jj3c5nyb.js → cli-h9bejmkf.js} +76 -39
  71. package/dist/{cli-ct8sz3np.js → cli-hs3mqswp.js} +6 -6
  72. package/dist/{cli-tdk7jtka.js → cli-hv3820ez.js} +1 -1
  73. package/dist/{cli-pqfecppn.js → cli-je587f74.js} +1 -1
  74. package/dist/{cli-y4a4458j.js → cli-jhtvt7gn.js} +3 -3
  75. package/dist/{cli-dkejt425.js → cli-mmw2sjaf.js} +7 -7
  76. package/dist/{cli-50w82h6m.js → cli-mwxez0pz.js} +1 -0
  77. package/dist/{cli-avxh26pd.js → cli-nk8swfpx.js} +4 -4
  78. package/dist/{cli-fhvk2nvp.js → cli-p7g7wd9n.js} +9 -9
  79. package/dist/{cli-bhgrhedp.js → cli-q8aq48v1.js} +1 -1
  80. package/dist/{cli-6a40p4kv.js → cli-qn79645p.js} +1 -1
  81. package/dist/{cli-nc6a8b5b.js → cli-qx1dwrr5.js} +2 -2
  82. package/dist/{cli-sdh61g52.js → cli-s6fhqbz1.js} +2 -2
  83. package/dist/{cli-eb279wn3.js → cli-sfajkbd7.js} +2 -2
  84. package/dist/{cli-z64t9pe6.js → cli-snypfjgj.js} +1 -1
  85. package/dist/{cli-ytc7fpza.js → cli-t25rq8mg.js} +4 -4
  86. package/dist/{cli-zqmmy073.js → cli-t90k0phh.js} +18 -18
  87. package/dist/{cli-fz9pcjsw.js → cli-tzzas8rb.js} +4 -4
  88. package/dist/{cli-rtmqzat7.js → cli-vdfngx2g.js} +2 -2
  89. package/dist/{cli-9w8712tq.js → cli-vr4eyq6p.js} +43 -14
  90. package/dist/{cli-z4f346g5.js → cli-vx9acp12.js} +1 -1
  91. package/dist/{cli-y518qkjg.js → cli-w24f3j49.js} +10 -10
  92. package/dist/{cli-yn4kt85g.js → cli-w41bvvms.js} +1 -1
  93. package/dist/{cli-9fsagra4.js → cli-w6c6dj91.js} +1 -1
  94. package/dist/{cli-kde4ky90.js → cli-x5yb8zc8.js} +2 -2
  95. package/dist/{cli-48nvk6sb.js → cli-xhkek467.js} +2 -2
  96. package/dist/{cli-avqkr20b.js → cli-y6qqbpwc.js} +2 -2
  97. package/dist/{cli-7wy8gbwb.js → cli-ya1cj689.js} +1 -1
  98. package/dist/{cli-prf7kz78.js → cli-yeh3g1q6.js} +603 -78
  99. package/dist/{cli-ajjvqhf3.js → cli-z6m6xzxt.js} +2 -2
  100. package/dist/{cli-2jk4s7z1.js → cli-zaate0rd.js} +3 -3
  101. package/dist/{cli-n85m2wkq.js → cli-zkbz8m2q.js} +3 -2
  102. package/dist/{cli-0b655smz.js → cli-zvpkrgsc.js} +5 -5
  103. package/dist/cli.js +27 -27
  104. package/dist/{codex-adapter-f3yp0kaj.js → codex-adapter-ysfg6ty3.js} +8 -8
  105. package/dist/{codex-hook-262cekfp.js → codex-hook-c0nvm30r.js} +2 -2
  106. package/dist/{codex-login-1ven7yje.js → codex-login-ven5cz5j.js} +1 -1
  107. package/dist/{codex-session-runner-ns4mv70p.js → codex-session-runner-823scr6g.js} +9 -9
  108. package/dist/{commands-5bzf2tfw.js → commands-5rbm07fz.js} +3 -3
  109. package/dist/{controller-5xt7kvfm.js → controller-wn3vd217.js} +3 -3
  110. package/dist/{controllers-connect-0gg13mzp.js → controllers-connect-34jzhfft.js} +28 -28
  111. package/dist/core-kdehq26g.js +42 -0
  112. package/dist/{cursor-adapter-p0c5zv6r.js → cursor-adapter-w1681kp1.js} +2 -2
  113. package/dist/{db-2s68ycq7.js → db-6bkgbfwk.js} +3 -3
  114. package/dist/{db-q7q639k5.js → db-hcj16x7z.js} +2 -2
  115. package/dist/{devin-adapter-t8d86q9x.js → devin-adapter-fs90ab4v.js} +1 -1
  116. package/dist/{dispatcher-j2y1q7ae.js → dispatcher-jgjqrfzv.js} +25 -25
  117. package/dist/{docker-1b41eysj.js → docker-1h33jvh9.js} +2 -2
  118. package/dist/{dsh-adapter-pgnkf4st.js → dsh-adapter-g9yqv09y.js} +2 -2
  119. package/dist/{e2b-xm60c8ad.js → e2b-jnk0yeva.js} +2 -2
  120. package/dist/{e2b-ew8c5j5v.js → e2b-y7e5kmzf.js} +2 -2
  121. package/dist/{easter-egg-3d-0kea97jf.js → easter-egg-3d-w17nsny6.js} +1 -1
  122. package/dist/{embedding-space-3n6mhhmy.js → embedding-space-v06fwy7b.js} +6 -6
  123. package/dist/{embeddings-jfmj6yme.js → embeddings-g50dxea4.js} +1 -1
  124. package/dist/{event-bus-v4ywhc2p.js → event-bus-08t2b4y2.js} +1 -1
  125. package/dist/{execute-tjrej979.js → execute-1n36haw1.js} +1 -1
  126. package/dist/{external-channel-jy8w2gg3.js → external-channel-43tv8pg6.js} +2 -2
  127. package/dist/fx-adapter-bvh05t4a.js +20 -0
  128. package/dist/grok-adapter-my5j8mdf.js +20 -0
  129. package/dist/handlers-wyymeeqh.js +41 -0
  130. package/dist/heartbeat-sf3nk937.js +50 -0
  131. package/dist/{hook-bpnncsec.js → hook-dqph1e05.js} +8 -8
  132. package/dist/{hook-fv1jwrv7.js → hook-m1m9dm6w.js} +6 -6
  133. package/dist/{http-bpa26czn.js → http-w0th1cz9.js} +160 -102
  134. package/dist/index-22khdtby.js +44 -0
  135. package/dist/{index-mpj0z9e0.js → index-c0e8en64.js} +1 -1
  136. package/dist/{index-620y7jzq.js → index-e8pz8qdg.js} +3 -3
  137. package/dist/{index-8p0j4h4j.js → index-ez823q84.js} +94 -89
  138. package/dist/{index-w216g9y9.js → index-ffba0z8q.js} +35 -21
  139. package/dist/{index-s8re7mvq.js → index-gkpfgpg7.js} +1 -1
  140. package/dist/{index-4k7m5dgj.js → index-k8ajc0g0.js} +143 -103
  141. package/dist/index-np0582ac.js +40 -0
  142. package/dist/{index-52tgbhrw.js → index-pb03vans.js} +28 -28
  143. package/dist/index-vgkrj1jt.js +39 -0
  144. package/dist/{index-pe3d8jfy.js → index-whysn1wf.js} +1 -1
  145. package/dist/{index-0h6qd4p1.js → index-y4vd4mhn.js} +3 -4
  146. package/dist/{k8s-fy8hbhkg.js → k8s-8326q0rq.js} +2 -2
  147. package/dist/{keepalive-d6z12s04.js → keepalive-2v06q2e8.js} +5 -4
  148. package/dist/lead-55z813ng.js +79 -0
  149. package/dist/{maintenance-7kac6g2g.js → maintenance-vx7vjhhy.js} +1 -1
  150. package/dist/{oauth-refresh-sweep-t1xjetbh.js → oauth-refresh-sweep-g06k4bza.js} +4 -3
  151. package/dist/{object-webhooks-6rdagg0r.js → object-webhooks-3dzdq4fm.js} +7 -7
  152. package/dist/{onboard-32y1cfxy.js → onboard-232pazny.js} +4 -4
  153. package/dist/{opencode-adapter-enp3v31n.js → opencode-adapter-t0paqbh8.js} +8 -8
  154. package/dist/{otel-impl-k0tm5ptj.js → otel-impl-kmpkyp4y.js} +2 -2
  155. package/dist/{pending-24zebgvs.js → pending-x0z3vx1x.js} +26 -26
  156. package/dist/{pi-mono-adapter-yj72xxxe.js → pi-mono-adapter-7pmypn6d.js} +17 -15
  157. package/dist/{pricing-refresh-cf25x38j.js → pricing-refresh-ytjmtyd7.js} +2 -2
  158. package/dist/{rbac-roles-0wydd22m.js → rbac-roles-fgm5mxr2.js} +3 -3
  159. package/dist/{rbac-roles-at6crb3r.js → rbac-roles-xyaxekh3.js} +2 -2
  160. package/dist/{render-v2-nvcw0jd7.js → render-v2-ws972g4r.js} +10 -10
  161. package/dist/{resume-y4w0k5v3.js → resume-m6mjzhkp.js} +13 -13
  162. package/dist/{runtime-vpe43hx0.js → runtime-zzpc0c8a.js} +1 -1
  163. package/dist/{session-access-gkyvnfye.js → session-access-vp35xs91.js} +5 -5
  164. package/dist/{session-source-backfill-3w2st4m2.js → session-source-backfill-p73e8zbe.js} +2 -2
  165. package/dist/{setup-axxvqtys.js → setup-r4kd7rxg.js} +1 -1
  166. package/dist/thread-buffer-cm2nzq6t.js +42 -0
  167. package/dist/{tree-visibility-y4fqvab5.js → tree-visibility-07h2tbs2.js} +2 -2
  168. package/dist/{user-merge-jobs-kcmwvrc6.js → user-merge-jobs-96vg9rpe.js} +3 -3
  169. package/dist/{virtual-modules-7d92dct1.js → virtual-modules-vgn3f2x4.js} +3 -3
  170. package/dist/{work-objects-f708e069.js → work-objects-74hbcx3e.js} +28 -28
  171. package/dist/worker-5pn2vzx6.js +79 -0
  172. package/dist/{worker-follow-up-0by8wztc.js → worker-follow-up-ezavwn5d.js} +25 -25
  173. package/dist/{x-3dtaf2r9.js → x-asbrnafg.js} +2 -2
  174. package/openapi.json +1793 -1622
  175. package/package.json +10 -10
  176. package/src/apps/catalog.generated.json +726 -0
  177. package/src/apps/definition.ts +24 -7
  178. package/src/apps/page-validator.ts +225 -3
  179. package/src/be/db.ts +38 -10
  180. package/src/be/mcp-proxy.ts +5 -4
  181. package/src/be/migrations/340_api_key_spend_cap.sql +5 -0
  182. package/src/be/schedules/validate.ts +26 -0
  183. package/src/be/swarm-config-guard.ts +4 -0
  184. package/src/commands/credential-outcome-report.ts +5 -2
  185. package/src/commands/onboard/agent-fs-version.ts +1 -1
  186. package/src/commands/provider-credentials.ts +19 -0
  187. package/src/commands/provider-error-class.ts +4 -1
  188. package/src/commands/rate-limit-outcome.ts +48 -3
  189. package/src/commands/runner.ts +113 -55
  190. package/src/commands/worktree-reaper.ts +600 -0
  191. package/src/extensions/contract-types.generated.ts +1 -1
  192. package/src/http/agents.ts +4 -0
  193. package/src/http/api-keys.ts +27 -3
  194. package/src/http/pages-public.ts +40 -4
  195. package/src/http/pool-keys.ts +21 -2
  196. package/src/http/schedules.ts +28 -3
  197. package/src/http/script-connections.ts +12 -4
  198. package/src/http/script-runs.ts +12 -3
  199. package/src/http/tasks.ts +6 -10
  200. package/src/mcp-client/http-client.ts +3 -1
  201. package/src/oauth/identity-capture.ts +6 -1
  202. package/src/oauth/mcp-wrapper.ts +10 -3
  203. package/src/oauth/wrapper.ts +15 -3
  204. package/src/prompts/session-templates.ts +1 -0
  205. package/src/providers/acp-targets.ts +2 -2
  206. package/src/providers/amp-adapter.ts +1 -1
  207. package/src/providers/dsh-adapter.ts +1 -1
  208. package/src/providers/pi-mono-adapter.ts +4 -2
  209. package/src/providers/runtime-dependencies.ts +1 -1
  210. package/src/rbac/legacy-policy.ts +2 -0
  211. package/src/rbac/permissions.ts +5 -0
  212. package/src/scripts-runtime/types/swarm-extension.d.ts +7 -7
  213. package/src/slack/enrich.ts +14 -11
  214. package/src/tests/agents-list-model-display.test.ts +23 -0
  215. package/src/tests/apps-spike2.test.ts +35 -0
  216. package/src/tests/base-prompt.test.ts +1 -0
  217. package/src/tests/deploy-guard.test.ts +24 -0
  218. package/src/tests/dsh-adapter.test.ts +1 -1
  219. package/src/tests/ensure-token.test.ts +2 -2
  220. package/src/tests/entrypoint-repo-autoclone-args.test.ts +202 -0
  221. package/src/tests/fake-dns.ts +47 -0
  222. package/src/tests/fixtures/base-prompt-baseline.json +12 -12
  223. package/src/tests/latest-model-report.test.ts +138 -0
  224. package/src/tests/mcp-oauth-dcr-reuse.test.ts +5 -2
  225. package/src/tests/mcp-oauth-ensure-token.test.ts +3 -2
  226. package/src/tests/mcp-oauth-manual-client.test.ts +6 -1
  227. package/src/tests/mcp-oauth-wrapper.test.ts +20 -4
  228. package/src/tests/mcp-outbound-fetch-guard.test.ts +169 -0
  229. package/src/tests/mcp-server-ssrf.test.ts +2 -0
  230. package/src/tests/memory-search-stall.test.ts +5 -0
  231. package/src/tests/oauth-connection-fetch-guard.test.ts +162 -0
  232. package/src/tests/oauth-token-endpoint-fetch-guard.test.ts +121 -0
  233. package/src/tests/oauth-wrapper.test.ts +1 -2
  234. package/src/tests/pages-head-v2.test.ts +2 -1
  235. package/src/tests/script-connections-http.test.ts +8 -3
  236. package/src/tests/script-connections.test.ts +2 -0
  237. package/src/tests/slack-thread-participants.test.ts +14 -3
  238. package/src/tests/spend-cap-credentials.test.ts +34 -0
  239. package/src/tests/spend-cap-outcome.test.ts +67 -0
  240. package/src/tests/subscription-first.test.ts +119 -0
  241. package/src/tests/worktree-reaper.test.ts +424 -0
  242. package/src/tools/get-task-details.ts +247 -5
  243. package/src/tools/schedules/patch-schedule.ts +26 -1
  244. package/src/tools/schedules/update-schedule.ts +28 -2
  245. package/src/utils/credentials.ts +36 -1
  246. package/src/utils/egress-guard.ts +40 -10
  247. package/src/utils/error-tracker.ts +17 -0
  248. package/templates/skills/apps/SKILL.md +191 -2
  249. package/templates/skills/apps/content.md +191 -2
  250. package/templates/skills/boards-and-sheets/content.md +11 -0
  251. package/templates/skills/pages/content.md +11 -0
  252. package/templates/skills/swarm-docs/content.md +2 -0
  253. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  254. package/templates/skills/swarm-scripts/content.md +1 -0
  255. package/templates/workflows/ralph-loop/content.md +6 -6
  256. package/dist/acp-adapter-cn53011z.js +0 -17
  257. package/dist/cli-pr0eze3x.js +0 -149
  258. package/dist/core-0fqtbrxa.js +0 -42
  259. package/dist/fx-adapter-k6w3jvz9.js +0 -20
  260. package/dist/grok-adapter-4q5tssw0.js +0 -20
  261. package/dist/handlers-qxgfvvsf.js +0 -41
  262. package/dist/heartbeat-6tr2w2da.js +0 -50
  263. package/dist/index-0mcxjdsa.js +0 -44
  264. package/dist/index-dz4q23ag.js +0 -40
  265. package/dist/index-s175jckx.js +0 -39
  266. package/dist/lead-p3hx7h35.js +0 -79
  267. package/dist/thread-buffer-rwa7d4dx.js +0 -42
  268. package/dist/worker-8rg9gz74.js +0 -79
@@ -390,6 +390,8 @@ const AppPageSchema = z
390
390
  headerActions: z.string().optional(),
391
391
  /** `false` leaves the page out of the sidebar. Pages with a required param never list. */
392
392
  nav: z.boolean().optional(),
393
+ /** Page-local state: initial JSON values, read and written at `/local/<name>`. */
394
+ state: z.record(AppNameSchema, z.unknown()).optional(),
393
395
  })
394
396
  .strict();
395
397
 
@@ -1082,19 +1084,32 @@ export async function parseAppDefinition(
1082
1084
  continue;
1083
1085
  }
1084
1086
  // Invoke-time runs the script with the OWNER's bindings, so a writer may
1085
- // only wire scripts it owns (or global ones). A reference the stored
1087
+ // only wire scripts it owns (or owner-less global ones). A reference the stored
1086
1088
  // definition already carries at this exact path is grandfathered so
1087
1089
  // foreign-authored apps stay editable — the bare id is not, so an existing
1088
1090
  // foreign reference cannot seed a new one elsewhere.
1089
- if (
1090
- foreignScriptForWriter(elementContext, script) &&
1091
- grandfatheredScriptRefs.get(`actions.${name}`) !==
1092
- scriptRefKey(action.scriptId, action.args, undefined)
1093
- ) {
1091
+ const grandfatheredRef =
1092
+ grandfatheredScriptRefs.get(`actions.${name}`) ===
1093
+ scriptRefKey(action.scriptId, action.args, undefined);
1094
+ const owner = getSavedScriptOwnerAgentId(script);
1095
+ if (foreignScriptForWriter(elementContext, script) && !grandfatheredRef) {
1094
1096
  issues.push({
1095
1097
  path: `actions.${name}.scriptId`,
1096
1098
  message: `script "${action.scriptId}" is agent-scoped to another agent — reference a script you own or a global script`,
1097
1099
  });
1100
+ } else if (
1101
+ // A global script with an owning agent also runs as that owner, so the
1102
+ // sync-source rule applies: only that agent or the operator may wire it.
1103
+ script.scope !== "agent" &&
1104
+ owner !== null &&
1105
+ (elementContext.writerIsUser === true || typeof elementContext.writerAgentId === "string") &&
1106
+ elementContext.writerAgentId !== owner &&
1107
+ !grandfatheredRef
1108
+ ) {
1109
+ issues.push({
1110
+ path: `actions.${name}.scriptId`,
1111
+ message: `script "${action.scriptId}" runs with agent "${owner}"'s credentials — only that agent or the operator may wire or alter this action`,
1112
+ });
1098
1113
  }
1099
1114
  }
1100
1115
 
@@ -1194,7 +1209,9 @@ function applyMergePatch(target: unknown, patch: unknown, path: string[]): unkno
1194
1209
  (path.length === 3 && path[0] === "models" && path[2] === "columns") ||
1195
1210
  (path.length === 3 && path[0] === "models" && path[2] === "sources") ||
1196
1211
  (path.length === 3 && path[0] === "elements" && path[2] === "elements") ||
1197
- (path.length === 3 && path[0] === "pages" && (path[2] === "elements" || path[2] === "params"));
1212
+ (path.length === 3 &&
1213
+ path[0] === "pages" &&
1214
+ (path[2] === "elements" || path[2] === "params" || path[2] === "state"));
1198
1215
 
1199
1216
  for (const [key, value] of Object.entries(patch)) {
1200
1217
  if (value === null) {
@@ -34,6 +34,8 @@ interface SchemaValidationResult {
34
34
  interface StateRef {
35
35
  path: string;
36
36
  value: string;
37
+ /** A write target (`$bindState`, `ui.set`): only page-local `/local/<name>` state. */
38
+ write?: boolean;
37
39
  }
38
40
 
39
41
  export const ELEMENT_KEYS = new Set([
@@ -102,7 +104,23 @@ const RESERVED_UI_IDS = new Set(["__proto__", "constructor", "prototype"]);
102
104
  * keyed by component type. Chains nested one level deeper (an array prop
103
105
  * whose items each carry a chain) are listed in `ITEM_ACTION_CHAINS`.
104
106
  */
107
+ /** Mirrors `INPUT_KEYS` (apps/ui `catalog.ts`): the `onKeyDown:<Key>` props an Input accepts. */
108
+ const INPUT_KEYS = [
109
+ "Backspace",
110
+ "Delete",
111
+ "Enter",
112
+ "Escape",
113
+ "Tab",
114
+ "ArrowLeft",
115
+ "ArrowRight",
116
+ "ArrowUp",
117
+ "ArrowDown",
118
+ "Home",
119
+ "End",
120
+ ];
121
+
105
122
  const PROP_ACTION_CHAINS: Record<string, readonly string[]> = {
123
+ Input: ["onInput", "onPaste", ...INPUT_KEYS.map((key) => `onKeyDown:${key}`)],
106
124
  Table: ["onRowClick", "onRetry"],
107
125
  Form: ["onSubmit"],
108
126
  Kanban: ["onMove", "onCardClick"],
@@ -265,6 +283,46 @@ function collectRepeatBindingPaths(value: unknown, path: string, paths: string[]
265
283
  }
266
284
  }
267
285
 
286
+ /**
287
+ * Expression operators and their operand counts `[min, max]`. Mirrors
288
+ * `apps/ui/src/lib/json-render/expressions.ts`.
289
+ */
290
+ const EXPRESSION_ARITY: Record<string, readonly [number, number]> = {
291
+ $add: [1, Infinity],
292
+ $sub: [2, 2],
293
+ $mul: [1, Infinity],
294
+ $div: [2, 2],
295
+ $min: [1, Infinity],
296
+ $max: [1, Infinity],
297
+ $split: [1, 3],
298
+ $join: [1, 2],
299
+ $length: [1, 1],
300
+ };
301
+
302
+ /** The operator of a `{ "$op": [...] }` expression object, or null. */
303
+ function expressionOp(value: unknown): string | null {
304
+ if (!isPlainObject(value)) return null;
305
+ const keys = Object.keys(value);
306
+ return keys.length === 1 && Object.hasOwn(EXPRESSION_ARITY, keys[0]!) ? keys[0]! : null;
307
+ }
308
+
309
+ /** Svg shapes: valid only as children of an `Svg`. */
310
+ const SVG_SHAPES = new Set(["Rect", "Line", "Path", "Circle", "SvgText"]);
311
+ /** Mirrors `SVG_PATH_DATA` (apps/ui `catalog.ts`): path commands and numbers only. */
312
+ const SVG_PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]*$/;
313
+
314
+ function isBindStateBinding(value: unknown): value is { $bindState: string } {
315
+ return (
316
+ isPlainObject(value) && Object.keys(value).length === 1 && typeof value.$bindState === "string"
317
+ );
318
+ }
319
+
320
+ function isBindItemBinding(value: unknown): value is { $bindItem: string } {
321
+ return (
322
+ isPlainObject(value) && Object.keys(value).length === 1 && typeof value.$bindItem === "string"
323
+ );
324
+ }
325
+
268
326
  function isActionSentinel(value: unknown): boolean {
269
327
  if (!isPlainObject(value) || Object.keys(value).length !== 1) return false;
270
328
  if (typeof value.$row === "string") return true;
@@ -338,6 +396,38 @@ function validateSchema(
338
396
 
339
397
  if (isRepeatBinding(value)) return { issues: [], stateRefs: [] };
340
398
 
399
+ if (isBindStateBinding(value) || isBindItemBinding(value)) {
400
+ return {
401
+ issues: [issue(path, "$bindState and $bindItem are only allowed on Input.value")],
402
+ stateRefs: [],
403
+ };
404
+ }
405
+
406
+ const op = expressionOp(value);
407
+ if (op) {
408
+ const operands = (value as Record<string, unknown>)[op];
409
+ const [min, max] = EXPRESSION_ARITY[op]!;
410
+ if (!Array.isArray(operands) || operands.length < min || operands.length > max) {
411
+ const count = min === max ? `${min}` : max === Infinity ? `at least ${min}` : `${min}-${max}`;
412
+ return {
413
+ issues: [issue(appendPath(path, op), `must be an array of ${count} operand(s)`)],
414
+ stateRefs: [],
415
+ };
416
+ }
417
+ const result: SchemaValidationResult = { issues: [], stateRefs: [] };
418
+ for (const [index, operand] of operands.entries()) {
419
+ const operandResult = validateSchema(
420
+ operand,
421
+ {},
422
+ appendPath(appendPath(path, op), index),
423
+ allowActionSentinels,
424
+ );
425
+ result.issues.push(...operandResult.issues);
426
+ result.stateRefs.push(...operandResult.stateRefs);
427
+ }
428
+ return result;
429
+ }
430
+
341
431
  if (isActionSentinel(value)) {
342
432
  return allowActionSentinels
343
433
  ? { issues: [], stateRefs: [] }
@@ -592,6 +682,20 @@ function actionParams(
592
682
  );
593
683
  }
594
684
  }
685
+ } else if (step.action === "ui.set") {
686
+ // A literal path is checked against the page's declared state; a computed
687
+ // one (an expression) is held to `/local/...` by the runtime handler.
688
+ if (typeof params.path === "string") {
689
+ result.stateRefs.push({
690
+ path: appendPath(paramsPath, "path"),
691
+ value: params.path,
692
+ write: true,
693
+ });
694
+ } else if (!expressionOp(params.path)) {
695
+ result.issues.push(
696
+ issue(appendPath(paramsPath, "path"), "must be a /local/<name> path or an expression"),
697
+ );
698
+ }
595
699
  } else if (step.action === "ui.toast") {
596
700
  // The Undo chain runs through the same handlers as any other chain, so
597
701
  // its steps get the same per-action checks (models, queries, actions).
@@ -663,7 +767,24 @@ function validateStateRef(
663
767
  formIds: Set<string>,
664
768
  uiIds: Set<string>,
665
769
  pageParams: Record<string, unknown>,
770
+ pageState: Record<string, unknown>,
666
771
  ): AppValidationIssue | null {
772
+ const localMatch = /^\/local\/([^/]+)(?:\/.*)?$/.exec(ref.value);
773
+ if (localMatch) {
774
+ const name = localMatch[1]!;
775
+ if (!Object.hasOwn(pageState, name)) {
776
+ return issue(
777
+ ref.path,
778
+ `state reference targets undeclared page state "${name}"; declare it in the page's \`state\``,
779
+ );
780
+ }
781
+ return ref.value.split("/").some((segment) => RESERVED_UI_IDS.has(segment))
782
+ ? issue(ref.path, `invalid state reference "${ref.value}"`)
783
+ : null;
784
+ }
785
+ if (ref.write) {
786
+ return issue(ref.path, `only page-local /local/<name> state is writable (got "${ref.value}")`);
787
+ }
667
788
  if (ref.value === "/route/page") return null;
668
789
  const routeParam = /^\/route\/params\/([^/]+)$/.exec(ref.value);
669
790
  if (routeParam) {
@@ -1716,6 +1837,10 @@ export function validatePage(
1716
1837
  const page = options?.tree ?? definition.pages[pageName!]!;
1717
1838
  const pagePath = options?.path ?? appendPath("pages", pageName!);
1718
1839
  const pageParams = pageName ? (definition.pages[pageName]?.params ?? {}) : {};
1840
+ const pageState = pageName ? (definition.pages[pageName]?.state ?? {}) : {};
1841
+ const inputIds = new Set<string>();
1842
+ /** Input elements whose `value` is a `$bindItem`: they need a repeat over `/local` state. */
1843
+ const bindItemPaths: { elementId: string; path: string }[] = [];
1719
1844
  const elementsPath = appendPath(pagePath, "elements");
1720
1845
  const root = page.root;
1721
1846
  const elements = page.elements;
@@ -1778,9 +1903,25 @@ export function validatePage(
1778
1903
  ? itemActionChains(type, rawElement.props, propsPath).map(({ path }) => path)
1779
1904
  : [],
1780
1905
  );
1906
+ const inputValue =
1907
+ type === "Input" && isPlainObject(rawElement.props) ? rawElement.props.value : undefined;
1908
+ const boundInputValue = isBindStateBinding(inputValue) || isBindItemBinding(inputValue);
1781
1909
  const actionChainPath = (path: string): boolean =>
1782
1910
  (PROP_ACTION_CHAINS[String(type)] ?? []).some((prop) => path === `${propsPath}.${prop}`) ||
1783
- itemChainPaths.has(path);
1911
+ itemChainPaths.has(path) ||
1912
+ (boundInputValue && path === `${propsPath}.value`);
1913
+ if (isBindStateBinding(inputValue)) {
1914
+ stateRefs.push({ path: `${propsPath}.value`, value: inputValue.$bindState, write: true });
1915
+ } else if (isBindItemBinding(inputValue)) {
1916
+ bindItemPaths.push({ elementId, path: `${propsPath}.value` });
1917
+ }
1918
+ if (
1919
+ type === "Input" &&
1920
+ isPlainObject(rawElement.props) &&
1921
+ typeof rawElement.props.id === "string"
1922
+ ) {
1923
+ inputIds.add(rawElement.props.id);
1924
+ }
1784
1925
  const propsResult = validateSchema(
1785
1926
  Object.hasOwn(rawElement, "props") ? rawElement.props : {},
1786
1927
  component.props,
@@ -2181,6 +2322,82 @@ export function validatePage(
2181
2322
  }
2182
2323
  }
2183
2324
 
2325
+ // `$bindItem` writes into the repeated list, so the nearest repeat must
2326
+ // iterate page-local state.
2327
+ for (const { elementId, path } of bindItemPaths) {
2328
+ let parentId = parentByChild.get(elementId);
2329
+ const seen = new Set<string>();
2330
+ let repeatPath: unknown;
2331
+ while (parentId && !seen.has(parentId)) {
2332
+ seen.add(parentId);
2333
+ const parent = elements[parentId];
2334
+ if (isPlainObject(parent) && isPlainObject(parent.repeat)) {
2335
+ repeatPath = parent.repeat.statePath;
2336
+ break;
2337
+ }
2338
+ parentId = parentByChild.get(parentId);
2339
+ }
2340
+ if (typeof repeatPath !== "string") {
2341
+ issues.push(issue(path, "$bindItem is only allowed inside a repeated element"));
2342
+ } else {
2343
+ stateRefs.push({ path, value: repeatPath, write: true });
2344
+ }
2345
+ }
2346
+
2347
+ for (const [elementId, rawElement] of elementEntries) {
2348
+ if (!isPlainObject(rawElement)) continue;
2349
+ const elementPath = `${elementsPath}.${elementId}`;
2350
+ const parent = elements[parentByChild.get(elementId) ?? ""];
2351
+ const parentType = isPlainObject(parent) ? parent.type : undefined;
2352
+ if (typeof rawElement.type === "string" && SVG_SHAPES.has(rawElement.type)) {
2353
+ if (parentType !== "Svg") {
2354
+ issues.push(
2355
+ issue(appendPath(elementPath, "type"), `${rawElement.type} must be a child of an Svg`),
2356
+ );
2357
+ }
2358
+ }
2359
+ if (rawElement.type === "Svg" && parentType !== "Svg") {
2360
+ const props = isPlainObject(rawElement.props) ? rawElement.props : {};
2361
+ for (const key of ["width", "height"]) {
2362
+ if (props[key] === undefined) {
2363
+ issues.push(issue(`${elementPath}.props.${key}`, "is required on an outer Svg"));
2364
+ }
2365
+ }
2366
+ }
2367
+ if (rawElement.type === "Svg" && Array.isArray(rawElement.children)) {
2368
+ for (const [index, child] of rawElement.children.entries()) {
2369
+ const childType = isPlainObject(elements[String(child)])
2370
+ ? (elements[String(child)] as Record<string, unknown>).type
2371
+ : undefined;
2372
+ if (typeof childType === "string" && childType !== "Svg" && !SVG_SHAPES.has(childType)) {
2373
+ issues.push(
2374
+ issue(
2375
+ `${elementPath}.children.${index}`,
2376
+ `Svg children must be Rect, Line, Path, Circle, SvgText or Svg (got ${childType})`,
2377
+ ),
2378
+ );
2379
+ }
2380
+ }
2381
+ }
2382
+ if (
2383
+ rawElement.type === "Path" &&
2384
+ isPlainObject(rawElement.props) &&
2385
+ typeof rawElement.props.d === "string" &&
2386
+ !SVG_PATH_DATA.test(rawElement.props.d)
2387
+ ) {
2388
+ issues.push(issue(`${elementPath}.props.d`, "must hold SVG path commands and numbers only"));
2389
+ }
2390
+ }
2391
+
2392
+ // `ui.focus` ids are literal Input ids of this tree.
2393
+ visitPageActionSteps(page, pagePath, (step, path) => {
2394
+ if (step.action !== "ui.focus" || !isPlainObject(step.params)) return;
2395
+ const id = step.params.id;
2396
+ if (typeof id === "string" && !inputIds.has(id)) {
2397
+ issues.push(issue(`${path}.params.id`, `no Input with id "${id}" on this page`));
2398
+ }
2399
+ });
2400
+
2184
2401
  const visited = new Set<string>();
2185
2402
  const visiting = new Set<string>();
2186
2403
  const visit = (elementId: string): void => {
@@ -2241,7 +2458,12 @@ export function validatePage(
2241
2458
  const propMatch = /^\/props\/([^/]+)(?:\/.*)?$/.exec(ref.value);
2242
2459
  const userConfigRef = ref.value === "/user" || ref.value.startsWith("/user/");
2243
2460
  let stateIssue: AppValidationIssue | null;
2244
- if (options?.elementMode && userConfigRef) {
2461
+ if (options?.elementMode && ref.write) {
2462
+ stateIssue = issue(
2463
+ ref.path,
2464
+ `${options.elementMode} elements cannot write state; bind page-local state at page level`,
2465
+ );
2466
+ } else if (options?.elementMode && userConfigRef) {
2245
2467
  stateIssue = issue(
2246
2468
  ref.path,
2247
2469
  `${options.elementMode} elements cannot read /user state; read userConfig via a prop or bind it at page level`,
@@ -2256,7 +2478,7 @@ export function validatePage(
2256
2478
  `pure element state reference "${ref.value}" escapes /props/<declared>; use a declared prop or switch the element to bound mode`,
2257
2479
  );
2258
2480
  } else {
2259
- stateIssue = validateStateRef(ref, definition, formIds, uiIds, pageParams);
2481
+ stateIssue = validateStateRef(ref, definition, formIds, uiIds, pageParams, pageState);
2260
2482
  }
2261
2483
  if (stateIssue) issues.push(stateIssue);
2262
2484
  }
package/src/be/db.ts CHANGED
@@ -160,7 +160,7 @@ import {
160
160
  } from "../utils/config-env-export";
161
161
  import { MASKED_SECRET_VALUE } from "../utils/config-secrets";
162
162
  import { deriveProviderFromKeyType } from "../utils/credentials";
163
- import type { RateLimitWindowTelemetry } from "../utils/error-tracker";
163
+ import type { RateLimitWindowTelemetry, SpendCap } from "../utils/error-tracker";
164
164
  import { getGitHubHostForSql } from "../utils/github-host";
165
165
  import { extractGitHubPullRequestUrls } from "../utils/github-pull-request";
166
166
  import { validateHeartbeatExpiry } from "../utils/heartbeat-expiry";
@@ -11884,6 +11884,8 @@ export interface ApiKeyStatus {
11884
11884
  scopeId: string | null;
11885
11885
  status: string;
11886
11886
  rateLimitedUntil: string | null;
11887
+ /** The spend cap behind the current rate limit, or null for an ordinary one. */
11888
+ spendCap: SpendCap | null;
11887
11889
  lastUsedAt: string | null;
11888
11890
  lastRateLimitAt: string | null;
11889
11891
  totalUsageCount: number;
@@ -11912,9 +11914,10 @@ export interface ApiKeyStatus {
11912
11914
  updatedAt: string;
11913
11915
  }
11914
11916
 
11915
- type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows" | "providerAccount"> & {
11917
+ type ApiKeyStatusRow = Omit<ApiKeyStatus, "rateLimitWindows" | "providerAccount" | "spendCap"> & {
11916
11918
  rateLimitWindows: string | null;
11917
11919
  providerAccount: string | null;
11920
+ spendCap: string | null;
11918
11921
  };
11919
11922
 
11920
11923
  function parseRateLimitWindowsJson(value: string | null | undefined): RateLimitWindowTelemetry {
@@ -11935,6 +11938,7 @@ function rowToApiKeyStatus(row: ApiKeyStatusRow): ApiKeyStatus {
11935
11938
  ...row,
11936
11939
  rateLimitWindows: parseRateLimitWindowsJson(row.rateLimitWindows),
11937
11940
  providerAccount: parseProviderAccount(row.providerAccount),
11941
+ spendCap: row.spendCap ? (JSON.parse(row.spendCap) as SpendCap) : null,
11938
11942
  };
11939
11943
  }
11940
11944
 
@@ -11947,6 +11951,8 @@ export interface AvailableKeyIndicesResult {
11947
11951
  earliestModelResetAt: string | null;
11948
11952
  /** Indices excluded because the key's subscription plan cannot run the model family. */
11949
11953
  seatBlockedIndices: number[];
11954
+ /** Rate-limited indices whose limit is a provider spend cap: no retry helps before it resets. */
11955
+ spendCappedIndices: number[];
11950
11956
  authFailureFence: number; // highest `authFailureSeq` among these rows
11951
11957
  }
11952
11958
 
@@ -11991,7 +11997,7 @@ export async function getAvailableKeyIndices(
11991
11997
  // Auto-clear expired rate limits. Never an auth bench: only `clearAuthBench` lifts it.
11992
11998
  await client.run(
11993
11999
  `UPDATE api_key_status
11994
- SET status = 'available', rateLimitedUntil = NULL, updatedAt = ?
12000
+ SET status = 'available', rateLimitedUntil = NULL, spendCap = NULL, updatedAt = ?
11995
12001
  WHERE ${rowFilter}
11996
12002
  AND status = 'rate_limited' AND rateLimitedUntil <= ? AND consecutiveAuthFailures < ?`,
11997
12003
  [now, ...rowParams, now, CODEX_AUTH_FAILURE_BENCH_THRESHOLD],
@@ -12007,8 +12013,9 @@ export async function getAvailableKeyIndices(
12007
12013
  plan: string | null;
12008
12014
  authFailureSeq: number;
12009
12015
  lastValidationFailedAt: string | null;
12016
+ spendCap: string | null;
12010
12017
  }>(
12011
- `SELECT keyIndex, keySuffix, scope, scopeId, status, rateLimitWindows, plan, authFailureSeq, lastValidationFailedAt FROM api_key_status
12018
+ `SELECT keyIndex, keySuffix, scope, scopeId, status, rateLimitWindows, plan, authFailureSeq, lastValidationFailedAt, spendCap FROM api_key_status
12012
12019
  WHERE ${rowFilter}`,
12013
12020
  rowParams,
12014
12021
  );
@@ -12026,6 +12033,9 @@ export async function getAvailableKeyIndices(
12026
12033
  const blockedIndices = new Set(
12027
12034
  rows.filter((r) => r.status === "rate_limited").flatMap(positionsOf),
12028
12035
  );
12036
+ const spendCappedIndices = [
12037
+ ...new Set(rows.filter((r) => r.status === "rate_limited" && r.spendCap).flatMap(positionsOf)),
12038
+ ];
12029
12039
  const rejectedIndices = [
12030
12040
  ...new Set(rows.filter((row) => row.lastValidationFailedAt !== null).flatMap(positionsOf)),
12031
12041
  ];
@@ -12081,6 +12091,7 @@ export async function getAvailableKeyIndices(
12081
12091
  rejectedIndices,
12082
12092
  modelBlockedIndices,
12083
12093
  seatBlockedIndices,
12094
+ spendCappedIndices,
12084
12095
  earliestModelResetAt:
12085
12096
  earliestModelResetsAtSec !== undefined
12086
12097
  ? new Date(earliestModelResetsAtSec * 1000).toISOString()
@@ -12198,7 +12209,10 @@ export async function setApiKeyPlan(
12198
12209
  return result.changes > 0;
12199
12210
  }
12200
12211
 
12201
- /** Mark a key as rate-limited until a retry-after timestamp; never shortens an auth-failure bench. */
12212
+ /**
12213
+ * Mark a key as rate-limited until a retry-after timestamp; never shortens an auth-failure bench.
12214
+ * `spendCap` records a provider spend limit behind it; an ordinary rate limit clears it.
12215
+ */
12202
12216
  export async function markKeyRateLimited(
12203
12217
  keyType: string,
12204
12218
  keySuffix: string,
@@ -12206,22 +12220,35 @@ export async function markKeyRateLimited(
12206
12220
  rateLimitedUntil: string,
12207
12221
  scope = "global",
12208
12222
  scopeId: string | null = null,
12223
+ spendCap: SpendCap | null = null,
12209
12224
  ): Promise<void> {
12210
12225
  const now = new Date().toISOString();
12211
12226
  const effectiveScopeId = scopeId ?? "";
12212
12227
  const provider = deriveProviderFromKeyType(keyType);
12213
12228
  await getDbClient().run(
12214
- `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, status, rateLimitedUntil, lastRateLimitAt, rateLimitCount, provider, updatedAt)
12215
- VALUES (?, ?, ?, ?, ?, 'rate_limited', ?, ?, 1, ?, ?)
12229
+ `INSERT INTO api_key_status (keyType, keySuffix, keyIndex, scope, scopeId, status, rateLimitedUntil, lastRateLimitAt, rateLimitCount, provider, updatedAt, spendCap)
12230
+ VALUES (?, ?, ?, ?, ?, 'rate_limited', ?, ?, 1, ?, ?, ?)
12216
12231
  ON CONFLICT(keyType, keySuffix, scope, scopeId)
12217
12232
  DO UPDATE SET
12218
12233
  status = 'rate_limited',
12219
12234
  rateLimitedUntil = CASE WHEN status = 'rate_limited' AND consecutiveAuthFailures >= ${CODEX_AUTH_FAILURE_BENCH_THRESHOLD} THEN MAX(COALESCE(rateLimitedUntil, ''), excluded.rateLimitedUntil) ELSE excluded.rateLimitedUntil END,
12235
+ spendCap = excluded.spendCap,
12220
12236
  lastRateLimitAt = excluded.lastRateLimitAt,
12221
12237
  rateLimitCount = rateLimitCount + 1,
12222
12238
  keyIndex = excluded.keyIndex,
12223
12239
  updatedAt = excluded.updatedAt`,
12224
- [keyType, keySuffix, keyIndex, scope, effectiveScopeId, rateLimitedUntil, now, provider, now],
12240
+ [
12241
+ keyType,
12242
+ keySuffix,
12243
+ keyIndex,
12244
+ scope,
12245
+ effectiveScopeId,
12246
+ rateLimitedUntil,
12247
+ now,
12248
+ provider,
12249
+ now,
12250
+ spendCap ? JSON.stringify(spendCap) : null,
12251
+ ],
12225
12252
  );
12226
12253
  }
12227
12254
 
@@ -12388,7 +12415,7 @@ export async function clearKeyRateLimit(
12388
12415
  // The key's rows in every scope: `getAvailableKeyIndices` reads them all by suffix.
12389
12416
  const result = await tx.run(
12390
12417
  `UPDATE api_key_status
12391
- SET status = 'available', rateLimitedUntil = NULL, updatedAt = ?
12418
+ SET status = 'available', rateLimitedUntil = NULL, spendCap = NULL, updatedAt = ?
12392
12419
  WHERE keyType = ? AND keySuffix = ?
12393
12420
  AND status = 'rate_limited' AND ((? AND authFailureSeq <= ?) OR consecutiveAuthFailures < ?)`,
12394
12421
  [
@@ -12404,7 +12431,8 @@ export async function clearKeyRateLimit(
12404
12431
  if (!clearAuthBench) return cleared;
12405
12432
  const lifted = await tx.query<{ keySuffix: string }>(
12406
12433
  `UPDATE api_key_status SET consecutiveAuthFailures = 0, updatedAt = ?1,
12407
- status = CASE WHEN keySuffix = ?2 THEN status ELSE 'available' END, rateLimitedUntil = CASE WHEN keySuffix = ?2 THEN rateLimitedUntil END
12434
+ status = CASE WHEN keySuffix = ?2 THEN status ELSE 'available' END, rateLimitedUntil = CASE WHEN keySuffix = ?2 THEN rateLimitedUntil END,
12435
+ spendCap = CASE WHEN keySuffix = ?2 THEN spendCap END
12408
12436
  WHERE keyType = ?3 AND (consecutiveAuthFailures > 0 OR status = 'rate_limited')
12409
12437
  AND ((keySuffix = ?2 AND authFailureSeq <= ?7)
12410
12438
  OR (keySuffix != ?2 AND keyIndex = ?6 AND scope = ?4 AND scopeId = ?5)) RETURNING keySuffix`,
@@ -3,6 +3,7 @@ import { McpHttpClient, type McpTool, type McpToolCallEnvelope } from "@/mcp-cli
3
3
  import { ensureMcpToken } from "@/oauth/ensure-mcp-token";
4
4
  import { assertUrlSafe, publicEndpointSsrfOptions } from "@/oauth/mcp-wrapper";
5
5
  import type { McpServer } from "@/types";
6
+ import { createSsrfGuardedFetch } from "@/utils/egress-guard";
6
7
  import { registerVolatileSecret } from "@/utils/secret-scrubber";
7
8
 
8
9
  const MCP_PROXY_TIMEOUT_MS = 30_000;
@@ -102,16 +103,16 @@ async function createMcpServerClient(
102
103
  }
103
104
  if (!server.url) throw new Error("MCP server URL is required");
104
105
 
105
- // Validate when resolving the persisted URL, and again in McpHttpClient
106
- // immediately before every request to defend against a changed record or DNS
107
- // rebinding between the initial validation and an MCP tool call.
106
+ // Validate when resolving the persisted URL. Every request then goes through
107
+ // the guarded fetch, which re-checks the URL, resolves the name and connects
108
+ // only to a checked address, and re-checks each redirect hop.
108
109
  assertUrlSafe(server.url, publicEndpointSsrfOptions());
109
110
 
110
111
  const client = new McpHttpClient(server.url, "", "", undefined, {
111
112
  clientInfo: { name: "agent-swarm-script-mcp-proxy", version: "1.0.0" },
112
113
  omitEmptyAuthHeaders: true,
113
114
  timeoutMs: context.timeoutMs ?? MCP_PROXY_TIMEOUT_MS,
114
- validateUrl: (url) => assertUrlSafe(url, publicEndpointSsrfOptions()),
115
+ fetch: createSsrfGuardedFetch(publicEndpointSsrfOptions()),
115
116
  });
116
117
  client.useRawUrl = true;
117
118
  client.customHeaders = await resolveMcpHeaders(server, context);
@@ -0,0 +1,5 @@
1
+ -- Spend cap behind a key's current rate limit: a JSON object
2
+ -- `{limitUsd, spendUsd, resetsAt}` when the provider refused the key because it
3
+ -- hit its spend limit (OpenRouter 403 key limit, 402 insufficient credits).
4
+ -- NULL for an ordinary rate limit. Read only while `status = 'rate_limited'`.
5
+ ALTER TABLE api_key_status ADD COLUMN spendCap TEXT;
@@ -19,3 +19,29 @@ export function validateRecurringTiming(merged: MergedScheduleTiming): Recurring
19
19
  }
20
20
  return null;
21
21
  }
22
+
23
+ /** The fields that pick what a schedule runs. A fire runs as the schedule's creator. */
24
+ export const SCHEDULE_TARGET_FIELDS = [
25
+ "targetType",
26
+ "taskTemplate",
27
+ "workflowId",
28
+ "scriptName",
29
+ "scriptArgs",
30
+ "params",
31
+ ] as const;
32
+
33
+ type ScheduleTargetFields = Partial<Record<(typeof SCHEDULE_TARGET_FIELDS)[number], unknown>>;
34
+
35
+ /**
36
+ * True when `patch` changes any target field of `existing`. A restated value is
37
+ * not a change, so a full-form save that keeps the target passes.
38
+ */
39
+ export function changesScheduleTarget(
40
+ existing: ScheduleTargetFields,
41
+ patch: ScheduleTargetFields,
42
+ ): boolean {
43
+ return SCHEDULE_TARGET_FIELDS.some(
44
+ (field) =>
45
+ patch[field] !== undefined && !Bun.deepEquals(patch[field] ?? null, existing[field] ?? null),
46
+ );
47
+ }
@@ -724,6 +724,10 @@ const VALIDATED_KEYS: Record<string, ConfigValidator> = {
724
724
  APPS_JSON_COLUMN_MAX_BYTES_BOUNDS.min,
725
725
  APPS_JSON_COLUMN_MAX_BYTES_BOUNDS.max,
726
726
  ),
727
+ // Worker worktree reaper (src/commands/worktree-reaper.ts clamps to the same ranges).
728
+ ...enumValidator("WORKTREE_REAPER_MODE", ["off", "dry-run", "on"]),
729
+ ...boundedIntegerValidators(["WORKTREE_TTL_HOURS"], 1, 2160),
730
+ ...boundedIntegerValidators(["WORKTREE_SWEEP_INTERVAL_MINUTES"], 5, 1440),
727
731
  ...boundedIntegerValidators(
728
732
  ["CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS"],
729
733
  CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS_BOUNDS.min,
@@ -1,4 +1,4 @@
1
- import type { RateLimitWindowTelemetry } from "../utils/error-tracker";
1
+ import type { RateLimitWindowTelemetry, SpendCap } from "../utils/error-tracker";
2
2
  import { modelFamilyOf } from "../utils/model-rate-limit-windows";
3
3
  import type {
4
4
  ProviderAccountTelemetry,
@@ -15,6 +15,7 @@ async function reportKeyRateLimit(
15
15
  keySuffix: string,
16
16
  keyIndex: number,
17
17
  rateLimitedUntil: string,
18
+ spendCap?: SpendCap,
18
19
  ): Promise<void> {
19
20
  try {
20
21
  const response = await fetch(`${apiUrl}/api/keys/report-rate-limit`, {
@@ -28,6 +29,7 @@ async function reportKeyRateLimit(
28
29
  keySuffix,
29
30
  keyIndex,
30
31
  rateLimitedUntil,
32
+ ...(spendCap ? { spendCap } : {}),
31
33
  }),
32
34
  // Awaited on a key-wide outcome: a hung API must not hold the task open.
33
35
  signal: AbortSignal.timeout(10_000),
@@ -39,7 +41,7 @@ async function reportKeyRateLimit(
39
41
  return;
40
42
  }
41
43
  console.log(
42
- `[credentials] Reported key ...${keySuffix} as rate-limited until ${rateLimitedUntil}`,
44
+ `[credentials] Reported key ...${keySuffix} as ${spendCap ? "spend-capped" : "rate-limited"} until ${rateLimitedUntil}`,
43
45
  );
44
46
  } catch (err) {
45
47
  console.warn(
@@ -181,6 +183,7 @@ export async function reportCredentialOutcomeThenFinish(
181
183
  credentialInfo.keySuffix,
182
184
  credentialInfo.keyIndex,
183
185
  keyRateLimitedUntil,
186
+ outcome.kind === "key" ? outcome.spendCap : undefined,
184
187
  ).catch(() => {});
185
188
  // `finish` may resume the task on another key of the pool: the bench
186
189
  // lands first, so the resume's claim cannot draw this key again.
@@ -2,4 +2,4 @@
2
2
  * agent-fs image tag bundled by `agent-swarm onboard --yes`.
3
3
  * `bun run bump:agent-fs` rewrites it together with the other pins.
4
4
  */
5
- export const AGENT_FS_VERSION = "0.18.26";
5
+ export const AGENT_FS_VERSION = "0.18.27";
@@ -839,6 +839,25 @@ export async function reportAcpStatus(
839
839
  }
840
840
  }
841
841
 
842
+ /**
843
+ * The model the task itself selected (a pin, a tier or a task profile), for
844
+ * `buildLatestModelReport({ taskModel })`. Claim resolution also returns the
845
+ * agent's own default profile (`profile:agent-default`); that model comes from the
846
+ * agent's settings, not the task, so it must not report as task-selected.
847
+ */
848
+ export function taskSelectedModelForReport(opts: {
849
+ /** Server claim-time resolution (`task.resolvedModel`). */
850
+ resolvedModel?: string;
851
+ modelSource?: string;
852
+ /** Local resolution from the task's own pin/tier. */
853
+ localModel?: string;
854
+ }): string | undefined {
855
+ if (opts.resolvedModel) {
856
+ return opts.modelSource === "profile:agent-default" ? undefined : opts.resolvedModel;
857
+ }
858
+ return opts.localModel || undefined;
859
+ }
860
+
842
861
  export function buildLatestModelReport(opts: {
843
862
  model: string;
844
863
  taskModel?: string;