@desplega.ai/agent-swarm 2.8.2 → 2.8.3

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 (258) hide show
  1. package/dist/acp-adapter-xq6s2z6t.js +14 -0
  2. package/dist/{actions-kxek041g.js → actions-ewz7bp4g.js} +20 -19
  3. package/dist/{amp-adapter-ce7jjke4.js → amp-adapter-f25tqhnf.js} +3 -3
  4. package/dist/{app-v6zz8yh0.js → app-mkptw0k7.js} +4 -4
  5. package/dist/{assistant-m0sw9xx2.js → assistant-c47rfe77.js} +23 -22
  6. package/dist/{boot-args-schema-66bk37wv.js → boot-args-schema-4vb0xsat.js} +1 -1
  7. package/dist/{boot-reembed-edjpwsc1.js → boot-reembed-1ghy2sab.js} +1 -1
  8. package/dist/{boot-reembed-y27n09tz.js → boot-reembed-htr73hbs.js} +1 -1
  9. package/dist/{boot-scrub-sweep-1xc35965.js → boot-scrub-sweep-yrytg42z.js} +4 -4
  10. package/dist/{boot-seeds-7hjj91qj.js → boot-seeds-n2b3dx4e.js} +4 -4
  11. package/dist/{boxd-ent8ch04.js → boxd-jmfqgkqa.js} +1 -1
  12. package/dist/{claude-adapter-stw7jdcf.js → claude-adapter-r33pqnzx.js} +8 -9
  13. package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-hddmxjyj.js} +4 -4
  14. package/dist/{claude-managed-setup-y6z2perp.js → claude-managed-setup-hfvry1bd.js} +5 -5
  15. package/dist/{claude-sdk-session-vvya8wqk.js → claude-sdk-session-0hamqzc7.js} +10 -11
  16. package/dist/{cli-v1dv1r37.js → cli-0bcgyj5b.js} +74 -3
  17. package/dist/{cli-t2tma8gb.js → cli-0vksaxvr.js} +2 -2
  18. package/dist/{cli-mrt48bx7.js → cli-15204js0.js} +1 -1
  19. package/dist/{cli-8aes17e4.js → cli-1m96dc36.js} +3 -3
  20. package/dist/{cli-2r0jcc3k.js → cli-2d0cghfn.js} +1 -1
  21. package/dist/{cli-0cq8y6m7.js → cli-4ax9mvvg.js} +4 -4
  22. package/dist/{cli-tekytdq9.js → cli-4dpkjc2e.js} +6 -6
  23. package/dist/{cli-x1wa213s.js → cli-4e1hfbpq.js} +5 -5
  24. package/dist/{cli-7349va39.js → cli-500c09j9.js} +921 -431
  25. package/dist/{cli-9mb2q6pb.js → cli-54qr8mcd.js} +2 -2
  26. package/dist/{cli-m88rpzkh.js → cli-5a7szzfh.js} +2 -2
  27. package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
  28. package/dist/{cli-vj75tyaw.js → cli-6yygkr0w.js} +7 -7
  29. package/dist/{cli-kjtwrhea.js → cli-7c5tgqhf.js} +5 -5
  30. package/dist/{cli-2gxeg5gr.js → cli-8476gtwf.js} +1 -1
  31. package/dist/{cli-zh9rsbqf.js → cli-922z7gwm.js} +3 -3
  32. package/dist/{cli-jrzkw01m.js → cli-93t5s4zq.js} +2 -2
  33. package/dist/{cli-gyt3zydq.js → cli-9zmb7ptc.js} +9 -9
  34. package/dist/{cli-dzpc6en0.js → cli-am1ptset.js} +2 -2
  35. package/dist/{cli-w401b9tq.js → cli-awwptga4.js} +1 -1
  36. package/dist/{cli-26ctbcdp.js → cli-bhsfbmk8.js} +3 -3
  37. package/dist/{cli-mxn1qvbn.js → cli-bj6qhgte.js} +14 -32
  38. package/dist/{cli-g70vxtjh.js → cli-c0xjnr8z.js} +2 -2
  39. package/dist/{cli-jdknh18m.js → cli-c3ng0mb4.js} +13 -13
  40. package/dist/{cli-f4e8r23x.js → cli-c71n3bxq.js} +11 -6
  41. package/dist/{cli-6rc5frdm.js → cli-crpf163n.js} +25 -18
  42. package/dist/{cli-1qkz151v.js → cli-dpsfwh7n.js} +13 -21
  43. package/dist/{cli-xzm9vcfg.js → cli-dtdht77h.js} +2 -2
  44. package/dist/{cli-a0z912j7.js → cli-e2w34h6z.js} +137 -62
  45. package/dist/{cli-eddnyg3t.js → cli-emekyyhr.js} +1 -1
  46. package/dist/{cli-d84byzn8.js → cli-f1kwb5fc.js} +109 -33
  47. package/dist/{cli-0jzra9ad.js → cli-gn9y6fn7.js} +2 -2
  48. package/dist/{cli-vdektqgf.js → cli-gpz1d0t2.js} +4 -4
  49. package/dist/{cli-rcecc3yq.js → cli-h9yy18gy.js} +84 -36
  50. package/dist/{cli-m5akxq8q.js → cli-j8cjdzan.js} +1 -1
  51. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  52. package/dist/{cli-b98a65ed.js → cli-k2rw11py.js} +3 -3
  53. package/dist/{cli-3e875j5p.js → cli-k96cecs7.js} +276 -47
  54. package/dist/{cli-3vjhs18n.js → cli-kd56bmk4.js} +1 -1
  55. package/dist/{cli-3sy2xags.js → cli-kmemts3w.js} +12 -12
  56. package/dist/{cli-f6bahpn5.js → cli-knva3nmx.js} +2 -2
  57. package/dist/{cli-959kp5h2.js → cli-kw44j53p.js} +13 -13
  58. package/dist/{cli-bsywb58a.js → cli-mdpbjnzq.js} +10 -10
  59. package/dist/{cli-2kvhc7x8.js → cli-me0r8gzr.js} +35 -76
  60. package/dist/{cli-4vzgeta4.js → cli-mwwmka77.js} +14 -14
  61. package/dist/{cli-q24n86d2.js → cli-n5t077me.js} +2 -2
  62. package/dist/{cli-rvhdmjvt.js → cli-nx2n3z6p.js} +1 -1
  63. package/dist/{cli-28fq781p.js → cli-pe4d96rb.js} +1 -1
  64. package/dist/{cli-3rkdne1h.js → cli-pxwtcgcp.js} +2 -2
  65. package/dist/{cli-n6vtrcht.js → cli-qmqt520k.js} +2 -2
  66. package/dist/{cli-pchypa1s.js → cli-qps8je6j.js} +17 -2
  67. package/dist/{cli-97ae65rz.js → cli-rjvsf9qa.js} +5 -5
  68. package/dist/{cli-e1p3n5gq.js → cli-rqfvkx5t.js} +6 -6
  69. package/dist/{cli-3vmb0n58.js → cli-s7zz734a.js} +1 -1
  70. package/dist/{cli-rmzsadkf.js → cli-s8p8hhty.js} +2 -2
  71. package/dist/{cli-j24zbska.js → cli-sdvcrq5x.js} +5 -5
  72. package/dist/{cli-5y340nzn.js → cli-sg27rk2t.js} +5 -5
  73. package/dist/{cli-d6521kb5.js → cli-skmhsnqh.js} +1 -1
  74. package/dist/{cli-5mrq3ake.js → cli-t4dv07kr.js} +1 -1
  75. package/dist/{cli-z1w943va.js → cli-t5ys4ebm.js} +3 -3
  76. package/dist/{cli-f4r3g076.js → cli-tas6ckky.js} +2 -2
  77. package/dist/{cli-1pz0330a.js → cli-tf79ryyy.js} +1 -1
  78. package/dist/{cli-kc7v1nfv.js → cli-tnzebztn.js} +1 -1
  79. package/dist/{cli-pfs8adn4.js → cli-vx421edw.js} +3 -3
  80. package/dist/{cli-kchjb7qy.js → cli-x3ex5bqf.js} +1 -1
  81. package/dist/cli-yss07azk.js +142 -0
  82. package/dist/{cli-fwy8kfd6.js → cli-z8cvws4c.js} +98 -16
  83. package/dist/{cli-g5mtmf6t.js → cli-zdaypkq9.js} +146 -52
  84. package/dist/{cli-fpjmegdb.js → cli-zeaehgyd.js} +2 -2
  85. package/dist/{cli-837vfs2x.js → cli-ztq5z4e1.js} +4 -4
  86. package/dist/cli.js +20 -20
  87. package/dist/{codex-adapter-zerf5qsp.js → codex-adapter-2brxx5ta.js} +7 -8
  88. package/dist/{codex-hook-30gyhzxe.js → codex-hook-c930c3ea.js} +1 -1
  89. package/dist/{codex-login-bcda78ge.js → codex-login-cbrs1h5w.js} +1 -1
  90. package/dist/{codex-session-runner-89s304py.js → codex-session-runner-y9anfj0r.js} +8 -9
  91. package/dist/{commands-jeh1b51j.js → commands-wn9q06qr.js} +3 -3
  92. package/dist/{controller-mctfbrse.js → controller-fw608czd.js} +4 -4
  93. package/dist/{controllers-connect-nxa1ddwn.js → controllers-connect-63j5rdcm.js} +20 -20
  94. package/dist/{cursor-adapter-qj8vehv6.js → cursor-adapter-6mb9jme8.js} +2 -2
  95. package/dist/{db-2dvay0es.js → db-0m6v5tq4.js} +3 -3
  96. package/dist/{db-b36qn6k3.js → db-y4wfrzbm.js} +4 -2
  97. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-r0yx3gv8.js} +1 -1
  98. package/dist/{dispatcher-gndbta01.js → dispatcher-9tq2zzdj.js} +17 -17
  99. package/dist/{docker-866qpzt9.js → docker-j75atvpt.js} +2 -2
  100. package/dist/{dsh-adapter-f75sz821.js → dsh-adapter-t09sv4tq.js} +2 -2
  101. package/dist/{e2b-jbm7mj93.js → e2b-7s9dscap.js} +2 -2
  102. package/dist/{e2b-3gpc2n3w.js → e2b-a7vzs2vj.js} +2 -2
  103. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-fbwvmwhe.js} +1 -1
  104. package/dist/{embedding-space-4p05vb2x.js → embedding-space-wh8de1t9.js} +6 -6
  105. package/dist/{embeddings-m6768mgh.js → embeddings-3hpbdtjr.js} +1 -1
  106. package/dist/{event-bus-e66gh7cc.js → event-bus-tr6h3gv8.js} +1 -1
  107. package/dist/{execute-b3mrb1mv.js → execute-4bdf8sdy.js} +1 -1
  108. package/dist/{external-channel-gjv3jne3.js → external-channel-ts2fwqh0.js} +2 -2
  109. package/dist/fx-adapter-1rnxnf56.js +17 -0
  110. package/dist/grok-adapter-efhmf1r8.js +17 -0
  111. package/dist/handlers-anrr3py9.js +32 -0
  112. package/dist/{heartbeat-a1tv60gt.js → heartbeat-2ze5fzpc.js} +20 -20
  113. package/dist/{hook-8h5dzcgq.js → hook-ca54yd4s.js} +5 -5
  114. package/dist/{hook-cyaps9ba.js → hook-gaehe2w5.js} +7 -7
  115. package/dist/{http-t15mhbd9.js → http-jfg8t2yk.js} +3861 -1798
  116. package/dist/{index-tvfafeyy.js → index-3gv6sc4z.js} +1 -1
  117. package/dist/{index-qav6455f.js → index-3yvzbhxd.js} +97 -22
  118. package/dist/index-8w2aznds.js +33 -0
  119. package/dist/{index-w1zqf680.js → index-csgrxedz.js} +1 -1
  120. package/dist/index-qnjvr362.js +37 -0
  121. package/dist/index-yzxd3sn9.js +32 -0
  122. package/dist/{keepalive-91s7hzrb.js → keepalive-k2a3qe73.js} +4 -4
  123. package/dist/lead-zhxqbfdv.js +69 -0
  124. package/dist/{maintenance-7pjmy5xy.js → maintenance-gb5sd5nc.js} +1 -1
  125. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  126. package/dist/{oauth-refresh-sweep-rzqfm94j.js → oauth-refresh-sweep-y7rm6bkb.js} +3 -3
  127. package/dist/{onboard-74st7pag.js → onboard-jmc5qerv.js} +3 -3
  128. package/dist/{opencode-adapter-arn7gm8q.js → opencode-adapter-7eade9ev.js} +6 -7
  129. package/dist/{otel-impl-rnzey8cb.js → otel-impl-8j1xhxqd.js} +2 -2
  130. package/dist/{pi-mono-adapter-6mkwq64n.js → pi-mono-adapter-yqmaf32x.js} +13 -13
  131. package/dist/{pricing-refresh-ha21jhk7.js → pricing-refresh-1nj722h6.js} +2 -2
  132. package/dist/{rbac-roles-wqhma4dr.js → rbac-roles-b1mtr6dr.js} +3 -3
  133. package/dist/{rbac-roles-59dxachk.js → rbac-roles-n1f3frk1.js} +2 -2
  134. package/dist/{render-v2-14kpzx12.js → render-v2-1gfpd8rj.js} +4 -4
  135. package/dist/{resume-gsa5fb5f.js → resume-w1s1eh5v.js} +7 -7
  136. package/dist/{runtime-1hv06jsn.js → runtime-84g5egsc.js} +1 -1
  137. package/dist/{session-access-skm7bnp6.js → session-access-y6z1txk4.js} +4 -4
  138. package/dist/{session-source-backfill-pbqzbncv.js → session-source-backfill-gxxwfh12.js} +3 -3
  139. package/dist/{setup-5yermsem.js → setup-r91gstyk.js} +1 -1
  140. package/dist/{virtual-modules-gazyapte.js → virtual-modules-cgnj6kme.js} +3 -3
  141. package/dist/{work-objects-xj0ck0w4.js → work-objects-qcxzg61c.js} +20 -20
  142. package/dist/worker-7j2907g6.js +69 -0
  143. package/dist/{worker-follow-up-911xc0b8.js → worker-follow-up-y2d2h7km.js} +17 -17
  144. package/dist/{x-2fyrt5pp.js → x-qhxq2ama.js} +2 -2
  145. package/openapi.json +1214 -108
  146. package/package.json +3 -3
  147. package/src/be/db/tasks/read.ts +33 -0
  148. package/src/be/db.ts +32 -7
  149. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  150. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  151. package/src/be/migrations/293_savings_component_links.sql +58 -0
  152. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  153. package/src/be/model-profile-check.ts +10 -2
  154. package/src/be/savings/compute.ts +511 -16
  155. package/src/be/savings/model.ts +282 -14
  156. package/src/be/savings/read.ts +1500 -0
  157. package/src/be/savings/rollup.ts +571 -0
  158. package/src/be/scripts/run-credential.ts +15 -3
  159. package/src/be/scripts/typecheck.ts +86 -4
  160. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  161. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  162. package/src/be/swarm-config-guard.ts +8 -0
  163. package/src/be/users.ts +29 -2
  164. package/src/commands/runner.ts +159 -41
  165. package/src/extensions/contract-types.generated.ts +1 -1
  166. package/src/http/index.ts +8 -1
  167. package/src/http/poll.ts +14 -1
  168. package/src/http/requested-by.ts +97 -1
  169. package/src/http/savings.ts +676 -190
  170. package/src/http/scripts.ts +26 -15
  171. package/src/http/tasks.ts +43 -5
  172. package/src/prompts/session-templates.ts +80 -3
  173. package/src/providers/acp-targets.ts +1 -1
  174. package/src/providers/amp-adapter.ts +1 -1
  175. package/src/providers/claude-adapter.ts +0 -20
  176. package/src/providers/claude-flag-settings.ts +12 -10
  177. package/src/providers/codex-adapter.ts +9 -34
  178. package/src/providers/opencode-adapter.ts +34 -12
  179. package/src/scheduler/scheduler.ts +20 -14
  180. package/src/scripts-runtime/ctx.ts +1 -1
  181. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  182. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  183. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  184. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  185. package/src/scripts-runtime/stdlib/index.ts +3 -1
  186. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  187. package/src/scripts-runtime/swarm-sdk.ts +186 -17
  188. package/src/scripts-runtime/types/stdlib.d.ts +86 -4
  189. package/src/scripts-runtime/types/swarm-extension.d.ts +26 -0
  190. package/src/scripts-runtime/types/swarm-sdk.d.ts +60 -2
  191. package/src/slack/actions.ts +1 -0
  192. package/src/slack/assistant.ts +2 -0
  193. package/src/slack/enrich.ts +144 -50
  194. package/src/slack/handlers.ts +37 -95
  195. package/src/slack/templates.ts +9 -0
  196. package/src/slack/thread-buffer.ts +45 -71
  197. package/src/slack/thread-participants.ts +187 -0
  198. package/src/tests/base-prompt.test.ts +5 -4
  199. package/src/tests/claude-adapter-binary.test.ts +7 -1
  200. package/src/tests/claude-adapter.test.ts +10 -64
  201. package/src/tests/claude-flag-settings.test.ts +15 -11
  202. package/src/tests/claude-hook-credentials.test.ts +0 -1
  203. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  204. package/src/tests/codex-adapter.test.ts +17 -78
  205. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  206. package/src/tests/db-task-read-contract.test.ts +2 -0
  207. package/src/tests/db-task-write-contract.test.ts +1 -0
  208. package/src/tests/docs-index-footprint.test.js +3 -3
  209. package/src/tests/dreaming-learnings.test.ts +104 -0
  210. package/src/tests/extensions-pre-task.test.ts +4 -2
  211. package/src/tests/fetch-resolved-env.test.ts +47 -1
  212. package/src/tests/opencode-adapter.test.ts +53 -6
  213. package/src/tests/prompt-template-session.test.ts +17 -1
  214. package/src/tests/runner-requester-profile.test.ts +139 -1
  215. package/src/tests/savings-compound.test.ts +774 -0
  216. package/src/tests/savings-compute.test.ts +7 -198
  217. package/src/tests/savings-fleet-latency.test.ts +143 -0
  218. package/src/tests/savings-fleet-read.test.ts +195 -0
  219. package/src/tests/savings-fleet-scale.test.ts +222 -0
  220. package/src/tests/savings-model.test.ts +212 -0
  221. package/src/tests/savings-read.test.ts +367 -0
  222. package/src/tests/savings-rollup.test.ts +766 -0
  223. package/src/tests/savings-scripts.test.ts +611 -0
  224. package/src/tests/script-connections.test.ts +2 -0
  225. package/src/tests/script-executor-conformance.test.ts +444 -0
  226. package/src/tests/scripts-http.test.ts +55 -0
  227. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  228. package/src/tests/secret-rules.test.ts +124 -1
  229. package/src/tests/secret-scrubber.test.ts +1 -1
  230. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  231. package/src/tests/slack-identity-resolution.test.ts +23 -0
  232. package/src/tests/slack-inbound-files.test.ts +2 -1
  233. package/src/tests/slack-thread-participants.test.ts +429 -0
  234. package/src/tests/tool-annotations.test.ts +30 -0
  235. package/src/types.ts +31 -0
  236. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  237. package/src/utils/mcp-server-fetcher.ts +13 -5
  238. package/src/utils/request-auth-context.ts +24 -0
  239. package/src/utils/secret-rules.generated.ts +1 -1
  240. package/src/utils/secret-scrubber.ts +154 -29
  241. package/src/workflows/executors/swarm-script.ts +23 -19
  242. package/templates/skills/swarm-scripts/SKILL.md +5 -4
  243. package/templates/skills/swarm-scripts/content.md +5 -4
  244. package/templates/skills/work-on-task/SKILL.md +1 -1
  245. package/templates/skills/work-on-task/content.md +1 -1
  246. package/templates/workflows/dreaming/content.md +1 -1
  247. package/dist/acp-adapter-fqzkxyra.js +0 -15
  248. package/dist/cli-4bd1rck6.js +0 -4
  249. package/dist/cli-xf3qw745.js +0 -104
  250. package/dist/fx-adapter-rpsgb1tw.js +0 -18
  251. package/dist/grok-adapter-n2m3zjg1.js +0 -18
  252. package/dist/handlers-nv8edn19.js +0 -32
  253. package/dist/index-ksmyd6kc.js +0 -37
  254. package/dist/index-rjnrje98.js +0 -32
  255. package/dist/index-tv3413wy.js +0 -33
  256. package/dist/lead-3hmddvrm.js +0 -70
  257. package/dist/worker-qgg0m2gw.js +0 -70
  258. package/src/providers/ctx-mode-env.ts +0 -10
