@desplega.ai/agent-swarm 2.7.7 → 2.7.8

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 (251) hide show
  1. package/dist/{acp-adapter-7b4vk3h5.js → acp-adapter-vg5hqkvj.js} +6 -6
  2. package/dist/{actions-3tt153af.js → actions-4m1ct4nh.js} +18 -18
  3. package/dist/{amp-adapter-njpts0yr.js → amp-adapter-txqh7eqj.js} +2 -2
  4. package/dist/{app-nky4378f.js → app-e00m45gn.js} +3 -3
  5. package/dist/{assistant-jnb669pa.js → assistant-gd08kr9e.js} +20 -20
  6. package/dist/boot-args-schema-tjrkpbvm.js +89 -0
  7. package/dist/{boot-reembed-9mgvaztt.js → boot-reembed-21hbck22.js} +1 -1
  8. package/dist/{boot-reembed-qs2djdej.js → boot-reembed-mdxd3wgp.js} +1 -1
  9. package/dist/{boot-scrub-sweep-yjpdj7s1.js → boot-scrub-sweep-qy0zr9t2.js} +3 -3
  10. package/dist/{boot-seeds-5cm6ambd.js → boot-seeds-n46eaxdv.js} +4 -4
  11. package/dist/{claude-adapter-fn287zmm.js → claude-adapter-j37w2eds.js} +6 -6
  12. package/dist/{claude-managed-adapter-dvs2xw5n.js → claude-managed-adapter-8jvcma9a.js} +3 -3
  13. package/dist/{claude-managed-setup-wtdz2mj2.js → claude-managed-setup-rzkjmgc1.js} +3 -3
  14. package/dist/{claude-sdk-session-x91kqyhm.js → claude-sdk-session-4k7w73t0.js} +7 -7
  15. package/dist/{cli-rtt8g4v9.js → cli-0ykgn1h5.js} +1 -1
  16. package/dist/{cli-5b456bpf.js → cli-1cxrbkk6.js} +2 -2
  17. package/dist/{cli-5jnhv72d.js → cli-269q28a1.js} +4 -2
  18. package/dist/{cli-k1nje3v3.js → cli-32m9eda8.js} +49 -37
  19. package/dist/{cli-35rsp8ye.js → cli-3e4snnzf.js} +1 -1
  20. package/dist/{cli-5zx699j9.js → cli-4t50yq3j.js} +2 -2
  21. package/dist/{cli-n6bv12jn.js → cli-5j0m12ns.js} +10 -3
  22. package/dist/{cli-dhar9qay.js → cli-5ja3b75e.js} +2 -2
  23. package/dist/{cli-g08zdaec.js → cli-66ww7fer.js} +1 -1
  24. package/dist/{cli-nmzhp1b5.js → cli-7axf41jq.js} +25 -14
  25. package/dist/{cli-gz6q4eve.js → cli-84rj785g.js} +5 -5
  26. package/dist/{cli-fyt2g4wd.js → cli-85gzce7b.js} +5 -5
  27. package/dist/{cli-3fg0bdcv.js → cli-8h0ayw8c.js} +1 -1
  28. package/dist/{cli-qghe0h66.js → cli-8rpcng8j.js} +2 -2
  29. package/dist/{cli-ws19768n.js → cli-8sdejs1f.js} +115 -51
  30. package/dist/{cli-8305gbq0.js → cli-9m8hdawy.js} +3 -3
  31. package/dist/{cli-excnnjg2.js → cli-ae0dnfee.js} +1 -1
  32. package/dist/{cli-e0kmphd6.js → cli-bb0mmdk8.js} +2 -2
  33. package/dist/{cli-1c6tzt8g.js → cli-bbw9wj9m.js} +8 -8
  34. package/dist/{cli-pjctyea3.js → cli-bshb7jas.js} +2 -2
  35. package/dist/{cli-08bmz9z9.js → cli-btfsp3mv.js} +3 -3
  36. package/dist/{cli-4zsenjhy.js → cli-c0kqky8y.js} +16 -3
  37. package/dist/{cli-tgrv9cjx.js → cli-dq8x79v8.js} +1 -1
  38. package/dist/{cli-ftyxyspd.js → cli-eqtfgfr6.js} +1 -1
  39. package/dist/{cli-ddaanqkd.js → cli-eyg1pa00.js} +3 -3
  40. package/dist/{cli-8sckt74b.js → cli-fyhr5h4s.js} +34 -12
  41. package/dist/{cli-q3tkegby.js → cli-fzachfnf.js} +1 -1
  42. package/dist/{cli-ayayvfg4.js → cli-ga786dzg.js} +13 -10
  43. package/dist/{cli-yyj3j5m4.js → cli-gazw7kpa.js} +2 -2
  44. package/dist/{cli-e46hg0xw.js → cli-gvx71kqv.js} +2 -2
  45. package/dist/{cli-pc6n7fre.js → cli-jdv6ypxs.js} +1 -1
  46. package/dist/{cli-cm5yqn35.js → cli-kf3pxxdg.js} +1 -0
  47. package/dist/{cli-6g0hb4cp.js → cli-kyr67fgx.js} +7 -7
  48. package/dist/{cli-95jzxcp3.js → cli-m0hmeqma.js} +2 -2
  49. package/dist/{cli-6pfd54vx.js → cli-msg9m2ny.js} +3 -1
  50. package/dist/{cli-afkqkrtw.js → cli-nbsf8yvn.js} +15 -3
  51. package/dist/{cli-tfyyvzx6.js → cli-njwac61j.js} +5 -0
  52. package/dist/{cli-vz22fyqv.js → cli-nn3ysbqk.js} +1 -1
  53. package/dist/{cli-m0da8j35.js → cli-p3vsj0d3.js} +5 -5
  54. package/dist/{cli-72v799xn.js → cli-ppjxh6ah.js} +3 -3
  55. package/dist/{cli-k899ehvh.js → cli-q4ebh7h7.js} +4 -4
  56. package/dist/{cli-75gkpjvw.js → cli-qd57hhhh.js} +2 -2
  57. package/dist/{cli-qh4d4tvk.js → cli-rjknb2ae.js} +4 -4
  58. package/dist/{cli-caj33vcq.js → cli-s4ss5g59.js} +1 -1
  59. package/dist/{cli-cb2a8pna.js → cli-sq4n7af4.js} +1 -1
  60. package/dist/{cli-vfym7wmz.js → cli-ssnjfg5p.js} +5 -5
  61. package/dist/{cli-je518txm.js → cli-t60ajbbp.js} +8 -8
  62. package/dist/{cli-adeegh7d.js → cli-tpksw2nr.js} +21 -17
  63. package/dist/{cli-wk5yrfwd.js → cli-w4xnbm46.js} +150 -58
  64. package/dist/{cli-k8196sh2.js → cli-wemma3jd.js} +8 -7
  65. package/dist/{cli-cppkf404.js → cli-xq9r2wtt.js} +45 -21
  66. package/dist/{cli-bfv7vdg6.js → cli-xr8908my.js} +11 -11
  67. package/dist/{cli-73jzwksr.js → cli-ycscb2ar.js} +4 -1
  68. package/dist/{cli-p82cnnjq.js → cli-yqefz277.js} +1 -1
  69. package/dist/{cli-jtjtabxe.js → cli-z1srzaf6.js} +11 -3
  70. package/dist/{cli-pq73h5mz.js → cli-z75yxkjh.js} +3 -3
  71. package/dist/{cli-e5bzrn01.js → cli-zkky4t5g.js} +1 -1
  72. package/dist/cli.js +17 -15
  73. package/dist/{codex-adapter-cf2yxe9m.js → codex-adapter-88z6psm4.js} +5 -5
  74. package/dist/{codex-hook-a0c6g6t6.js → codex-hook-fac6175r.js} +1 -1
  75. package/dist/{codex-login-y0pmff1c.js → codex-login-74wa4hmq.js} +1 -1
  76. package/dist/{codex-session-runner-6vfzdgbd.js → codex-session-runner-zwbcwzvx.js} +5 -5
  77. package/dist/{commands-t3mfy7vn.js → commands-7amxs716.js} +3 -3
  78. package/dist/{controller-q7xrbaz0.js → controller-5rkkc37m.js} +2 -2
  79. package/dist/{controllers-connect-c6nm70kg.js → controllers-connect-m7d4vxxb.js} +19 -19
  80. package/dist/{cursor-adapter-ftd81ga8.js → cursor-adapter-x1q18693.js} +1 -1
  81. package/dist/{db-vemtpmcc.js → db-athc68zt.js} +4 -2
  82. package/dist/{db-dk572x25.js → db-h2fsfve3.js} +3 -3
  83. package/dist/{dispatcher-kh7ecxh9.js → dispatcher-b1yz2bnn.js} +17 -17
  84. package/dist/{dsh-adapter-v8628r89.js → dsh-adapter-e33bkxq9.js} +1 -1
  85. package/dist/{easter-egg-3d-nenw4x63.js → easter-egg-3d-pv5qnzc8.js} +1 -1
  86. package/dist/{embedding-space-0jepb239.js → embedding-space-b4txbwrk.js} +6 -6
  87. package/dist/{embeddings-xxt49yxg.js → embeddings-m6zn6tad.js} +1 -1
  88. package/dist/{execute-1mhw6e4x.js → execute-68nwny8m.js} +1 -1
  89. package/dist/{external-channel-55v12e60.js → external-channel-gkckmhzh.js} +2 -2
  90. package/dist/{fx-adapter-bs8wqrk5.js → fx-adapter-m5jbgd5q.js} +7 -7
  91. package/dist/{grok-adapter-gpjqmkcq.js → grok-adapter-csvv7sac.js} +7 -7
  92. package/dist/handlers-8x5gfbzx.js +32 -0
  93. package/dist/{heartbeat-k42svnr0.js → heartbeat-6c2y3267.js} +20 -20
  94. package/dist/{hook-6nphweh0.js → hook-q5fv0jy2.js} +6 -6
  95. package/dist/{hook-114m7hap.js → hook-w0q2wcrv.js} +5 -5
  96. package/dist/{http-r8cc4wz7.js → http-bxat8dg3.js} +260 -120
  97. package/dist/{index-nh3wyqdt.js → index-bxrexmfy.js} +13 -13
  98. package/dist/{index-e3s8wmxy.js → index-cqhqpgrv.js} +1 -1
  99. package/dist/{index-fpk4bcd9.js → index-fm0czesf.js} +1 -1
  100. package/dist/index-hpfte8jd.js +33 -0
  101. package/dist/index-ncf7yb5s.js +30 -0
  102. package/dist/index-vte6dyeh.js +37 -0
  103. package/dist/{keepalive-x060nt9p.js → keepalive-qnt21cv0.js} +3 -3
  104. package/dist/lead-4bvftzm6.js +71 -0
  105. package/dist/{maintenance-2xxfexhf.js → maintenance-btdr68y4.js} +1 -1
  106. package/dist/{oauth-refresh-sweep-fckc4ar5.js → oauth-refresh-sweep-vczabeh4.js} +2 -2
  107. package/dist/{onboard-zc48j237.js → onboard-k33ezyq8.js} +2 -2
  108. package/dist/{opencode-adapter-r690h1cr.js → opencode-adapter-3dst2ka7.js} +5 -5
  109. package/dist/{otel-impl-r5xbh81q.js → otel-impl-13am7a65.js} +1 -1
  110. package/dist/{pi-mono-adapter-c7v8sdec.js → pi-mono-adapter-c53de1gd.js} +15 -9
  111. package/dist/{pricing-refresh-3pmre11v.js → pricing-refresh-9fcbnq3f.js} +3 -3
  112. package/dist/{rbac-roles-910mmkgz.js → rbac-roles-66j5h4y5.js} +5 -3
  113. package/dist/{rbac-roles-3vbshwsb.js → rbac-roles-gw0p9h3j.js} +2 -2
  114. package/dist/{render-v2-pxykkbab.js → render-v2-fg8bmdn4.js} +3 -3
  115. package/dist/{resume-adda0bwy.js → resume-1c8kr3nh.js} +6 -6
  116. package/dist/{runtime-fnbm7stk.js → runtime-tzf9j7tc.js} +1 -1
  117. package/dist/{session-access-2fvamrdc.js → session-access-d0atq10j.js} +7 -5
  118. package/dist/{session-source-backfill-08xvv0sm.js → session-source-backfill-0vscqmsa.js} +2 -2
  119. package/dist/{setup-1aqmvmh1.js → setup-tvfa7rwe.js} +1 -1
  120. package/dist/{virtual-modules-d2pjk9j1.js → virtual-modules-efxcp740.js} +2 -2
  121. package/dist/{work-objects-9s0yrm5j.js → work-objects-ks71xqeb.js} +20 -20
  122. package/dist/worker-e7v2bvm9.js +71 -0
  123. package/dist/{worker-follow-up-3q78fqmr.js → worker-follow-up-bfx0h9hg.js} +17 -17
  124. package/openapi.json +104 -24
  125. package/package.json +3 -1
  126. package/src/be/db/model-profiles.ts +1 -1
  127. package/src/be/db/session-tree.ts +9 -5
  128. package/src/be/db/session-visibility.ts +25 -9
  129. package/src/be/db/tasks/read.ts +11 -6
  130. package/src/be/db/tasks/write.ts +77 -7
  131. package/src/be/db-queries/tracker.ts +4 -2
  132. package/src/be/db.ts +49 -17
  133. package/src/be/migrations/271_subscription_usage_model.sql +30 -0
  134. package/src/be/model-validation.ts +19 -1
  135. package/src/be/rbac-roles.ts +21 -0
  136. package/src/be/runtime-pools/routing.ts +1 -1
  137. package/src/be/scripts/boot-args-schema.ts +95 -0
  138. package/src/be/scripts/extract-schema.ts +15 -10
  139. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -1
  140. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -1
  141. package/src/be/seed-scripts/catalog/get-child-outputs.ts +1 -1
  142. package/src/be/seed-scripts/catalog/wait-for-task.ts +1 -1
  143. package/src/be/swarm-config-guard.ts +7 -0
  144. package/src/be/users.ts +6 -4
  145. package/src/commands/claude-managed-setup.ts +1 -1
  146. package/src/commands/runner.ts +26 -9
  147. package/src/extensions/contract-types.generated.ts +1 -1
  148. package/src/http/agents.ts +7 -1
  149. package/src/http/approval-requests.ts +30 -6
  150. package/src/http/codex-oauth-device.ts +2 -2
  151. package/src/http/index.ts +8 -0
  152. package/src/http/mcp-oauth.ts +6 -0
  153. package/src/http/mcp-servers.ts +8 -0
  154. package/src/http/models-catalog.ts +1 -1
  155. package/src/http/pages-public.ts +38 -1
  156. package/src/http/poll.ts +3 -4
  157. package/src/http/prompt-templates.ts +1 -1
  158. package/src/http/schedules.ts +4 -0
  159. package/src/http/script-runs.ts +6 -1
  160. package/src/http/session-access.ts +61 -6
  161. package/src/http/sessions.ts +23 -7
  162. package/src/http/tasks.ts +53 -9
  163. package/src/http/users.ts +30 -1
  164. package/src/http/utils.ts +2 -1
  165. package/src/http/workflows.ts +11 -7
  166. package/src/prompts/session-templates.ts +1 -0
  167. package/src/providers/acp-targets.ts +1 -1
  168. package/src/providers/amp-adapter.ts +1 -1
  169. package/src/providers/codex-adapter.ts +9 -2
  170. package/src/providers/codex-oauth/device.ts +49 -15
  171. package/src/providers/codex-oauth/flow.ts +2 -1
  172. package/src/providers/pi-mono-adapter.ts +8 -0
  173. package/src/providers/pricing-sources.md +16 -1
  174. package/src/providers/swarm-events-shared.ts +15 -2
  175. package/src/rbac/legacy-policy.ts +1 -0
  176. package/src/rbac/permissions.ts +5 -0
  177. package/src/scheduler/deferred-task-waits.ts +9 -4
  178. package/src/scripts-runtime/extract-args-schema.ts +3 -1
  179. package/src/scripts-runtime/swarm-sdk.ts +1 -1
  180. package/src/scripts-runtime/types/swarm-extension.d.ts +29 -28
  181. package/src/server-user.ts +1 -1
  182. package/src/slack/ack.ts +48 -12
  183. package/src/slack/blocks.ts +1 -0
  184. package/src/slack/reaction-shortcode.ts +8 -2
  185. package/src/slack/render-v2.ts +30 -3
  186. package/src/slack/task-output.ts +4 -1
  187. package/src/slack/thread-buffer.ts +2 -2
  188. package/src/tasks/task-skip.ts +28 -0
  189. package/src/tasks/terminal-result-guard.ts +3 -2
  190. package/src/telemetry.ts +28 -1
  191. package/src/tests/agentmail-inbox-mapping.test.ts +73 -0
  192. package/src/tests/approval-requests.test.ts +58 -0
  193. package/src/tests/claude-managed-setup.test.ts +36 -0
  194. package/src/tests/codex-adapter.test.ts +2 -2
  195. package/src/tests/codex-oauth-device.test.ts +60 -0
  196. package/src/tests/codex-swarm-events.test.ts +43 -1
  197. package/src/tests/context-window.test.ts +14 -0
  198. package/src/tests/db-queries-tracker.test.ts +2 -1
  199. package/src/tests/db-task-read-contract.test.ts +1 -0
  200. package/src/tests/db-task-write-contract.test.ts +2 -0
  201. package/src/tests/deferred-task-wake.test.ts +7 -2
  202. package/src/tests/e2e-coverage-contract.test.ts +235 -0
  203. package/src/tests/empty-output-schema.test.ts +160 -0
  204. package/src/tests/env-flag.test.ts +1 -0
  205. package/src/tests/explicit-model-validation.test.ts +14 -0
  206. package/src/tests/http-api-integration.test.ts +2 -2
  207. package/src/tests/http-users.test.ts +63 -0
  208. package/src/tests/mcp-input-caps.test.ts +4 -3
  209. package/src/tests/merge-gate-detect-changes.test.ts +22 -0
  210. package/src/tests/pages-authed-mode.test.ts +13 -2
  211. package/src/tests/pi-mono-adapter.test.ts +39 -4
  212. package/src/tests/rbac-engine.test.ts +1 -0
  213. package/src/tests/runner-context-usage.test.ts +119 -0
  214. package/src/tests/script-connections.test.ts +2 -0
  215. package/src/tests/script-executor-quickjs.test.ts +2 -0
  216. package/src/tests/script-runs-http.test.ts +57 -0
  217. package/src/tests/scripts-boot-args-schema.test.ts +181 -0
  218. package/src/tests/scripts-runtime.test.ts +24 -0
  219. package/src/tests/sdk-store-progress-skipped.test.ts +155 -0
  220. package/src/tests/session-costs-model-key-normalize.test.ts +59 -0
  221. package/src/tests/session-sharing.test.ts +212 -2
  222. package/src/tests/slack-reaction-config.test.ts +1 -0
  223. package/src/tests/slack-render-v2.test.ts +73 -0
  224. package/src/tests/slack-skip-reaction.test.ts +203 -0
  225. package/src/tests/store-progress-skipped.test.ts +159 -0
  226. package/src/tests/subscription-usage-migration.test.ts +57 -0
  227. package/src/tests/swarm-config-reserved-keys.test.ts +3 -0
  228. package/src/tests/telemetry-endpoint-override.test.ts +27 -0
  229. package/src/tests/trigger-claiming.test.ts +2 -0
  230. package/src/tests/workflow-system-one-extraction.test.ts +29 -0
  231. package/src/tools/create-channel.ts +1 -1
  232. package/src/tools/defer-task.ts +1 -1
  233. package/src/tools/register-agentmail-inbox.ts +5 -0
  234. package/src/tools/repos/update-repo.ts +1 -1
  235. package/src/tools/request-human-input.ts +1 -1
  236. package/src/tools/send-task.ts +1 -1
  237. package/src/tools/store-progress.ts +39 -8
  238. package/src/tools/tracker/tracker-unlink.ts +2 -1
  239. package/src/tools/workflows/retry-workflow-run.ts +3 -0
  240. package/src/types.ts +11 -2
  241. package/src/utils/context-window.ts +6 -1
  242. package/src/utils/output-schema.ts +23 -0
  243. package/src/workflows/executors/system-one-providers.ts +25 -6
  244. package/src/workflows/recovery.ts +8 -4
  245. package/src/workflows/resume.ts +19 -0
  246. package/dist/handlers-zxmp1ta4.js +0 -32
  247. package/dist/index-a8phxqnk.js +0 -37
  248. package/dist/index-k6h00t4c.js +0 -30
  249. package/dist/index-xrz7te8h.js +0 -33
  250. package/dist/lead-956sd2yc.js +0 -71
  251. package/dist/worker-y15hy08h.js +0 -71