@@ -483,12 +483,70 @@ export interface SwarmSdk {
483
483
  }): Promise<unknown>;
484
484
  }
485
485
 
486
+ export interface RetryOptions {
487
+ /** Retries after the first call. Default 3, so at most 4 calls. */
488
+ retries?: number;
489
+ /** First backoff delay in ms. Doubles on each retry, with jitter. Default 200. */
490
+ minDelayMs?: number;
491
+ /** Cap on a single wait, including a Retry-After wait. Default 5000. */
492
+ maxDelayMs?: number;
493
+ /** Total time across all calls and waits, in ms. Default 30000. */
494
+ budgetMs?: number;
495
+ /**
496
+ * Decides whether to retry: gets the thrown error or the returned value and
497
+ * the 1-based attempt. Default: retry any throw, plus a failed fetch Response,
498
+ * ctx.api raw result or ctx.swarm envelope with status 429, 502, 503 or 504.
499
+ */
500
+ retryOn?: (errorOrResult: unknown, attempt: number) => boolean | Promise<boolean>;
501
+ /** Stops the retries: once it aborts, the wait ends and retry rejects with its reason. */
502
+ signal?: AbortSignal;
503
+ }
504
+
505
+ export interface FetchRetryOptions extends RetryOptions {
506
+ /**
507
+ * Sends an Idempotency-Key header, the same value on every attempt: true
508
+ * generates a UUID per call, a string is used as is. A POST or PATCH with
509
+ * the header also retries 502/503/504 and network errors. It only prevents
510
+ * a duplicate when the server dedupes by the key.
511
+ */
512
+ idempotencyKey?: boolean | string;
513
+ }
514
+
515
+ /**
516
+ * ctx.stdlib.fetch options. Default retries: 429 on every method (Retry-After
517
+ * honoured); 502/503/504 and network errors on GET, HEAD, OPTIONS, PUT, DELETE,
518
+ * or any request with an Idempotency-Key. A stream body gets one attempt.
519
+ */
520
+ export type FetchOptions = RequestInit & {
521
+ /** false: one attempt. true or omitted: the defaults above. An object tunes them. */
522
+ retry?: boolean | FetchRetryOptions;
523
+ /** @deprecated Use retry: { retries }. Total attempts, so retries: 1 is one attempt. */
524
+ retries?: number;
525
+ /** Per-attempt timeout in ms. Default 30000. */
526
+ timeoutMs?: number;
527
+ };
528
+
529
+ export interface Retry {
530
+ /**
531
+ * Calls fn(attempt) (sync or async) until it succeeds or a retry is not
532
+ * warranted. Out of attempts or budget: rethrows the last error or returns
533
+ * the last result. Honours Retry-After on a 429, capped by maxDelayMs.
534
+ */
535
+ <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions): Promise<Awaited<T>>;
536
+ /** Returns a reusable function with fn's arguments that retries each call. */
537
+ wrap<A extends unknown[], T>(
538
+ fn: (...args: A) => T | Promise<T>,
539
+ options?: RetryOptions,
540
+ ): (...args: A) => Promise<Awaited<T>>;
541
+ }
542
+
486
543
  export interface ScriptStdlib {
487
- fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
488
- fetchJson(input: string | URL | Request, init?: RequestInit): Promise<unknown>;
544
+ fetch(input: string | URL | Request, init?: FetchOptions): Promise<Response>;
545
+ fetchJson(input: string | URL | Request, init?: FetchOptions): Promise<unknown>;
489
546
  grep(pattern: string, files?: string | string[]): Promise<string>;
490
547
  glob(pattern: string): Promise<string[]>;
491
548
  table(rows: Array<Record<string, unknown>>): string;
549
+ retry: Retry;
492
550
  Redacted: RedactedStatic;
493
551
  }
494
552
 
@@ -639,11 +697,35 @@ declare module "stdlib" {
639
697
  meta<T>(self: Redacted<T>): { type: "system" | "user"; isSecret: boolean };
640
698
  isSecret<T>(self: Redacted<T>): boolean;
641
699
  };
642
- export function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
643
- export function fetchJson(input: string | URL | Request, init?: RequestInit): Promise<unknown>;
700
+ export function fetch(input: string | URL | Request, init?: FetchOptions): Promise<Response>;
701
+ export function fetchJson(input: string | URL | Request, init?: FetchOptions): Promise<unknown>;
644
702
  export function grep(pattern: string, files?: string | string[]): Promise<string>;
645
703
  export function glob(pattern: string): Promise<string[]>;
646
704
  export function table(rows: Array<Record<string, unknown>>): string;
705
+ export interface RetryOptions {
706
+ retries?: number;
707
+ minDelayMs?: number;
708
+ maxDelayMs?: number;
709
+ budgetMs?: number;
710
+ retryOn?: (errorOrResult: unknown, attempt: number) => boolean | Promise<boolean>;
711
+ signal?: AbortSignal;
712
+ }
713
+ export interface FetchRetryOptions extends RetryOptions {
714
+ idempotencyKey?: boolean | string;
715
+ }
716
+ export type FetchOptions = RequestInit & {
717
+ retry?: boolean | FetchRetryOptions;
718
+ /** @deprecated Use retry: { retries }. Total attempts. */
719
+ retries?: number;
720
+ timeoutMs?: number;
721
+ };
722
+ export const retry: {
723
+ <T>(fn: (attempt: number) => T | Promise<T>, options?: RetryOptions): Promise<Awaited<T>>;
724
+ wrap<A extends unknown[], T>(
725
+ fn: (...args: A) => T | Promise<T>,
726
+ options?: RetryOptions,
727
+ ): (...args: A) => Promise<Awaited<T>>;
728
+ };
647
729
  }