@@ -1,7 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { getSteeringMessageById } from "../be/db";
3
3
  import { getActiveSessionById } from "../be/db/active-sessions";
4
- import { getUserGrant } from "../be/rbac-roles";
4
+ import { getUserGrant, userHoldsExplicitVerb } from "../be/rbac-roles";
5
5
  import {
6
6
  getSessionRoot,
7
7
  hasSessionAccess,
@@ -28,14 +28,59 @@ import { jsonError } from "./utils";
28
28
  * active user in `X-Swarm-User-Id`. On the shared key that identity is
29
29
  * honor-system, the same trust the dashboard already gives favorites.
30
30
  * `userId: null` is a guest page session, which has no user at all.
31
+ * `readAll` is the all-users read scope: the request opted in and the user
32
+ * may read every session (see `canReadAllSessions`). It lifts reads only;
33
+ * write and steer checks still need the user's own access.
31
34
  */
32
- export type SessionActor = { kind: "bypass" } | { kind: "user"; userId: string | null };
35
+ export type SessionActor =
36
+ | { kind: "bypass" }
37
+ | { kind: "user"; userId: string | null; readAll?: boolean };
33
38
 
34
39
  const BYPASS: SessionActor = { kind: "bypass" };
35
40
 
41
+ /**
42
+ * Request header that opts a dashboard tab into the all-users read scope, so
43
+ * every list and detail read of that tab carries it. `GET /api/tasks` and
44
+ * `GET /api/sessions` also take it as `scope=all`.
45
+ */
46
+ export const SESSION_SCOPE_HEADER = "x-swarm-session-scope";
47
+
48
+ function requestsAllUsersScope(req: IncomingMessage): boolean {
49
+ const raw = req.headers[SESSION_SCOPE_HEADER];
50
+ return (Array.isArray(raw) ? raw[0] : raw)?.trim().toLowerCase() === "all";
51
+ }
52
+
53
+ /**
54
+ * Whether `userId` may opt in to read every user's sessions: one of its roles
55
+ * lists `session.read.all` explicitly. The grant-all `admin` role is not
56
+ * enough, because every new user gets it (`trg_users_default_role`). The
57
+ * stored grant decides with RBAC on or off: RBAC off opens the admission
58
+ * gate, not other users' private sessions.
59
+ */
60
+ export async function canReadAllSessions(userId: string): Promise<boolean> {
61
+ return userHoldsExplicitVerb(userId, "session.read.all");
62
+ }
63
+
64
+ /**
65
+ * The session actor of a request. The all-users scope (`allUsers`, or the
66
+ * `X-Swarm-Session-Scope: all` header) sets `readAll` only for a user who may
67
+ * read every session; for anyone else it is ignored and the usual filter
68
+ * applies. A bypass actor already reads everything.
69
+ */
36
70
  export async function resolveSessionActor(
37
71
  req: IncomingMessage,
38
72
  myAgentId: string | undefined,
73
+ opts: { allUsers?: boolean } = {},
74
+ ): Promise<SessionActor> {
75
+ const actor = await resolveBaseSessionActor(req, myAgentId);
76
+ if (actor.kind !== "user" || !actor.userId) return actor;
77
+ if (!opts.allUsers && !requestsAllUsersScope(req)) return actor;
78
+ return (await canReadAllSessions(actor.userId)) ? { ...actor, readAll: true } : actor;
79
+ }
80
+
81
+ async function resolveBaseSessionActor(
82
+ req: IncomingMessage,
83
+ myAgentId: string | undefined,
39
84
  ): Promise<SessionActor> {
40
85
  const auth = getRequestAuth(req);
41
86
  const userId = authUserId(auth);
@@ -50,12 +95,18 @@ export async function resolveSessionActor(
50
95
  return BYPASS;
51
96
  }
52
97
 
98
+ /** `access`, raised to at least `read` for an actor with the all-users read scope. */
99
+ export function withReadAll(actor: SessionActor, access: SessionAccess): SessionAccess {
100
+ return actor.kind === "user" && actor.readAll && access === "none" ? "read" : access;
101
+ }
102
+
53
103
  /** The actor's access to the session holding `taskId`; `owner` for a bypass actor. */
54
104
  export async function sessionAccessFor(
55
105
  actor: SessionActor,
56
106
  taskId: string,
57
107
  ): Promise<SessionAccess> {
58
- return actor.kind === "bypass" ? "owner" : sessionAccess(actor.userId, taskId);
108
+ if (actor.kind === "bypass") return "owner";
109
+ return withReadAll(actor, await sessionAccess(actor.userId, taskId));
59
110
  }
60
111
 
61
112
  export const SESSION_READ_DENIED =
@@ -71,9 +122,12 @@ export async function canReadSession(
71
122
  return hasSessionAccess(access, "read");
72
123
  }
73
124
 
74
- /** The SQL list filter (`readableSessionCondition`) for an actor; none for a bypass actor. */
125
+ /**
126
+ * The SQL list filter (`readableSessionCondition`) for an actor; none for a
127
+ * bypass actor or the all-users read scope.
128
+ */
75
129
  export function readableByFor(actor: SessionActor): { userId: string | null } | undefined {
76
- return actor.kind === "user" ? { userId: actor.userId } : undefined;
130
+ return actor.kind === "user" && !actor.readAll ? { userId: actor.userId } : undefined;
77
131
  }
78
132
 
79
133
  export const SESSION_WRITE_DENIED =
@@ -162,7 +216,8 @@ async function denialFor(
162
216
  if (actor.kind === "bypass") return null;
163
217
  const root = await getSessionRoot(taskId);
164
218
  if (!root) return null;
165
- if (hasSessionAccess(await sessionAccessForRoot(actor.userId, root), needed)) return null;
219
+ const access = withReadAll(actor, await sessionAccessForRoot(actor.userId, root));
220
+ if (hasSessionAccess(access, needed)) return null;
166
221
  return needed === "read" ? SESSION_READ_DENIED : SESSION_WRITE_DENIED;
167
222
  }
168
223
 
@@ -84,6 +84,7 @@ import {
84
84
  resolveSessionActor,
85
85
  type SessionActor,
86
86
  sessionAccessFor,
87
+ withReadAll,
87
88
  } from "./session-access";
88
89
  import { jsonError } from "./utils";
89
90
 
@@ -593,12 +594,16 @@ const listSessions = route({
593
594
  * an empty list for mine or shared.
594
595
  * tree: Sessions that GET /api/session-tree counts: mine plus shared with me,
595
596
  * no ownerless roots. A bypass actor sees every root.
597
+ * all: every user's sessions, read-only. Honored for a user who may read
598
+ * every session (admin, or `session.read.all`); anyone else gets the
599
+ * default list. The `X-Swarm-Session-Scope: all` header opts in the same
600
+ * way and also lifts the tree scope.
596
601
  */
597
602
  scope: z
598
- .enum(["mine", "shared", "tree"])
603
+ .enum(["mine", "shared", "tree", "all"])
599
604
  .optional()
600
605
  .describe(
601
- "mine: owned sessions. shared: sessions shared with me. tree: Sessions that GET /api/session-tree counts: mine plus shared with me, no ownerless roots. A bypass actor sees every root with tree scope.",
606
+ "mine: owned sessions. shared: sessions shared with me. tree: Sessions that GET /api/session-tree counts: mine plus shared with me, no ownerless roots. A bypass actor sees every root with tree scope. all: every user's sessions, read-only, for a user with an admin role or session.read.all; ignored for anyone else. The X-Swarm-Session-Scope: all header opts in the same way, also for tree.",
602
607
  ),
603
608
  /** With `scope=tree`: `mine` (default) or `all`. Must match the tree's `show`. */
604
609
  show: SessionShowSchema,
@@ -862,7 +867,9 @@ async function accessForRoot(
862
867
  actor: SessionActor,
863
868
  root: { id: string; requestedByUserId: string | null },
864
869
  ): Promise<SessionAccess> {
865
- return actor.kind === "bypass" ? "owner" : sessionAccessForRoot(actor.userId, root);
870
+ return actor.kind === "bypass"
871
+ ? "owner"
872
+ : withReadAll(actor, await sessionAccessForRoot(actor.userId, root));
866
873
  }
867
874
 
868
875
  // ─── Handler ─────────────────────────────────────────────────────────────────
@@ -972,9 +979,13 @@ export async function handleSessions(
972
979
  .map((s) => s.trim())
973
980
  .filter(Boolean)
974
981
  : undefined;
975
- const actor = await resolveSessionActor(req, myAgentId);
982
+ const allUsers = parsed.query.scope === "all";
983
+ const actor = await resolveSessionActor(req, myAgentId, { allUsers });
976
984
  const limit = Math.min(200, Math.max(0, parsed.query.limit ?? 25));
977
- if (actor.kind === "bypass" && parsed.query.scope && parsed.query.scope !== "tree") {
985
+ if (
986
+ actor.kind === "bypass" &&
987
+ (parsed.query.scope === "mine" || parsed.query.scope === "shared")
988
+ ) {
978
989
  // No user to own or receive a share.
979
990
  listSessions.respond(res, 200, {
980
991
  sessions: [],
@@ -1004,7 +1015,11 @@ export async function handleSessions(
1004
1015
  ? {
1005
1016
  viewer: {
1006
1017
  userId: actor.userId,
1007
- scope: parsed.query.scope === "tree" ? "all" : (parsed.query.scope ?? "all"),
1018
+ scope:
1019
+ parsed.query.scope === "mine" || parsed.query.scope === "shared"
1020
+ ? parsed.query.scope
1021
+ : "all",
1022
+ readAll: actor.readAll,
1008
1023
  } as const,
1009
1024
  }
1010
1025
  : {}),
@@ -1067,6 +1082,7 @@ export async function handleSessions(
1067
1082
  actor.userId,
1068
1083
  { ...list, mine: show !== "all" },
1069
1084
  action,
1085
+ actor.readAll,
1070
1086
  );
1071
1087
  triageSessionListRoute.respond(res, 200, { updated });
1072
1088
  return true;
@@ -1219,7 +1235,7 @@ export async function handleSessions(
1219
1235
  // The viewer's read state, so a client marks a session read on open
1220
1236
  // without the list row (the same rule as `GET /api/sessions`).
1221
1237
  actor.kind === "user" && actor.userId
1222
- ? getSessionReadState(sessionRoot.id, actor.userId)
1238
+ ? getSessionReadState(sessionRoot.id, actor.userId, undefined, actor.readAll)
1223
1239
  : Promise.resolve(null),
1224
1240
  getSessionGroupKey(root),
1225
1241
  ]);
package/src/http/tasks.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  recordTaskProviderIfUnset,
31
31
  resumeTask,
32
32
  settleSupersededTaskDependents,
33
+ skipTask,
33
34
  supersedeTask,
34
35
  TASK_LINEAGE_LIMITS,
35
36
  updateAgentStatusFromCapacity,
@@ -55,6 +56,7 @@ import { can, isRbacEnabled, type RbacPrincipal, type RbacResource } from "../rb
55
56
  import { chatThreadOfContextKey } from "../tasks/context-key";
56
57
  import { TaskCreationBlockedError } from "../tasks/errors";
57
58
  import { createTaskWithSiblingAwareness } from "../tasks/sibling-awareness";
59
+ import { finalizeSkippedTaskReaction, skipReasonFrom } from "../tasks/task-skip";
58
60
  import { guardTerminalTaskResultWrite } from "../tasks/terminal-result-guard";
59
61
  import { createResumeFollowUp, createWorkerTaskFollowUp } from "../tasks/worker-follow-up";
60
62
  import {
@@ -234,7 +236,7 @@ const listTasks = route({
234
236
  pattern: ["api", "tasks"],
235
237
  summary: "List tasks with filters",
236
238
  description:
237
- "Returns tasks with the full `task` text replaced by a bounded `taskPreview` and completion/integration blobs dropped by default — list views only need the preview. Pass `fields=full` to restore the full `AgentTask`, or `fields=timeline` for the narrow shape the dashboard timeline draws. Every shape gives a user caller only tasks of sessions they can read. Fetch a single task in full via `GET /api/tasks/{id}`. `total` (the filtered row count, ignoring limit/offset) is computed only with `includeTotal=true`.",
239
+ "Returns tasks with the full `task` text replaced by a bounded `taskPreview` and completion/integration blobs dropped by default — list views only need the preview. Pass `fields=full` to restore the full `AgentTask`, or `fields=timeline` for the narrow shape the dashboard timeline draws. Every shape gives a user caller only tasks of sessions they can read, unless `scope=all` applies. Fetch a single task in full via `GET /api/tasks/{id}`. `total` (the filtered row count, ignoring limit/offset) is computed only with `includeTotal=true`.",
238
240
  tags: ["Tasks"],
239
241
  query: z.object({
240
242
  /** Single status, or comma-separated list (e.g. "failed,cancelled"). */
@@ -275,6 +277,12 @@ const listTasks = route({
275
277
  fields: z.enum(["full", "slim", "timeline"]).optional(),
276
278
  /** `true` adds `total`, a filtered COUNT(*) that pagers need. Omitted by default. */
277
279
  includeTotal: z.enum(["true", "false"]).optional(),
280
+ scope: z
281
+ .enum(["all"])
282
+ .optional()
283
+ .describe(
284
+ "all: every user's tasks, read-only, for a user with an admin role or session.read.all; ignored for anyone else. The X-Swarm-Session-Scope: all header opts in the same way.",
285
+ ),
278
286
  }),
279
287
  responses: {
280
288
  200: {
@@ -655,11 +663,13 @@ const finishTask = route({
655
663
  path: "/api/tasks/{id}/finish",
656
664
  pattern: ["api", "tasks", null, "finish"],
657
665
  session: { taskParam: "id" },
658
- summary: "Mark task as completed or failed (runner endpoint)",
666
+ summary: "Mark task as completed, failed, or skipped (runner endpoint)",
667
+ description:
668
+ "`skipped` ends a task that is not the caller's to handle. It needs a one-line reason in `failureReason` (or `output`), keeps `output` empty, posts nothing, and creates no follow-up.",
659
669
  tags: ["Tasks"],
660
670
  params: z.object({ id: z.string() }),
661
671
  body: z.object({
662
- status: z.enum(["completed", "failed"]),
672
+ status: z.enum(["completed", "failed", "skipped"]),
663
673
  output: z.string().optional(),
664
674
  failureReason: z.string().optional(),
665
675
  force: z.boolean().optional(),
@@ -669,7 +679,7 @@ const finishTask = route({
669
679
  auth: { apiKey: true, agentId: true },
670
680
  responses: {
671
681
  200: { description: "Task finished", schema: FinishTaskSuccessSchema },
672
- 400: { description: "Invalid status" },
682
+ 400: { description: "Invalid status, or a skip without a reason" },
673
683
  403: { description: "Not assigned to this agent" },
674
684
  404: { description: "Task not found" },
675
685
  409: {
@@ -993,7 +1003,9 @@ export async function handleTasks(
993
1003
 
994
1004
  // Every shape carries task text, so a user sees only sessions they can
995
1005
  // read, and `total` counts the same rows.
996
- const actor = await resolveSessionActor(req, myAgentId);
1006
+ const actor = await resolveSessionActor(req, myAgentId, {
1007
+ allUsers: parsed.query.scope === "all",
1008
+ });
997
1009
  const filters = {
998
1010
  status,
999
1011
  agentId: parsed.query.agentId || undefined,
@@ -1014,7 +1026,7 @@ export async function handleTasks(
1014
1026
  orderBy: parsed.query.orderBy,
1015
1027
  limit: parsed.query.limit,
1016
1028
  offset: parsed.query.offset,
1017
- readableBy: actor.kind === "user" ? { userId: actor.userId } : undefined,
1029
+ readableBy: readableByFor(actor),
1018
1030
  };
1019
1031
  // List responses default to slim (full `task` text → bounded `taskPreview`,
1020
1032
  // heavy blobs dropped); `?fields=full` restores the full `AgentTask`.
@@ -1771,7 +1783,23 @@ export async function handleTasks(
1771
1783
  return { error: "Task is assigned to another agent", status: 403 };
1772
1784
  }
1773
1785
 
1774
- const terminalResultGuard = await guardTerminalTaskResultWrite(task, parsed.body);
1786
+ const skipReason =
1787
+ parsed.body.status === "skipped"
1788
+ ? skipReasonFrom(parsed.body.failureReason, parsed.body.output)
1789
+ : undefined;
1790
+ if (parsed.body.status === "skipped" && !skipReason) {
1791
+ return {
1792
+ error: 'Status "skipped" needs a one-line reason in failureReason',
1793
+ status: 400,
1794
+ };
1795
+ }
1796
+
1797
+ const terminalResultGuard = await guardTerminalTaskResultWrite(
1798
+ task,
1799
+ parsed.body.status === "skipped"
1800
+ ? { status: "skipped", failureReason: skipReason, force: parsed.body.force }
1801
+ : parsed.body,
1802
+ );
1775
1803
  if (terminalResultGuard.handled) {
1776
1804
  const { handled: _handled, ...guardResult } = terminalResultGuard;
1777
1805
  return { ...guardResult, alreadyFinished: true };
@@ -1797,6 +1825,12 @@ export async function handleTasks(
1797
1825
  return { error: "Failed to complete task", status: 500 };
1798
1826
  }
1799
1827
  updatedTask = result;
1828
+ } else if (parsed.body.status === "skipped") {
1829
+ const result = await skipTask(parsed.params.id, skipReason!);
1830
+ if (!result) {
1831
+ return { error: "Failed to mark task as skipped", status: 500 };
1832
+ }
1833
+ updatedTask = result;
1800
1834
  } else {
1801
1835
  const result = await failTask(
1802
1836
  parsed.params.id,
@@ -1829,7 +1863,9 @@ export async function handleTasks(
1829
1863
  return true;
1830
1864
  }
1831
1865
 
1832
- if (result.task && isFreshFinishResult(result)) {
1866
+ if (result.task && isFreshFinishResult(result) && parsed.body.status === "skipped") {
1867
+ finalizeSkippedTaskReaction(result.task, "tasks.finish");
1868
+ } else if (result.task && isFreshFinishResult(result)) {
1833
1869
  const finishEventId = parsed.body.status === "completed" ? "completed" : "failed";
1834
1870
 
1835
1871
  ensure({
@@ -1854,7 +1890,7 @@ export async function handleTasks(
1854
1890
  try {
1855
1891
  const followUp = await createWorkerTaskFollowUp({
1856
1892
  task: result.task,
1857
- status: parsed.body.status,
1893
+ status: finishEventId,
1858
1894
  output: parsed.body.output,
1859
1895
  failureReason: parsed.body.failureReason,
1860
1896
  });
@@ -2090,6 +2126,9 @@ export async function handleTasks(
2090
2126
  // step in `superseded` if the engine expects `failed`.
2091
2127
  if (task.workflowRunStepId != null) {
2092
2128
  const failed = await failTask(parsed.params.id, SUPERSEDED_WORKFLOW_TASK_REASON);
2129
+ if (task.agentId) {
2130
+ await updateAgentStatusFromCapacity(task.agentId);
2131
+ }
2093
2132
  ensure({
2094
2133
  id: "task.workflow_step_failed_on_supersede",
2095
2134
  flow: "task",
@@ -2132,6 +2171,11 @@ export async function handleTasks(
2132
2171
  return true;
2133
2172
  }
2134
2173
 
2174
+ // Cancel and finish recompute the agent status; a superseded task frees its slot too.
2175
+ if (task.agentId) {
2176
+ await updateAgentStatusFromCapacity(task.agentId);
2177
+ }
2178
+
2135
2179
  // Parent is now superseded. Create the resume child.
2136
2180
  const followUp = await createResumeFollowUp({
2137
2181
  parentId: parsed.params.id,
package/src/http/users.ts CHANGED
@@ -78,6 +78,7 @@ import { resolveAppUrl, resolveMcpBaseUrl } from "./config-values";
78
78
  import { clientIp, createIpRateLimiter } from "./ip-rate-limit";
79
79
  import { getOperatorActor } from "./operator-actor";
80
80
  import { route } from "./route-def";
81
+ import { resolveSessionActor } from "./session-access";
81
82
  import { ensureRoleManager } from "./user-roles";
82
83
  import { jsonError } from "./utils";
83
84
 
@@ -197,6 +198,11 @@ const whoamiRoute = route({
197
198
  roles: z.array(z.string()),
198
199
  })
199
200
  .optional(),
201
+ // Whether this request may opt in to the all-users read scope
202
+ // (`scope=all`, `X-Swarm-Session-Scope: all`). On the operator key it
203
+ // answers for the user picked in `X-Swarm-User-Id`. Absent on older
204
+ // servers.
205
+ sessionReadAll: z.boolean().optional(),
200
206
  }),
201
207
  },
202
208
  401: { description: "Unauthorized" },
@@ -251,6 +257,7 @@ const createUserRoute = route({
251
257
  },
252
258
  400: { description: "Validation error" },
253
259
  401: { description: "Unauthorized" },
260
+ 409: { description: "A user with this email already exists (user_exists)" },
254
261
  },
255
262
  auth: { apiKey: true },
256
263
  });
@@ -624,9 +631,10 @@ const addIdentityRoute = route({
624
631
  description: "Updated identity list",
625
632
  schema: z.object({ identities: z.array(UserIdentityLinkSchema) }),
626
633
  },
627
- 400: { description: "Validation error or PK collision" },
634
+ 400: { description: "Validation error" },
628
635
  401: { description: "Unauthorized" },
629
636
  404: { description: "User not found" },
637
+ 409: { description: "The (kind, externalId) identity is already linked (identity_taken)" },
630
638
  },
631
639
  auth: { apiKey: true },
632
640
  });
@@ -651,6 +659,15 @@ const deleteIdentityRoute = route({
651
659
 
652
660
  // ─── Helpers ─────────────────────────────────────────────────────────────────
653
661
 
662
+ /** True when `err` is a SQLite UNIQUE violation whose message names `target` (e.g. `users.email`). */
663
+ function isUniqueViolation(err: unknown, target: string): boolean {
664
+ return (
665
+ err instanceof Error &&
666
+ err.message.includes("UNIQUE constraint") &&
667
+ err.message.includes(target)
668
+ );
669
+ }
670
+
654
671
  const UNMAPPED_KINDS = [
655
672
  "slack",
656
673
  "github",
@@ -822,6 +839,8 @@ export async function handleUsers(
822
839
  const parsed = await whoamiRoute.parse(req, res, pathSegments, queryParams);
823
840
  if (!parsed) return true;
824
841
  const user = authUser(getRequestAuth(req));
842
+ const scopeActor = await resolveSessionActor(req, undefined, { allUsers: true });
843
+ const sessionReadAll = scopeActor.kind === "bypass" || scopeActor.readAll === true;
825
844
  if (user) {
826
845
  const [grant, roles] = await Promise.all([getUserGrant(user.id), listUserRoles(user.id)]);
827
846
  const grantsAll = !isRbacEnabled() || grant.grantsAll;
@@ -833,12 +852,14 @@ export async function handleUsers(
833
852
  verbs: grantsAll ? [] : [...grant.verbs].sort(),
834
853
  roles: roles.map((role) => role.name),
835
854
  },
855
+ sessionReadAll,
836
856
  });
837
857
  } else {
838
858
  whoamiRoute.respond(res, 200, {
839
859
  kind: "operator",
840
860
  user: null,
841
861
  grants: { grantsAll: true, verbs: [], roles: [] },
862
+ sessionReadAll,
842
863
  });
843
864
  }
844
865
  return true;
@@ -877,6 +898,10 @@ export async function handleUsers(
877
898
  const composed = await composeUser(user.id);
878
899
  createUserRoute.respond(res, 200, { user: composed });
879
900
  } catch (err) {
901
+ if (isUniqueViolation(err, "users.email")) {
902
+ jsonError(res, "user_exists", 409);
903
+ return true;
904
+ }
880
905
  jsonError(res, err instanceof Error ? err.message : "Failed to create user", 500);
881
906
  }
882
907
  return true;
@@ -1249,6 +1274,10 @@ export async function handleUsers(
1249
1274
  identities: await getUserIdentities(parsed.params.id),
1250
1275
  });
1251
1276
  } catch (err) {
1277
+ if (isUniqueViolation(err, "user_external_ids")) {
1278
+ jsonError(res, "identity_taken", 409);
1279
+ return true;
1280
+ }
1252
1281
  jsonError(res, err instanceof Error ? err.message : "Failed to link identity", 400);
1253
1282
  }
1254
1283
  return true;
package/src/http/utils.ts CHANGED
@@ -136,7 +136,8 @@ export function setCorsHeaders(req: IncomingMessage, res: ServerResponse) {
136
136
  const askedHeaders = Array.isArray(reqHeaders) ? reqHeaders.join(", ") : reqHeaders;
137
137
  res.setHeader(
138
138
  "Access-Control-Allow-Headers",
139
- askedHeaders ?? "Authorization, Content-Type, X-Agent-ID, X-Requested-With, X-Swarm-User-Id",
139
+ askedHeaders ??
140
+ "Authorization, Content-Type, X-Agent-ID, X-Requested-With, X-Swarm-User-Id, X-Swarm-Session-Scope",
140
141
  );
141
142
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
142
143
  res.setHeader("Access-Control-Expose-Headers", "Content-Type, Content-Length, ETag, Location");
@@ -430,6 +430,7 @@ const retryWorkflowRunRoute = route({
430
430
  responses: {
431
431
  200: { description: "Retry started", schema: SuccessResponseSchema },
432
432
  400: { description: "Cannot retry" },
433
+ 404: { description: "Run not found" },
433
434
  },
434
435
  });
435
436
 
@@ -788,13 +789,12 @@ export async function handleWorkflows(
788
789
  res.end();
789
790
  return true;
790
791
  }
791
- jsonError(
792
- res,
793
- result.reason === "patch"
794
- ? result.errors.join("; ")
795
- : `Invalid definition: ${result.errors.join("; ")}`,
796
- 400,
797
- );
792
+ // The only patch operation here is one update, so a patch error means the node is absent.
793
+ if (result.reason === "patch") {
794
+ jsonError(res, result.errors.join("; "), 404);
795
+ return true;
796
+ }
797
+ jsonError(res, `Invalid definition: ${result.errors.join("; ")}`, 400);
798
798
  return true;
799
799
  }
800
800
  patchWorkflowNodeRoute.respond(res, 200, await withSaveWarnings(result.workflow));
@@ -1114,6 +1114,10 @@ export async function handleWorkflows(
1114
1114
  if (retryWorkflowRunRoute.match(req.method, pathSegments)) {
1115
1115
  const parsed = await retryWorkflowRunRoute.parse(req, res, pathSegments, queryParams);
1116
1116
  if (!parsed) return true;
1117
+ if (!(await getWorkflowRunSummary(parsed.params.id))) {
1118
+ jsonError(res, `Workflow run not found: ${parsed.params.id}`, 404);
1119
+ return true;
1120
+ }
1117
1121
  try {
1118
1122
  await retryFailedRun(parsed.params.id, getExecutorRegistry());
1119
1123
  } catch (err) {
@@ -312,6 +312,7 @@ registerTemplate({
312
312
 
313
313
  The engine posts the thread tree and the outcome card. You post at most one message per task, and only when you have something the card will not carry. Progress, receipts, and relayed worker output stay out of Slack.
314
314
  The outcome card publishes your \`output\` verbatim. Keep free-text \`output\` under 120 words by default, with the exceptions in How you write.
315
+ A thread message addressed to someone else, or not yours to handle: end with \`store-progress\` status \`skipped\` and a one-line \`failureReason\`. It posts nothing to the thread. Never skip an explicit @mention of you or work assigned to you.
315
316
  A Slack task from an unknown user: register them with \`manage-user\` first.
316
317
  You MUST use the \`slack-interaction\` skill before you post to Slack.
317
318
  Call \`slack-leave-thread\` with your taskId when a thread no longer needs you: people are talking among themselves, someone tells you to stop or back off, or the thread's work is done. The swarm then ignores the thread until someone @mentions it. Leave quietly, with no goodbye message.
@@ -423,7 +423,7 @@ const copilotTargetProfile: AcpTargetProfile = {
423
423
  },
424
424
  };
425
425
 
426
- /** Qwen Code's `--auth-type` choices (0.26.4). `qwen-oauth` needs a browser, so it is left out. */
426
+ /** Qwen Code's `--auth-type` choices (0.26.5). `qwen-oauth` needs a browser, so it is left out. */
427
427
  const QWEN_AUTH_TYPES = ["openai", "openai-responses", "anthropic", "gemini", "vertex-ai"] as const;
428
428
 
429
429
  // Qwen Code is a Gemini CLI fork: QWEN_SYSTEM_MD replaces its built-in prompt
@@ -45,7 +45,7 @@ import type {
45
45
  * default; the image installs exactly this version and the per-task settings
46
46
  * set `amp.updates.mode: "disabled"`. Bump it deliberately, with a live run.
47
47
  */
48
- export const AMP_PACKAGE = "@ampcode/cli@0.0.1793450357-gd44904";
48
+ export const AMP_PACKAGE = "@ampcode/cli@0.0.1793534443-ga508b6";
49
49
 
50
50
  /** MCP server name. Amp exposes its tools as `agent_swarm` / `store_progress` (dashes become underscores). */
51
51
  const AMP_MCP_SERVER_NAME = "agent-swarm";
@@ -978,7 +978,7 @@ export class CodexSession implements ProviderSession {
978
978
  private readonly thread: CodexThread;
979
979
  private readonly config: ProviderSessionConfig;
980
980
  private readonly resolvedModel: string;
981
- private readonly contextWindow: number;
981
+ private contextWindow: number;
982
982
  private readonly skillsDir: string;
983
983
  private readonly summarizeDeps: SummarizeSessionForCodexDeps;
984
984
  private readonly listeners: Array<(event: ProviderEvent) => void> = [];
@@ -1459,7 +1459,14 @@ export class CodexSession implements ProviderSession {
1459
1459
  this.accountUsage(event.usage);
1460
1460
  break;
1461
1461
  case "context.updated":
1462
- this.emitContextUsage(event.usage, event.contextWindow ?? this.contextWindow);
1462
+ if (
1463
+ event.contextWindow != null &&
1464
+ Number.isFinite(event.contextWindow) &&
1465
+ event.contextWindow > 0
1466
+ ) {
1467
+ this.contextWindow = event.contextWindow;
1468
+ }
1469
+ this.emitContextUsage(event.usage, this.contextWindow);
1463
1470
  // Codex input tokens already include the cached read and write subsets.
1464
1471
  void this.observeContextBound(event.usage.input_tokens);
1465
1472
  break;
@@ -1,12 +1,42 @@
1
1
  import { _fetchHolder, CLIENT_ID, exchangeAuthorizationCode, getAccountId } from "./flow.js";
2
2
  import type { CodexOAuthCredentials } from "./types.js";
3
3
 
4
- const DEVICE_CODE_URL = "https://auth.openai.com/api/accounts/deviceauth/usercode";
5
- const DEVICE_TOKEN_URL = "https://auth.openai.com/api/accounts/deviceauth/token";
6
- const DEVICE_REDIRECT_URI = "https://auth.openai.com/deviceauth/callback";
4
+ const DEFAULT_DEVICE_BASE_URL = "https://auth.openai.com";
7
5
  const UPSTREAM_TIMEOUT_MS = 15_000;
8
6
 
9
- export const CODEX_DEVICE_VERIFICATION_URL = "https://auth.openai.com/codex/device";
7
+ /**
8
+ * Origin of the device login endpoints. Read on every call, so a config reload
9
+ * can point the login at a stand-in (the black-box suite runs one).
10
+ */
11
+ /**
12
+ * `CODEX_OAUTH_DEVICE_BASE_URL` is a test knob for the black-box suite. It is an env-only
13
+ * reserved config key (swarm_config writes refuse it) and only a loopback origin is
14
+ * honoured: the device login carries ChatGPT credentials, so a redirect to any other host
15
+ * must be impossible. Anything else falls back to auth.openai.com.
16
+ */
17
+ export function resolveCodexDeviceBaseUrl(raw: string | undefined): string {
18
+ const configured = raw?.trim();
19
+ if (!configured) return DEFAULT_DEVICE_BASE_URL;
20
+ try {
21
+ const url = new URL(configured);
22
+ const loopback =
23
+ url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
24
+ if (url.protocol === "http:" && loopback) return url.origin;
25
+ } catch {
26
+ // fall through
27
+ }
28
+ console.warn("[codex-oauth] CODEX_OAUTH_DEVICE_BASE_URL must be a loopback http origin; ignored");
29
+ return DEFAULT_DEVICE_BASE_URL;
30
+ }
31
+
32
+ function deviceBaseUrl(): string {
33
+ return resolveCodexDeviceBaseUrl(process.env.CODEX_OAUTH_DEVICE_BASE_URL);
34
+ }
35
+
36
+ /** The page where the user enters the code. Read on every call, like the other URLs. */
37
+ export function codexDeviceVerificationUrl(): string {
38
+ return `${deviceBaseUrl()}/codex/device`;
39
+ }
10
40
 
11
41
  export class DeviceCodeNotEnabledError extends Error {}
12
42
 
@@ -31,16 +61,19 @@ function parseInterval(value: unknown): number {
31
61
  }
32
62
 
33
63
  export async function requestDeviceCode(): Promise<DeviceCode> {
34
- const response = await _fetchHolder.current(DEVICE_CODE_URL, {
35
- method: "POST",
36
- headers: {
37
- "Content-Type": "application/json",
38
- originator: "agent-swarm",
39
- "User-Agent": "agent-swarm",
64
+ const response = await _fetchHolder.current(
65
+ `${deviceBaseUrl()}/api/accounts/deviceauth/usercode`,
66
+ {
67
+ method: "POST",
68
+ headers: {
69
+ "Content-Type": "application/json",
70
+ originator: "agent-swarm",
71
+ "User-Agent": "agent-swarm",
72
+ },
73
+ body: JSON.stringify({ client_id: CLIENT_ID }),
74
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
40
75
  },
41
- body: JSON.stringify({ client_id: CLIENT_ID }),
42
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
43
- });
76
+ );
44
77
 
45
78
  if (response.status === 404) throw new DeviceCodeNotEnabledError();
46
79
  if (!response.ok) throw new Error(`Device code request failed with HTTP ${response.status}`);
@@ -63,7 +96,7 @@ export async function pollDeviceToken(
63
96
  deviceAuthId: string,
64
97
  userCode: string,
65
98
  ): Promise<DeviceTokenPollResult> {
66
- const response = await _fetchHolder.current(DEVICE_TOKEN_URL, {
99
+ const response = await _fetchHolder.current(`${deviceBaseUrl()}/api/accounts/deviceauth/token`, {
67
100
  method: "POST",
68
101
  headers: {
69
102
  "Content-Type": "application/json",
@@ -95,8 +128,9 @@ export async function exchangeDeviceAuthorizationCode(
95
128
  const token = await exchangeAuthorizationCode(
96
129
  authorizationCode,
97
130
  codeVerifier,
98
- DEVICE_REDIRECT_URI,
131
+ `${deviceBaseUrl()}/deviceauth/callback`,
99
132
  AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
133
+ `${deviceBaseUrl()}/oauth/token`,
100
134
  );
101
135
  if (token.type !== "success") return null;
102
136
  const accountId = getAccountId(token.access);