648
730
  `;
649
731
 
@@ -211,6 +211,13 @@ export function reuseWatermark(o: { from: Cursor; at: string; reuseRan: boolean;
211
211
 
212
212
  const esc = (s: string, n: number) => String(s ?? "").replace(/\s+/g, " ").replace(/\|/g, "\\|").slice(0, n);
213
213
 
214
+ /** Measured triage cost: "this run" only when every triage task has a session_costs row; rows land late, so a short count is "partial". */
215
+ export function measuredCost(row: { tasks?: unknown; usd?: unknown } | undefined, taskCount: number): { usd: number; basis: string } | null {
216
+ const tasks = Number(row?.tasks ?? 0);
217
+ if (!row || row.usd === null || row.usd === undefined || tasks === 0) return null;
218
+ return { usd: Number(row.usd), basis: tasks >= taskCount ? "this run" : `partial: ${tasks} of ${taskCount} tasks` };
219
+ }
220
+
214
221
  export function renderSection(r: { skipReason?: string | null; read: number; planned: number; newRead: number; reuseRead: number; batches: number; okBatches: number; failedBatches: Array<{ batchId: string; status: string }>; promoted: number; kept: number; keptHowto: number; dropped: number; dropWhy: Record<string, number>; guards: Record<string, number>; invalid: Record<string, number>; missing: number; left: number | null; cursor: { from: string; to: string } | null; cost: { usd: number | null; basis: string }; samples: TriageRow[]; names: Record<string, string> }): string {
215
222
  const L: string[] = [HEADING];
216
223
  if (r.skipReason) {
@@ -439,8 +446,9 @@ export default async function (args: unknown, ctx: ScriptContext) {
439
446
  const taskIds = parsed.map((x) => x.taskId).filter(Boolean) as string[];
440
447
  let cost: { usd: number | null; basis: string } = { usd: null, basis: "no tasks" };
441
448
  if (taskIds.length) {
442
- const c = (await q("cost", `SELECT SUM(totalCostUsd) usd FROM session_costs WHERE taskId IN (${taskIds.map(() => "?").join(",")})`, taskIds))[0];
443
- if (c && c.usd !== null && c.usd !== undefined) cost = { usd: Number(c.usd), basis: "this run" };
449
+ const c = (await q("cost", `SELECT COUNT(DISTINCT taskId) tasks, SUM(totalCostUsd) usd FROM session_costs WHERE taskId IN (${taskIds.map(() => "?").join(",")})`, taskIds))[0];
450
+ const measured = measuredCost(c, new Set(taskIds).size);
451
+ if (measured) cost = measured;
444
452
  else {
445
453
  const prior = (await q("cost-prior", `SELECT COUNT(*) tasks, AVG(s.usd) usd FROM (SELECT sc.taskId, SUM(sc.totalCostUsd) usd FROM session_costs sc JOIN agent_tasks t ON t.id = sc.taskId WHERE t.tags LIKE '%dreaming-v2-learnings%' AND t.status = 'completed' AND sc.createdAt >= datetime('now','-7 days') GROUP BY sc.taskId) s`))[0];
446
454
  cost = prior && Number(prior.tasks) > 0 && prior.usd !== null ? { usd: Number(prior.usd) * taskIds.length, basis: `estimate: mean of ${prior.tasks} triage tasks in 7 days` } : { usd: null, basis: "session_costs lands after the triage tasks finish" };
@@ -707,6 +707,45 @@ export function handoffRow(path: string, r: Route, texts: string[], scripts: Ski
707
707
  memberIds,
708
708
  };
709
709
  }
710
+ // Synthesize turns only a few routes into actions a night (shared skill caps), so :latest carries every route it did
711
+ // not act on. A route is consumed when an approved synthesize action cites the handoff KV and one of its members.
712
+ export const ROUTES_KV_REF = "memtax-create:skill-routes";
713
+ export function consumedMembers(synth: unknown): Set<string> {
714
+ const s: any = parse(synth);
715
+ const out = new Set<string>();
716
+ for (const x of Array.isArray(s?.actions) ? s.actions : []) {
717
+ const ev: string[] = Array.isArray(x?.evidence) ? x.evidence.map(String) : [];
718
+ if (!ev.some((e) => e.includes(ROUTES_KV_REF))) continue;
719
+ for (const e of ev) if (e.startsWith("memory:")) out.add(e.slice("memory:".length));
720
+ }
721
+ return out;
722
+ }
723
+ /** Stored routes minus consumed ones, merged by slug with tonight's (union memberIds, tonight's fields win), members
724
+ * whose rows are gone dropped (`live` null = unknown, keep all), largest first. */
725
+ export function carryRoutes(tonight: any[], stored: any[], consumed: Set<string>, live: Set<string> | null) {
726
+ const slugOf = (r: any) => String(r?.slug || String(r?.path ?? "").split("/").pop() || "");
727
+ const namesOf = (r: any) => Object.fromEntries((r?.memberIds ?? []).map((id: string, i: number) => [id, String(r?.memberNames?.[i] ?? "")]));
728
+ const kept = stored.filter((r) => slugOf(r) && !(r.memberIds ?? []).some((id: string) => consumed.has(id)));
729
+ const tonightSlugs = new Set(tonight.map(slugOf));
730
+ const bySlug = new Map<string, any>();
731
+ const names: Record<string, string> = {};
732
+ for (const r of [...kept, ...tonight]) {
733
+ const slug = slugOf(r);
734
+ if (!slug) continue;
735
+ Object.assign(names, Object.fromEntries(Object.entries(namesOf(r)).filter(([, n]) => n)));
736
+ const prev = bySlug.get(slug);
737
+ bySlug.set(slug, { ...prev, ...r, slug, memberIds: [...new Set([...(prev?.memberIds ?? []), ...(r.memberIds ?? []).map(String)])] });
738
+ }
739
+ const routes: any[] = [];
740
+ let gone = 0;
741
+ for (const r of bySlug.values()) {
742
+ const memberIds = live ? r.memberIds.filter((id: string) => live.has(id)) : r.memberIds;
743
+ if (!memberIds.length) gone++;
744
+ else routes.push({ ...r, memberIds, memberNames: memberIds.map((id: string) => names[id] ?? "") });
745
+ }
746
+ routes.sort((x, y) => y.memberIds.length - x.memberIds.length);
747
+ return { routes, carried: routes.filter((r) => !tonightSlugs.has(r.slug)).length, consumed: stored.length - kept.length, gone };
748
+ }
710
749
  export const scriptHint = (texts: string[]) => texts.some((t) => /\b(GET|POST|PUT|PATCH|DELETE) \/|\bcurl\b|\bendpoint\b|https?:\/\/[^\s]*\/(v\d|api)\b|x-api-key|Bearer\b/i.test(String(t ?? "")));
711
750
 
712
751
  const KIND_OF_ROOT = (root: string) =>
@@ -1445,10 +1484,33 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1445
1484
  let handoff = runDry ? "dry run, not written" : "none";
1446
1485
  if (!runDry) {
1447
1486
  try {
1448
- const value = { runId, at: new Date().toISOString(), routes: skillRoutes.map((r) => ({ ...r, memberNames: (r.memberIds ?? []).map((id: string) => memberNames[id] ?? "") })) };
1449
- await ctx.swarm.kv_set({ namespace: NS, key: `memtax-create:skill-routes:${runId}`, value: value as any });
1450
- await ctx.swarm.kv_set({ namespace: NS, key: "memtax-create:skill-routes:latest", value: value as any });
1451
- handoff = `KV memtax-create:skill-routes:latest (${skillRoutes.length} routes)`;
1487
+ const tonight = skillRoutes.map((r) => ({ ...r, memberNames: (r.memberIds ?? []).map((id: string) => memberNames[id] ?? "") }));
1488
+ await ctx.swarm.kv_set({ namespace: NS, key: `memtax-create:skill-routes:${runId}`, value: { runId, at: new Date().toISOString(), routes: tonight } as any });
1489
+ // Tonight's synthesize already read the stored set: drop what it acted on, carry the rest forward.
1490
+ const stored: any = (await ctx.swarm.kv_getOrNull({ namespace: NS, key: "memtax-create:skill-routes:latest" }))?.value;
1491
+ const prior: any[] = Array.isArray(stored?.routes) ? stored.routes : [];
1492
+ let consumed = new Set<string>();
1493
+ try {
1494
+ for (const r of await qStrict(`SELECT json_extract(output, '$.taskOutput') v FROM workflow_run_steps WHERE runId = ? AND nodeId = 'synthesize'`, [runId])) for (const id of consumedMembers(r.v)) consumed.add(id);
1495
+ } catch (e: any) {
1496
+ consumed = new Set();
1497
+ errors.push(`handoff: synthesize step unreadable, nothing marked consumed: ${String(e?.message ?? e).slice(0, 200)}`);
1498
+ }
1499
+ const ids = [...new Set([...prior, ...tonight].flatMap((r: any) => (r?.memberIds ?? []).map(String)))];
1500
+ let live: Set<string> | null = null;
1501
+ try {
1502
+ live = new Set<string>();
1503
+ for (let i = 0; i < ids.length; i += 500) {
1504
+ const part = ids.slice(i, i + 500);
1505
+ for (const r of await qStrict(`SELECT DISTINCT id FROM agent_memory WHERE id IN (${part.map(() => "?").join(",")}) AND (expiresAt IS NULL OR expiresAt > ?)`, [...part, new Date().toISOString()])) live.add(String(r.id));
1506
+ }
1507
+ } catch (e: any) {
1508
+ live = null;
1509
+ errors.push(`handoff: member check failed, kept every member: ${String(e?.message ?? e).slice(0, 200)}`);
1510
+ }
1511
+ const carry = carryRoutes(tonight, prior, consumed, live);
1512
+ await ctx.swarm.kv_set({ namespace: NS, key: "memtax-create:skill-routes:latest", value: { runId, at: new Date().toISOString(), routes: carry.routes } as any });
1513
+ handoff = `KV memtax-create:skill-routes:latest (${carry.routes.length} routes: ${tonight.length} tonight, ${carry.carried} carried, ${carry.consumed} consumed, ${carry.gone} with no live members)`;
1452
1514
  } catch (e: any) {
1453
1515
  errors.push(`handoff: ${String(e?.message ?? e).slice(0, 200)}`);
1454
1516
  handoff = "failed";
@@ -1799,6 +1861,10 @@ async function runScript(args: unknown, ctx: ScriptContext) {
1799
1861
  t("handoff: covered how-to -> skill-refactor skill-update, no script", h2.lane === "skill-refactor" && h2.op === "skill-update" && h2.skill === "agentmail-sending" && h2.scriptLane === null, h2);
1800
1862
  const h3 = handoffRow("/howto/bluesky", routeCluster("/howto/bluesky", sk), ["POST /xrpc/com.atproto.repo.createRecord with Bearer token"], scr, ["d4", "d5"]);
1801
1863
  t("handoff: API how-to with no script -> script candidate", h3.scriptExisting === null && h3.script === true && h3.scriptLane === "scriptify", h3);
1864
+ const cm = consumedMembers(JSON.stringify({ actions: [{ evidence: ["memory:m1", "kv:dreaming-v2/memtax-create:skill-routes:latest"] }, { evidence: ["memory:m9"] }] }));
1865
+ t("carry: only an action citing the handoff KV consumes its members", cm.has("m1") && !cm.has("m9"), [...cm]);
1866
+ const cr = carryRoutes([{ slug: "b", memberIds: ["m4"], memberNames: ["n4"], route: "skill-new" }], [{ slug: "a", memberIds: ["m1"] }, { slug: "b", memberIds: ["m2", "m3"], memberNames: ["n2", "n3"], route: "skill-update" }, { slug: "c", memberIds: ["m5"] }], cm, new Set(["m1", "m2", "m4"]));
1867
+ t("carry: consumed dropped, merged by slug (union), dead members and empty routes dropped, largest first", cr.routes.length === 1 && cr.routes[0].slug === "b" && cr.routes[0].route === "skill-new" && cr.routes[0].memberIds.join() === "m2,m4" && cr.routes[0].memberNames.join() === "n2,n4" && cr.consumed === 1 && cr.gone === 1, cr);
1802
1868
  // Near-duplicate guard. Vectors with a known cosine: [1, 0] vs [c, sqrt(1 - c^2)].
1803
1869
  const at = (c: number) => [c, Math.sqrt(1 - c * c)];
1804
1870
  const o = { nearDupCos: 0.8, twinCos: 0.95 };
@@ -406,6 +406,14 @@ const VALIDATED_KEYS: Record<string, ConfigValidator> = {
406
406
  return "Invalid SWARM_ENABLED_TOOLS (expected comma-separated tool names or a JSON array of strings)";
407
407
  }
408
408
  },
409
+ COMPANY_EMAIL_DOMAINS: (value) =>
410
+ typeof value === "string" &&
411
+ value
412
+ .split(",")
413
+ .map((domain) => domain.trim())
414
+ .every((domain) => domain === "" || /^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(domain))
415
+ ? null
416
+ : "Invalid COMPANY_EMAIL_DOMAINS (expected comma-separated domains, e.g. example.com,example.dev)",
409
417
  FEEDBACK_ENDPOINT: (value) => {
410
418
  if (typeof value !== "string") {
411
419
  return "Invalid FEEDBACK_ENDPOINT (must use HTTPS, or HTTP on a loopback host)";
package/src/be/users.ts CHANGED
@@ -687,8 +687,28 @@ export async function mintRuntimeToken(
687
687
  export async function mintScriptRunToken(
688
688
  agentId: string,
689
689
  ttlMs: number,
690
+ provenance: { sourceStepId?: string; sourceScriptRunId?: string } = {},
690
691
  ): Promise<{ tokenId: string; plaintext: string }> {
691
- return await insertSessionToken(agentId, null, null, ttlMs, null, undefined, null, null, true);
692
+ const token = await insertSessionToken(
693
+ agentId,
694
+ null,
695
+ null,
696
+ ttlMs,
697
+ null,
698
+ undefined,
699
+ null,
700
+ null,
701
+ true,
702
+ );
703
+ // Recorded before the plaintext leaves this function, so no request can
704
+ // present the token without its provenance.
705
+ if (provenance.sourceStepId || provenance.sourceScriptRunId) {
706
+ await getDbClient().run(
707
+ "UPDATE session_tokens SET sourceStepId = ?, sourceScriptRunId = ? WHERE id = ?",
708
+ [provenance.sourceStepId ?? null, provenance.sourceScriptRunId ?? null, token.tokenId],
709
+ );
710
+ }
711
+ return token;
692
712
  }
693
713
 
694
714
  /** Whether a session token was minted by `mintScriptRunToken`. */
@@ -956,6 +976,8 @@ export async function resolveSessionToken(
956
976
  taskId: string | null;
957
977
  runtimeId: string | null;
958
978
  expiresAt: string;
979
+ sourceStepId?: string | null;
980
+ sourceScriptRunId?: string | null;
959
981
  }
960
982
  | null
961
983
  > {
@@ -972,9 +994,11 @@ export async function resolveSessionToken(
972
994
  placement: string | null;
973
995
  expiresAt: string;
974
996
  revokedAt: string | null;
997
+ sourceStepId: string | null;
998
+ sourceScriptRunId: string | null;
975
999
  }>(
976
1000
  `SELECT s.id, s.agentId, s.taskId, s.runtimeId, s.controllerId, s.expiresAt, s.revokedAt,
977
- c.placement FROM session_tokens s LEFT JOIN runtime_controllers c ON c.id = s.controllerId
1001
+ s.sourceStepId, s.sourceScriptRunId, c.placement FROM session_tokens s LEFT JOIN runtime_controllers c ON c.id = s.controllerId
978
1002
  WHERE s.tokenHash = ?`,
979
1003
  [hash],
980
1004
  );
@@ -1011,6 +1035,9 @@ export async function resolveSessionToken(
1011
1035
  taskId: row.taskId,
1012
1036
  runtimeId: row.runtimeId,
1013
1037
  expiresAt: row.expiresAt,
1038
+ ...(row.sourceStepId || row.sourceScriptRunId
1039
+ ? { sourceStepId: row.sourceStepId, sourceScriptRunId: row.sourceScriptRunId }
1040
+ : {}),
1014
1041
  };
1015
1042
  }
1016
1043
 
@@ -212,13 +212,7 @@ function scheduleRunnerGc(reason: string): boolean {
212
212
  return true;
213
213
  }
214
214
 
215
- /** Fetch repo config for a task's vcsRepo (e.g., "desplega-ai/agent-swarm") */
216
- export async function fetchRepoConfig(
217
- apiUrl: string,
218
- apiKey: string,
219
- vcsRepo: string,
220
- requireExactMatch = false,
221
- ): Promise<{
215
+ type RegisteredRepo = {
222
216
  id: string;
223
217
  url: string;
224
218
  name: string;
@@ -226,28 +220,35 @@ export async function fetchRepoConfig(
226
220
  defaultBranch: string;
227
221
  hooks?: { enabled: boolean } | null;
228
222
  guidelines?: RepoGuidelines | null;
229
- } | null> {
230
- try {
231
- const repoName = vcsRepoName(vcsRepo);
232
- const resp = await fetch(`${apiUrl}/api/repos?name=${encodeURIComponent(repoName)}`, {
223
+ };
224
+
225
+ /** Fetch repo config for a task's vcsRepo (e.g., "desplega-ai/agent-swarm") */
226
+ export async function fetchRepoConfig(
227
+ apiUrl: string,
228
+ apiKey: string,
229
+ vcsRepo: string,
230
+ requireExactMatch = false,
231
+ ): Promise<RegisteredRepo | null> {
232
+ const listRepos = async (name?: string): Promise<RegisteredRepo[] | null> => {
233
+ const query = name ? `?name=${encodeURIComponent(name)}` : "";
234
+ const resp = await fetch(`${apiUrl}/api/repos${query}`, {
233
235
  headers: { Authorization: `Bearer ${apiKey}` },
234
236
  });
235
237
  if (!resp.ok) return null;
236
- const data = (await resp.json()) as {
237
- repos: Array<{
238
- id: string;
239
- url: string;
240
- name: string;
241
- clonePath: string;
242
- defaultBranch: string;
243
- hooks?: { enabled: boolean } | null;
244
- guidelines?: RepoGuidelines | null;
245
- }>;
246
- };
247
- if (requireExactMatch) {
248
- return data.repos.find((r) => vcsRepoUrlMatches(r.url, vcsRepo)) ?? null;
249
- }
250
- return data.repos.find((r) => r.url.includes(vcsRepo)) ?? data.repos[0] ?? null;
238
+ return ((await resp.json()) as { repos: RegisteredRepo[] }).repos;
239
+ };
240
+ try {
241
+ const named = await listRepos(vcsRepoName(vcsRepo));
242
+ if (!named) return null;
243
+ // An exact URL match wins, by name first, then across all registered repos (a repo
244
+ // registered under a display name, `frontend` for acme/web), as the API's vcsRepoId
245
+ // does. Only then does the loose legacy match run, so a same-named unrelated repo
246
+ // never shadows the task's repo.
247
+ const exact =
248
+ named.find((r) => vcsRepoUrlMatches(r.url, vcsRepo)) ??
249
+ (await listRepos())?.find((r) => vcsRepoUrlMatches(r.url, vcsRepo));
250
+ if (exact || requireExactMatch) return exact ?? null;
251
+ return named.find((r) => r.url.includes(vcsRepo)) ?? named[0] ?? null;
251
252
  } catch {
252
253
  return null;
253
254
  }
@@ -2530,6 +2531,7 @@ export async function getPausedTasksFromAPI(config: ApiConfig): Promise<
2530
2531
  status?: string;
2531
2532
  contextKey?: string;
2532
2533
  requestedBy?: Trigger["requestedBy"];
2534
+ threadParticipants?: Trigger["threadParticipants"];
2533
2535
  /** The profile claim applied, and its pooled-key allowlist read again at fetch. */
2534
2536
  resolvedProfile?: string;
2535
2537
  credentialAllowlist?: Record<string, string[]>;
@@ -2570,6 +2572,7 @@ export async function getPausedTasksFromAPI(config: ApiConfig): Promise<
2570
2572
  output?: string;
2571
2573
  status?: string;
2572
2574
  requestedBy?: Trigger["requestedBy"];
2575
+ threadParticipants?: Trigger["threadParticipants"];
2573
2576
  resolvedProfile?: string;
2574
2577
  credentialAllowlist?: Record<string, string[]>;
2575
2578
  }>;
@@ -3466,6 +3469,21 @@ interface Trigger {
3466
3469
  /** Structured communication preferences from `users.metadata.comms`. */
3467
3470
  comms?: { tone?: string; language?: string; verbosity?: string };
3468
3471
  };
3472
+ /** People in a multi-person Slack thread (server: `buildTaskThreadParticipants`). */
3473
+ threadParticipants?: {
3474
+ total: number;
3475
+ more: number;
3476
+ people: Array<{
3477
+ label: string;
3478
+ trust: "internal" | "external" | "unknown";
3479
+ starter?: boolean;
3480
+ newest?: boolean;
3481
+ asked?: boolean;
3482
+ language?: string;
3483
+ verbosity?: string;
3484
+ }>;
3485
+ starterProfile?: NonNullable<Trigger["requestedBy"]>;
3486
+ };
3469
3487
  // Phase 4 — budget_refused fields. The server emits this envelope from
3470
3488
  // /api/poll and MCP task-action accept when an admission gate refuses to
3471
3489
  // let the agent claim a task. Worker reads cause + reset/spend/budget for
@@ -3509,34 +3527,131 @@ function workerModelTierOverrides(provider: ProviderName): ModelTierOverrides {
3509
3527
  }
3510
3528
 
3511
3529
  type RequesterProfile = NonNullable<Trigger["requestedBy"]>;
3530
+ type ThreadParticipants = NonNullable<Trigger["threadParticipants"]>;
3512
3531
 
3513
- export async function buildRequesterProfilePrompt(
3514
- requestedBy: RequesterProfile | undefined,
3515
- ): Promise<string> {
3516
- const comms = requestedBy?.comms;
3532
+ /** Comms and notes lines of a profile block, or undefined when it has nothing to say. */
3533
+ function profileSections(
3534
+ profile: RequesterProfile | undefined,
3535
+ ): { role: string; comms: string; notes: string } | undefined {
3536
+ const comms = profile?.comms;
3517
3537
  const commsParts = [
3518
3538
  comms?.tone ? `tone: ${comms.tone}` : undefined,
3519
3539
  comms?.language ? `language: ${comms.language}` : undefined,
3520
3540
  comms?.verbosity ? `verbosity: ${comms.verbosity}` : undefined,
3521
3541
  ].filter((part): part is string => Boolean(part));
3522
- if (!requestedBy?.role && !requestedBy?.notes && commsParts.length === 0) return "";
3542
+ if (!profile?.role && !profile?.notes && commsParts.length === 0) return undefined;
3543
+ const notes = profile?.notes?.trim();
3544
+ return {
3545
+ role: profile?.role ? ` (${profile.role})` : "",
3546
+ comms:
3547
+ commsParts.length > 0 ? `\nTheir communication preferences: ${commsParts.join(", ")}.` : "",
3548
+ notes: notes ? `\nTheir stated notes for how you should respond and act:\n${notes}` : "",
3549
+ };
3550
+ }
3523
3551
 
3524
- const commsSection =
3525
- commsParts.length > 0 ? `\nTheir communication preferences: ${commsParts.join(", ")}.` : "";
3526
- const notes = requestedBy?.notes?.trim();
3527
- const notesSection = notes
3528
- ? `\nTheir stated notes for how you should respond and act:\n${notes}`
3529
- : "";
3552
+ export async function buildRequesterProfilePrompt(
3553
+ requestedBy: RequesterProfile | undefined,
3554
+ inThread = false,
3555
+ ): Promise<string> {
3556
+ const sections = profileSections(requestedBy);
3557
+ if (!sections) return "";
3530
3558
  const result = await resolveTemplateAsync("task.requester.profile", {
3531
3559
  requester_name: requestedBy?.name ?? "",
3532
- requester_role_suffix: requestedBy?.role ? ` (${requestedBy.role})` : "",
3533
- requester_comms_section: commsSection,
3534
- requester_notes_section: notesSection,
3560
+ requester_role_suffix: sections.role,
3561
+ requester_thread_suffix: inThread ? ", who sent the newest message in this thread" : "",
3562
+ requester_comms_section: sections.comms,
3563
+ requester_notes_section: sections.notes,
3535
3564
  });
3536
3565
 
3537
3566
  return result.skipped ? "" : result.text.trim();
3538
3567
  }
3539
3568
 
3569
+ export async function buildThreadStarterProfilePrompt(
3570
+ starter: RequesterProfile | undefined,
3571
+ ): Promise<string> {
3572
+ const sections = profileSections(starter);
3573
+ if (!starter || !sections) return "";
3574
+ const result = await resolveTemplateAsync("task.thread.starter_profile", {
3575
+ starter_name: starter.name,
3576
+ starter_role_suffix: sections.role,
3577
+ starter_comms_section: sections.comms,
3578
+ starter_notes_section: sections.notes,
3579
+ });
3580
+ return result.skipped ? "" : result.text.trim();
3581
+ }
3582
+
3583
+ export async function buildUntrustedRequesterPrompt(requesterLabel: string): Promise<string> {
3584
+ const result = await resolveTemplateAsync("task.thread.untrusted_requester", {
3585
+ requester_label: requesterLabel,
3586
+ });
3587
+ return result.skipped ? "" : result.text.trim();
3588
+ }
3589
+
3590
+ /** One line per listed person; a primary sender points at their profile block by name. */
3591
+ export async function buildThreadParticipantsPrompt(
3592
+ thread: ThreadParticipants,
3593
+ rendered: { requesterProfile: boolean; starterProfile: boolean },
3594
+ ): Promise<string> {
3595
+ const lines = thread.people.map((person) => {
3596
+ const untrusted = person.trust !== "internal";
3597
+ const roles = [
3598
+ person.newest ? "newest sender" : undefined,
3599
+ person.starter ? "started this work" : undefined,
3600
+ !person.newest && !person.starter && person.asked ? "asked in this batch" : undefined,
3601
+ ].filter(Boolean);
3602
+ const notes = [
3603
+ person.language ? `language: ${person.language}` : undefined,
3604
+ person.verbosity ? `verbosity: ${person.verbosity}` : undefined,
3605
+ ].filter(Boolean);
3606
+ const profile =
3607
+ !untrusted && person.newest && rendered.requesterProfile
3608
+ ? "Profile: Requester Profile above."
3609
+ : !untrusted && person.starter && rendered.starterProfile
3610
+ ? "Profile: Thread starter profile above."
3611
+ : !untrusted && notes.length > 0
3612
+ ? `${notes.join("; ")}.`
3613
+ : "no saved preferences.";
3614
+ return roles.length > 0
3615
+ ? `- ${person.label}: ${roles.join(", ")}. ${profile[0]!.toUpperCase()}${profile.slice(1)}`
3616
+ : `- ${person.label}: ${profile}`;
3617
+ });
3618
+ if (thread.more > 0) lines.push(`- <${thread.more} more...>`);
3619
+ const result = await resolveTemplateAsync("task.thread.participants", {
3620
+ participant_count: String(thread.total),
3621
+ participant_lines: lines.join("\n"),
3622
+ });
3623
+ if (result.skipped) return "";
3624
+ if (!thread.people.some((person) => person.trust !== "internal")) return result.text.trim();
3625
+ const untrusted = await resolveTemplateAsync("task.thread.untrusted_participants", {});
3626
+ return untrusted.skipped ? result.text.trim() : `${result.text.trim()}\n${untrusted.text.trim()}`;
3627
+ }
3628
+
3629
+ /**
3630
+ * Requester-side blocks of the task prompt: the Requester Profile (or the
3631
+ * untrusted-requester block), the thread starter's profile, and the
3632
+ * participants list. Without thread participants this is the Requester
3633
+ * Profile alone, unchanged.
3634
+ */
3635
+ export async function buildRequesterPrompts(
3636
+ requestedBy: RequesterProfile | undefined,
3637
+ thread: ThreadParticipants | undefined,
3638
+ ): Promise<string[]> {
3639
+ const newest = thread?.people.find((person) => person.newest);
3640
+ const untrustedRequester = !!newest && newest.trust !== "internal";
3641
+ const head =
3642
+ newest && untrustedRequester
3643
+ ? await buildUntrustedRequesterPrompt(newest.label)
3644
+ : await buildRequesterProfilePrompt(requestedBy, !!thread);
3645
+ const starterProfile = await buildThreadStarterProfilePrompt(thread?.starterProfile);
3646
+ const participants = thread
3647
+ ? await buildThreadParticipantsPrompt(thread, {
3648
+ requesterProfile: !untrustedRequester && !!head,
3649
+ starterProfile: !!starterProfile,
3650
+ })
3651
+ : "";
3652
+ return [head, starterProfile, participants];
3653
+ }
3654
+
3540
3655
  /**
3541
3656
  * Warning appended to the task prompt when the task's `dir` was requested but
3542
3657
  * the session could not start there. Shared by the fresh and resume paths so
@@ -3554,6 +3669,7 @@ export function missingTaskDirWarning(
3554
3669
  /** Per-task context that rides in the task prompt, never the system prompt. */
3555
3670
  export type TaskSessionContext = Omit<TaskContextPromptArgs, keyof BasePromptArgs> & {
3556
3671
  requestedBy?: RequesterProfile;
3672
+ threadParticipants?: ThreadParticipants;
3557
3673
  /** Set when the task's `dir` does not exist and the session falls back. */
3558
3674
  cwdWarning?: string;
3559
3675
  };
@@ -3583,7 +3699,7 @@ export async function buildTaskSessionPrompts(input: {
3583
3699
  repoContext: context.repoContext,
3584
3700
  slackContext: context.slackContext,
3585
3701
  }),
3586
- await buildRequesterProfilePrompt(context.requestedBy),
3702
+ ...(await buildRequesterPrompts(context.requestedBy, context.threadParticipants)),
3587
3703
  context.cwdWarning?.trim(),
3588
3704
  ]
3589
3705
  .filter((part): part is string => Boolean(part))
@@ -7138,6 +7254,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7138
7254
  }
7139
7255
  : undefined,
7140
7256
  requestedBy: task.requestedBy,
7257
+ threadParticipants: task.threadParticipants,
7141
7258
  cwdWarning: missingTaskDirWarning(task.dir, resumeCwd),
7142
7259
  },
7143
7260
  });
@@ -7720,6 +7837,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
7720
7837
  repoContext: currentRepoContext,
7721
7838
  slackContext: taskSlackContext,
7722
7839
  requestedBy: trigger.requestedBy,
7840
+ threadParticipants: trigger.threadParticipants,
7723
7841
  cwdWarning,
7724
7842
  },
7725
7843
  });