@desplega.ai/agent-swarm 2.3.0 → 2.4.0

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 (247) hide show
  1. package/README.md +1 -0
  2. package/dist/{acp-adapter-v85a2bqy.js → acp-adapter-kedstxx6.js} +6 -6
  3. package/dist/{actions-zgcxfspj.js → actions-vget6r1k.js} +18 -16
  4. package/dist/{amp-adapter-jw9xfz42.js → amp-adapter-xeb5mktv.js} +2 -2
  5. package/dist/{app-4e1s4675.js → app-mqap8t8m.js} +3 -3
  6. package/dist/{assistant-v238n9dk.js → assistant-h0gv97mv.js} +20 -18
  7. package/dist/{boot-reembed-p666cw5n.js → boot-reembed-qr8a894z.js} +1 -1
  8. package/dist/{boot-reembed-w6pm64j4.js → boot-reembed-rj85jjhw.js} +1 -1
  9. package/dist/{boot-scrub-sweep-jcyjagn3.js → boot-scrub-sweep-eyfvn6v9.js} +3 -3
  10. package/dist/{boot-seeds-gbedmamp.js → boot-seeds-xs9a8dx1.js} +4 -4
  11. package/dist/{claude-adapter-q7wspzt8.js → claude-adapter-bm23cye7.js} +5 -5
  12. package/dist/{claude-managed-adapter-n7ahjyx6.js → claude-managed-adapter-1mwrsm9d.js} +2 -2
  13. package/dist/{claude-managed-setup-wza784fb.js → claude-managed-setup-gkfgks4j.js} +1 -1
  14. package/dist/{claude-sdk-session-yf400ptr.js → claude-sdk-session-apb4ypz3.js} +5 -5
  15. package/dist/cli-02vhhssk.js +848 -0
  16. package/dist/{cli-4ync7m60.js → cli-0ebey9hg.js} +1 -1
  17. package/dist/{cli-665j3feb.js → cli-0xk505e8.js} +1 -1
  18. package/dist/{cli-30m5q8mc.js → cli-1cevz46c.js} +5 -5
  19. package/dist/{cli-gzvb3d4a.js → cli-1jx0srjt.js} +3 -3
  20. package/dist/{cli-zj4d6afs.js → cli-1pa3rz69.js} +21 -6
  21. package/dist/{cli-fhvqt2fp.js → cli-2rwet3r7.js} +1 -1
  22. package/dist/{cli-azs9bhc5.js → cli-3wjs22x3.js} +2 -2
  23. package/dist/{cli-dxwh4j32.js → cli-4fhyq711.js} +45 -36
  24. package/dist/{cli-yv3n83x8.js → cli-5ff2sjyt.js} +1 -1
  25. package/dist/{cli-6vcyw6v7.js → cli-5s5hx57y.js} +5 -3
  26. package/dist/{cli-hz64bcnj.js → cli-6ftrrwm1.js} +9 -371
  27. package/dist/{cli-zes4tsbb.js → cli-8b9wvjps.js} +1 -1
  28. package/dist/cli-8cxkw1f5.js +382 -0
  29. package/dist/{cli-4s1kqrqg.js → cli-8rwvksbc.js} +2 -2
  30. package/dist/{cli-e09hj50q.js → cli-8wkb09q5.js} +11 -11
  31. package/dist/{cli-yv0vgscc.js → cli-a1esmmee.js} +13 -2
  32. package/dist/{cli-4hmaheb6.js → cli-avmqhatn.js} +7 -7
  33. package/dist/{cli-g6p7c2my.js → cli-b80a1100.js} +1 -1
  34. package/dist/{cli-tr24eeny.js → cli-bfc3k1x5.js} +3 -3
  35. package/dist/{cli-ka01m5rb.js → cli-bhwa8rzc.js} +13 -11
  36. package/dist/{cli-8cvvytad.js → cli-bn26xbcs.js} +2 -2
  37. package/dist/{cli-k28p6xh7.js → cli-c8fwpgqb.js} +1 -1
  38. package/dist/{cli-rc3r0bnh.js → cli-ccn0eybf.js} +1 -1
  39. package/dist/{cli-9td5ss65.js → cli-dsgj3e7a.js} +2 -2
  40. package/dist/{cli-a17tzmn0.js → cli-ecshf504.js} +2 -2
  41. package/dist/{cli-d43xqzbe.js → cli-eqgfs202.js} +1 -1
  42. package/dist/{cli-ppapy34w.js → cli-f3nx1h8z.js} +2 -2
  43. package/dist/{cli-ea7chd26.js → cli-ffbrkh1r.js} +74 -35
  44. package/dist/{cli-xgn4rwyv.js → cli-kk2r80n5.js} +4 -4
  45. package/dist/{cli-hn3pftj2.js → cli-kz116kvw.js} +3 -3
  46. package/dist/{cli-1v8w782f.js → cli-mvg2hf8p.js} +4 -4
  47. package/dist/{cli-5d1m1qca.js → cli-mz1ezzzh.js} +1 -1
  48. package/dist/{cli-jhmjwqcg.js → cli-nme7wery.js} +6 -6
  49. package/dist/{cli-65q70v2v.js → cli-nrrg0fvy.js} +18 -4
  50. package/dist/{cli-8jtrekpy.js → cli-p1m2b6gc.js} +7 -7
  51. package/dist/{cli-re4wkbzx.js → cli-rg7ntypm.js} +328 -47
  52. package/dist/{cli-fp4xbw07.js → cli-rsd7ga7v.js} +10 -8
  53. package/dist/{cli-etvn5ej2.js → cli-sppc0cmw.js} +1 -1
  54. package/dist/{cli-qrwp40st.js → cli-tg9ksbn8.js} +1 -1
  55. package/dist/{cli-6p7ddg72.js → cli-tgvpmnwz.js} +2 -2
  56. package/dist/{cli-q1812jbw.js → cli-tj4j2ts4.js} +6 -6
  57. package/dist/{cli-kqypty34.js → cli-ttaz6c7m.js} +2 -2
  58. package/dist/{cli-w7z94e6c.js → cli-tx00c0h6.js} +4 -2
  59. package/dist/{cli-4g629sgr.js → cli-wrv09v7q.js} +20 -1
  60. package/dist/{cli-cby329ny.js → cli-wyrr38xm.js} +2 -2
  61. package/dist/{cli-y3dvz6ge.js → cli-x1p5dhq2.js} +3 -3
  62. package/dist/{cli-8qsx817b.js → cli-x719j3vs.js} +219 -629
  63. package/dist/{cli-9e9kjqsj.js → cli-xfe63zx3.js} +1 -1
  64. package/dist/{cli-wtg6edvd.js → cli-ywyrffff.js} +1 -1
  65. package/dist/{cli-0rh20bp3.js → cli-zvze9rbm.js} +1 -1
  66. package/dist/cli.js +14 -14
  67. package/dist/{codex-adapter-nhjj2veb.js → codex-adapter-pp2gq8gr.js} +3 -3
  68. package/dist/{codex-hook-x6tm6y5m.js → codex-hook-qwzccd64.js} +1 -1
  69. package/dist/{codex-session-runner-6hggrjbx.js → codex-session-runner-0vzn09t8.js} +3 -3
  70. package/dist/{commands-mrw1ph2w.js → commands-psqhkttb.js} +2 -2
  71. package/dist/{controller-pt1zam5w.js → controller-t20vz2k8.js} +2 -2
  72. package/dist/{controllers-connect-ymw5541d.js → controllers-connect-gkxmqw9d.js} +24 -20
  73. package/dist/{cursor-adapter-cf4zh5x0.js → cursor-adapter-3v542qe5.js} +1 -1
  74. package/dist/{db-hy80219q.js → db-2xbyenjr.js} +2 -2
  75. package/dist/{db-hhpy6m4x.js → db-nc1rd869.js} +3 -2
  76. package/dist/{dispatcher-6pdjtkr1.js → dispatcher-ewceb8ts.js} +17 -15
  77. package/dist/{dsh-adapter-fbx06re2.js → dsh-adapter-75xwh78t.js} +1 -1
  78. package/dist/{easter-egg-3d-6hg2r942.js → easter-egg-3d-xsc47jwf.js} +1 -1
  79. package/dist/{execute-bcqc69a5.js → execute-gzmw1mnw.js} +1 -1
  80. package/dist/{external-channel-j6vb6ya1.js → external-channel-a5dsmxn4.js} +2 -2
  81. package/dist/{google-generative-ai-phpmwxvg.js → google-generative-ai-bmq8gkf3.js} +1 -1
  82. package/dist/{google-vertex-es9ybgdy.js → google-vertex-b1rvp52s.js} +1 -1
  83. package/dist/{grok-adapter-1193sprp.js → grok-adapter-vj88xr23.js} +7 -7
  84. package/dist/handlers-zbs90bny.js +39 -0
  85. package/dist/{heartbeat-h1w1ktce.js → heartbeat-t2m9r3wa.js} +20 -18
  86. package/dist/{hook-skrbja18.js → hook-8femx1bg.js} +4 -4
  87. package/dist/{hook-ejja4bpe.js → hook-xa677f8r.js} +5 -5
  88. package/dist/{http-mzh41mfj.js → http-xpmmq028.js} +868 -253
  89. package/dist/{index-vjn3wbzf.js → index-8pwc1jc8.js} +17 -15
  90. package/dist/{index-epr2gnbw.js → index-cdzyfrsp.js} +1 -1
  91. package/dist/{index-xmmkyx82.js → index-dg2tmj99.js} +17 -15
  92. package/dist/index-nxa6me0q.js +41 -0
  93. package/dist/{index-6rmnn89d.js → index-s7ckdajq.js} +9 -9
  94. package/dist/{index-wgsw9xcz.js → index-syztqdt6.js} +1 -1
  95. package/dist/{index-x0q2a4f9.js → index-ysd45kgc.js} +1 -1
  96. package/dist/{index-g909y089.js → index-zgvqzjsw.js} +8 -8
  97. package/dist/{keepalive-4djvbm2j.js → keepalive-3nr4st3r.js} +3 -3
  98. package/dist/{lead-61kqp604.js → lead-td8h2sfn.js} +33 -31
  99. package/dist/{maintenance-f3xhnjsm.js → maintenance-verwpe2c.js} +1 -1
  100. package/dist/{oauth-refresh-sweep-fpd6x6rw.js → oauth-refresh-sweep-9q2t0y3q.js} +2 -2
  101. package/dist/{onboard-196tjgyn.js → onboard-aytqedmq.js} +2 -2
  102. package/dist/{opencode-adapter-eeesgfqk.js → opencode-adapter-f4hryjny.js} +4 -4
  103. package/dist/{otel-impl-g8fh4c21.js → otel-impl-hckw4wt1.js} +1 -1
  104. package/dist/{pi-mono-adapter-zasp3ze3.js → pi-mono-adapter-hxby0ce1.js} +6 -6
  105. package/dist/{pricing-refresh-sdcf5yaz.js → pricing-refresh-5nvme3sm.js} +3 -3
  106. package/dist/{rbac-roles-bsp5657v.js → rbac-roles-pd8c26m1.js} +5 -3
  107. package/dist/{rbac-roles-2x4g1wb5.js → rbac-roles-vbpy21mg.js} +2 -2
  108. package/dist/{render-v2-0pyb39bb.js → render-v2-7nqgvk2q.js} +3 -3
  109. package/dist/{resume-a86tkj6r.js → resume-b6djcj3c.js} +6 -6
  110. package/dist/{runtime-ar8310ba.js → runtime-txrxc9za.js} +1 -1
  111. package/dist/session-access-fc3f9y12.js +25 -0
  112. package/dist/{setup-ypbzcapd.js → setup-n39szm6b.js} +1 -1
  113. package/dist/{virtual-modules-wzk6jf3a.js → virtual-modules-wyp2k6z3.js} +2 -2
  114. package/dist/{work-objects-yjp8de12.js → work-objects-jem2fre0.js} +20 -18
  115. package/dist/{worker-4ptnn1ge.js → worker-wr6xgfr2.js} +33 -31
  116. package/openapi.json +844 -110
  117. package/package.json +1 -1
  118. package/src/apps/action-caller.ts +6 -0
  119. package/src/apps/script-types.ts +16 -3
  120. package/src/be/db/active-sessions.ts +5 -0
  121. package/src/be/db/session-visibility.ts +29 -0
  122. package/src/be/db/tasks/read.ts +61 -3
  123. package/src/be/db/tasks/write.ts +15 -6
  124. package/src/be/db.ts +92 -33
  125. package/src/be/events.ts +11 -0
  126. package/src/be/migrations/230_session_shares.sql +23 -0
  127. package/src/be/rbac-roles.ts +2 -0
  128. package/src/be/session-shares.ts +244 -0
  129. package/src/be/swarm-config-guard.ts +23 -2
  130. package/src/commands/runner.ts +11 -0
  131. package/src/http/active-sessions.ts +13 -2
  132. package/src/http/agents.ts +10 -3
  133. package/src/http/all-routes.ts +1 -0
  134. package/src/http/api-keys.ts +3 -1
  135. package/src/http/approval-requests.ts +2 -1
  136. package/src/http/apps.ts +36 -11
  137. package/src/http/config.ts +3 -0
  138. package/src/http/context.ts +2 -0
  139. package/src/http/core.ts +39 -2
  140. package/src/http/events.ts +6 -2
  141. package/src/http/favorite-owner.ts +1 -1
  142. package/src/http/fs.ts +38 -3
  143. package/src/http/index.ts +3 -1
  144. package/src/http/memory.ts +3 -1
  145. package/src/http/ranking.ts +367 -0
  146. package/src/http/realtime.ts +26 -21
  147. package/src/http/route-def.ts +77 -11
  148. package/src/http/script-runs.ts +2 -1
  149. package/src/http/scripts.ts +8 -0
  150. package/src/http/session-access.ts +179 -0
  151. package/src/http/session-data.ts +10 -2
  152. package/src/http/sessions.ts +212 -12
  153. package/src/http/stats.ts +7 -3
  154. package/src/http/tasks.ts +83 -7
  155. package/src/http/used-by.ts +11 -3
  156. package/src/prompts/session-templates.ts +3 -1
  157. package/src/providers/amp-adapter.ts +1 -1
  158. package/src/ranking/telemetry-ranking.ts +147 -0
  159. package/src/ranking/usage.ts +57 -0
  160. package/src/rbac/admission.ts +22 -7
  161. package/src/rbac/legacy-policy.ts +2 -0
  162. package/src/rbac/permissions.ts +9 -0
  163. package/src/realtime/auth.ts +69 -0
  164. package/src/realtime/tickets.ts +4 -1
  165. package/src/realtime/transport.ts +77 -9
  166. package/src/slack/blocks.ts +18 -0
  167. package/src/slack/dm.ts +29 -0
  168. package/src/telemetry-contract/EVENTS.md +3 -0
  169. package/src/telemetry-contract/SOURCE.json +37 -4
  170. package/src/telemetry-contract/catalog.json +69 -0
  171. package/src/telemetry-contract/ranking/fixtures/expected.json +30 -0
  172. package/src/telemetry-contract/ranking/fixtures/invalid/bad-category.json +11 -0
  173. package/src/telemetry-contract/ranking/fixtures/invalid/bad-claim.json +11 -0
  174. package/src/telemetry-contract/ranking/fixtures/invalid/blank-description.json +11 -0
  175. package/src/telemetry-contract/ranking/fixtures/invalid/blank-name.json +11 -0
  176. package/src/telemetry-contract/ranking/fixtures/invalid/description-too-long.json +11 -0
  177. package/src/telemetry-contract/ranking/fixtures/invalid/domain-uppercase.json +11 -0
  178. package/src/telemetry-contract/ranking/fixtures/invalid/domain-with-scheme.json +11 -0
  179. package/src/telemetry-contract/ranking/fixtures/invalid/domain-with-www.json +11 -0
  180. package/src/telemetry-contract/ranking/fixtures/invalid/http-source-url.json +11 -0
  181. package/src/telemetry-contract/ranking/fixtures/invalid/missing-description.json +10 -0
  182. package/src/telemetry-contract/ranking/fixtures/invalid/missing-version.json +10 -0
  183. package/src/telemetry-contract/ranking/fixtures/invalid/name-not-string.json +11 -0
  184. package/src/telemetry-contract/ranking/fixtures/invalid/name-too-long.json +11 -0
  185. package/src/telemetry-contract/ranking/fixtures/invalid/not-object.json +1 -0
  186. package/src/telemetry-contract/ranking/fixtures/invalid/null.json +1 -0
  187. package/src/telemetry-contract/ranking/fixtures/invalid/other-with-subcategory.json +11 -0
  188. package/src/telemetry-contract/ranking/fixtures/invalid/oversize.json +1 -0
  189. package/src/telemetry-contract/ranking/fixtures/invalid/short-claim.json +11 -0
  190. package/src/telemetry-contract/ranking/fixtures/invalid/subcategory-other-category.json +11 -0
  191. package/src/telemetry-contract/ranking/fixtures/invalid/trailing-data.json +1 -0
  192. package/src/telemetry-contract/ranking/fixtures/invalid/unknown-field.json +12 -0
  193. package/src/telemetry-contract/ranking/fixtures/invalid/unsupported-version.json +11 -0
  194. package/src/telemetry-contract/ranking/fixtures/invalid/updated-at-not-date.json +11 -0
  195. package/src/telemetry-contract/ranking/fixtures/invalid/updated-at-offset.json +11 -0
  196. package/src/telemetry-contract/ranking/fixtures/invalid/wrong-case-field.json +11 -0
  197. package/src/telemetry-contract/ranking/fixtures/valid/category-without-subcategory.json +11 -0
  198. package/src/telemetry-contract/ranking/fixtures/valid/full.json +11 -0
  199. package/src/telemetry-contract/ranking/fixtures/valid/minimal.json +11 -0
  200. package/src/telemetry-contract/ranking/fixtures/valid/padded-text.json +11 -0
  201. package/src/telemetry-contract/ranking/fixtures/valid/unicode-name.json +11 -0
  202. package/src/telemetry-contract/ranking/listing.v1.schema.json +61 -0
  203. package/src/telemetry-contract/ranking/taxonomy.json +8 -0
  204. package/src/telemetry-contract/ranking-taxonomy.gen.ts +11 -0
  205. package/src/telemetry-contract/types.gen.ts +708 -1
  206. package/src/telemetry.ts +26 -2
  207. package/src/tests/apps-rbac.test.ts +189 -2
  208. package/src/tests/apps-script-types.test.ts +16 -3
  209. package/src/tests/check-pr-body.test.ts +23 -0
  210. package/src/tests/check-ranking-entry.test.ts +146 -0
  211. package/src/tests/db-extraction-contract.test.ts +1 -0
  212. package/src/tests/db-task-read-contract.test.ts +1 -0
  213. package/src/tests/docs-index-footprint.test.js +2 -2
  214. package/src/tests/org-identity.test.ts +44 -0
  215. package/src/tests/ranking-listing.test.ts +112 -0
  216. package/src/tests/ranking-route.test.ts +319 -0
  217. package/src/tests/ranking-usage.test.ts +50 -0
  218. package/src/tests/rbac-admission-e2e.test.ts +8 -0
  219. package/src/tests/rbac-admission.test.ts +38 -0
  220. package/src/tests/rbac-charact-http.test.ts +4 -3
  221. package/src/tests/rbac-engine.test.ts +2 -0
  222. package/src/tests/rbac-roles.test.ts +2 -0
  223. package/src/tests/realtime-room-surfaces.test.ts +3 -1
  224. package/src/tests/realtime-session-join-race.test.ts +142 -0
  225. package/src/tests/realtime-tickets.test.ts +24 -17
  226. package/src/tests/realtime-transport.test.ts +91 -0
  227. package/src/tests/session-route-posture.test.ts +639 -0
  228. package/src/tests/session-sharing-routes.test.ts +282 -0
  229. package/src/tests/session-sharing.test.ts +526 -0
  230. package/src/tests/sessions-detail-batch.test.ts +7 -1
  231. package/src/tests/slack-tool-blocks.test.ts +101 -0
  232. package/src/tests/slack-update.test.ts +55 -0
  233. package/src/tests/slack-user-dm.test.ts +177 -0
  234. package/src/tests/used-by-route.test.ts +10 -0
  235. package/src/tools/slack-post.ts +18 -12
  236. package/src/tools/slack-read.ts +13 -1
  237. package/src/tools/slack-reply.ts +7 -10
  238. package/src/tools/slack-start-thread.ts +18 -11
  239. package/src/tools/slack-update.ts +2 -9
  240. package/src/types.ts +35 -0
  241. package/src/utils/org-identity.ts +33 -0
  242. package/templates/skills/apps/SKILL.md +17 -0
  243. package/templates/skills/apps/content.md +17 -0
  244. package/dist/handlers-tb3xgjnm.js +0 -37
  245. package/dist/index-nyfcdpky.js +0 -39
  246. package/dist/{cli-n5mrsg0f.js → cli-60cgh1rv.js} +3 -3
  247. /package/dist/{cli-j0v75y13.js → cli-y83zk5sb.js} +0 -0
package/src/http/core.ts CHANGED
@@ -47,6 +47,14 @@ import { refreshSecretScrubberCache, registerSensitiveKeyName } from "../utils/s
47
47
  import { resolveHttpRequestAuth } from "./auth";
48
48
  import { generateOpenApiSpec, SCALAR_HTML } from "./openapi";
49
49
  import { findRoute, isPublicRoute, route, runtimeInstanceHeader } from "./route-def";
50
+ import {
51
+ canReadSession,
52
+ pathSessionDenial,
53
+ readableByFor,
54
+ resolveSessionActor,
55
+ SESSION_READ_DENIED,
56
+ userAgentIdentityDenial,
57
+ } from "./session-access";
50
58
  import {
51
59
  agentWithCapacity,
52
60
  duplicateGuardedQueryKey,
@@ -503,6 +511,15 @@ export async function handleCore(
503
511
  setRequestAuth(req, auth);
504
512
  }
505
513
 
514
+ // A user token never gains agent identity from X-Agent-ID, on /mcp, /api/poll
515
+ // or any worker-header route.
516
+ const routeDef = findRoute(req.method, pathSegments);
517
+ const agentIdentityDenial = await userAgentIdentityDenial(req, routeDef, pathSegments);
518
+ if (agentIdentityDenial) {
519
+ jsonError(res, agentIdentityDenial, 403);
520
+ return true;
521
+ }
522
+
506
523
  if (auth?.kind === "agent") {
507
524
  const query = parseQueryParams(req.url || "");
508
525
  const duplicate = duplicateGuardedQueryKey(query);
@@ -565,7 +582,7 @@ export async function handleCore(
565
582
  if (auth?.kind === "user" && isRbacEnabled()) {
566
583
  const grant = await getUserGrant(auth.userId);
567
584
  if (!grant.grantsAll) {
568
- const def = findRoute(req.method, pathSegments);
585
+ const def = routeDef;
569
586
  const decision = decideAdmission({
570
587
  method: req.method ?? "",
571
588
  rbac: def?.rbac,
@@ -585,6 +602,16 @@ export async function handleCore(
585
602
  }
586
603
  }
587
604
 
605
+ // Session access for every route keyed by a task or steering message, before
606
+ // its handler reads or changes anything (the route's `session` posture).
607
+ if (routeDef?.session) {
608
+ const sessionDenial = await pathSessionDenial(req, myAgentId, routeDef, pathSegments);
609
+ if (sessionDenial) {
610
+ jsonError(res, sessionDenial, 403);
611
+ return true;
612
+ }
613
+ }
614
+
588
615
  // POST /internal/reload-config — re-read swarm_config into process.env and re-init integrations
589
616
  if (req.method === "POST" && req.url === "/internal/reload-config") {
590
617
  try {
@@ -662,7 +689,14 @@ export async function handleCore(
662
689
  const queryParams = parseQueryParams(req.url || "");
663
690
  const taskId = queryParams.get("taskId");
664
691
 
692
+ // A user token naming an agent in X-Agent-ID still reads only its sessions.
693
+ const sessionActor = await resolveSessionActor(req, myAgentId);
665
694
  if (taskId) {
695
+ if (!(await canReadSession(req, myAgentId, taskId))) {
696
+ res.writeHead(403, { "Content-Type": "application/json" });
697
+ res.end(JSON.stringify({ error: SESSION_READ_DENIED }));
698
+ return true;
699
+ }
666
700
  // Check if specific task is cancelled
667
701
  const task = await getTaskById(taskId);
668
702
  if (task && task.status === "cancelled") {
@@ -687,7 +721,10 @@ export async function handleCore(
687
721
  }
688
722
 
689
723
  // No taskId - return all recently cancelled tasks for this agent
690
- const cancelledTasks = await getRecentlyCancelledTasksForAgent(myAgentId);
724
+ const cancelledTasks = await getRecentlyCancelledTasksForAgent(
725
+ myAgentId,
726
+ readableByFor(sessionActor),
727
+ );
691
728
  res.writeHead(200, { "Content-Type": "application/json" });
692
729
  res.end(JSON.stringify({ cancelled: cancelledTasks }));
693
730
  return true;
@@ -13,7 +13,8 @@ import {
13
13
  EventStatusSchema,
14
14
  SwarmEventSchema,
15
15
  } from "../types";
16
- import { route } from "./route-def";
16
+ import { bodyListTask, bodyTask, route } from "./route-def";
17
+ import { readableByFor, resolveSessionActor } from "./session-access";
17
18
  import { jsonError } from "./utils";
18
19
 
19
20
  // ─── Route Definitions ───────────────────────────────────────────────────────
@@ -36,6 +37,7 @@ const createEventRoute = route({
36
37
  method: "post",
37
38
  path: "/api/events",
38
39
  pattern: ["api", "events"],
40
+ session: bodyTask("taskId"),
39
41
  summary: "Store a single event",
40
42
  tags: ["Events"],
41
43
  body: eventBodySchema,
@@ -53,6 +55,7 @@ const createEventsBatchRoute = route({
53
55
  method: "post",
54
56
  path: "/api/events/batch",
55
57
  pattern: ["api", "events", "batch"],
58
+ session: bodyListTask("events", "taskId"),
56
59
  summary: "Store multiple events in a batch",
57
60
  tags: ["Events"],
58
61
  body: z.object({
@@ -153,7 +156,7 @@ export async function handleEvents(
153
156
  res: ServerResponse,
154
157
  pathSegments: string[],
155
158
  queryParams: URLSearchParams,
156
- _myAgentId: string | undefined,
159
+ myAgentId: string | undefined,
157
160
  ): Promise<boolean> {
158
161
  // Match batch BEFORE generic /api/events (POST)
159
162
  if (createEventsBatchRoute.match(req.method, pathSegments)) {
@@ -252,6 +255,7 @@ export async function handleEvents(
252
255
  limit: parsed.query.limit ?? 100,
253
256
  events: eventFilter,
254
257
  latestPerDataField: latestPerDataField ? { events: latestEvents, dataFields } : undefined,
258
+ readableBy: readableByFor(await resolveSessionActor(req, myAgentId)),
255
259
  });
256
260
  getEventsRoute.respond(
257
261
  res,
@@ -16,7 +16,7 @@ export type FavoriteOwner = {
16
16
  */
17
17
  export const DASHBOARD_USER_HEADER = "x-swarm-user-id";
18
18
 
19
- function dashboardUserIdHeader(req: IncomingMessage): string | null {
19
+ export function dashboardUserIdHeader(req: IncomingMessage): string | null {
20
20
  const raw = req.headers[DASHBOARD_USER_HEADER];
21
21
  const value = (Array.isArray(raw) ? raw[0] : raw)?.trim();
22
22
  return value ? value : null;
package/src/http/fs.ts CHANGED
@@ -15,6 +15,7 @@ import { getCurrentRequestAuth } from "../utils/request-auth-context";
15
15
  import { scrubSecrets } from "../utils/secret-scrubber";
16
16
  import { requestPrincipal } from "./request-principal";
17
17
  import { route } from "./route-def";
18
+ import { canReadSession, SESSION_READ_DENIED } from "./session-access";
18
19
  import { BODY_TOO_LARGE, enforceContentLengthCap, jsonError } from "./utils";
19
20
 
20
21
  // Upload wall-clock past which the provider round-trip is worth a log line.
@@ -126,6 +127,7 @@ const listTaskFilesRoute = route({
126
127
  method: "get",
127
128
  path: "/api/fs/tasks/{taskId}/files",
128
129
  pattern: ["api", "fs", "tasks", null, "files"],
130
+ session: { taskParam: "taskId" },
129
131
  summary: "List task file attachments",
130
132
  tags: ["FS"],
131
133
  params: taskParams,
@@ -142,6 +144,7 @@ const uploadTaskFileRoute = route({
142
144
  method: "post",
143
145
  path: "/api/fs/tasks/{taskId}/files",
144
146
  pattern: ["api", "fs", "tasks", null, "files"],
147
+ session: { taskParam: "taskId" },
145
148
  summary: "Upload a binary task file attachment",
146
149
  description:
147
150
  "Accepts a raw binary request body. Pass the display/path name as the `name` query parameter.",
@@ -163,6 +166,7 @@ const getTaskFileRoute = route({
163
166
  method: "get",
164
167
  path: "/api/fs/tasks/{taskId}/files/{attachmentId}",
165
168
  pattern: ["api", "fs", "tasks", null, "files", null],
169
+ session: { taskParam: "taskId" },
166
170
  summary: "Get task file attachment metadata",
167
171
  tags: ["FS"],
168
172
  params: attachmentParams,
@@ -176,6 +180,7 @@ const downloadTaskFileRoute = route({
176
180
  method: "get",
177
181
  path: "/api/fs/tasks/{taskId}/files/{attachmentId}/raw",
178
182
  pattern: ["api", "fs", "tasks", null, "files", null, "raw"],
183
+ session: { taskParam: "taskId" },
179
184
  summary: "Download raw task file bytes",
180
185
  description: "Streams raw bytes. File content is not secret-scrubbed.",
181
186
  tags: ["FS"],
@@ -193,6 +198,7 @@ const signedUrlTaskFileRoute = route({
193
198
  method: "get",
194
199
  path: "/api/fs/tasks/{taskId}/files/{attachmentId}/signed-url",
195
200
  pattern: ["api", "fs", "tasks", null, "files", null, "signed-url"],
201
+ session: { taskParam: "taskId" },
196
202
  summary: "Create a provider signed GET URL for a task file",
197
203
  tags: ["FS"],
198
204
  params: attachmentParams,
@@ -208,6 +214,7 @@ const deleteTaskFileRoute = route({
208
214
  method: "delete",
209
215
  path: "/api/fs/tasks/{taskId}/files/{attachmentId}",
210
216
  pattern: ["api", "fs", "tasks", null, "files", null],
217
+ session: { taskParam: "taskId" },
211
218
  summary: "Delete a task file attachment",
212
219
  tags: ["FS"],
213
220
  params: attachmentParams,
@@ -263,7 +270,13 @@ export async function handleFs(
263
270
  if (downloadTaskFileRoute.match(req.method, pathSegments)) {
264
271
  const parsed = await downloadTaskFileRoute.parse(req, res, pathSegments, queryParams);
265
272
  if (!parsed) return true;
266
- const attachment = await findAttachment(parsed.params.taskId, parsed.params.attachmentId, res);
273
+ const attachment = await findAttachment(
274
+ req,
275
+ myAgentId,
276
+ parsed.params.taskId,
277
+ parsed.params.attachmentId,
278
+ res,
279
+ );
267
280
  if (!attachment) return true;
268
281
  return sendDownload(res, attachment);
269
282
  }
@@ -271,7 +284,13 @@ export async function handleFs(
271
284
  if (signedUrlTaskFileRoute.match(req.method, pathSegments)) {
272
285
  const parsed = await signedUrlTaskFileRoute.parse(req, res, pathSegments, queryParams);
273
286
  if (!parsed) return true;
274
- const attachment = await findAttachment(parsed.params.taskId, parsed.params.attachmentId, res);
287
+ const attachment = await findAttachment(
288
+ req,
289
+ myAgentId,
290
+ parsed.params.taskId,
291
+ parsed.params.attachmentId,
292
+ res,
293
+ );
275
294
  if (!attachment) return true;
276
295
  return sendSignedUrl(res, attachment, parsed.query.expiresIn);
277
296
  }
@@ -279,7 +298,13 @@ export async function handleFs(
279
298
  if (getTaskFileRoute.match(req.method, pathSegments)) {
280
299
  const parsed = await getTaskFileRoute.parse(req, res, pathSegments, queryParams);
281
300
  if (!parsed) return true;
282
- const attachment = await findAttachment(parsed.params.taskId, parsed.params.attachmentId, res);
301
+ const attachment = await findAttachment(
302
+ req,
303
+ myAgentId,
304
+ parsed.params.taskId,
305
+ parsed.params.attachmentId,
306
+ res,
307
+ );
283
308
  if (!attachment) return true;
284
309
  getTaskFileRoute.respond(res, 200, attachment);
285
310
  return true;
@@ -313,6 +338,10 @@ export async function handleFs(
313
338
  const parsed = await listTaskFilesRoute.parse(req, res, pathSegments, queryParams);
314
339
  if (!parsed) return true;
315
340
  if (!(await getTaskById(parsed.params.taskId))) return notFound(res, "Task not found");
341
+ if (!(await canReadSession(req, myAgentId, parsed.params.taskId))) {
342
+ jsonError(res, SESSION_READ_DENIED, 403);
343
+ return true;
344
+ }
316
345
  listTaskFilesRoute.respond(res, 200, {
317
346
  attachments: await getTaskAttachments(parsed.params.taskId),
318
347
  });
@@ -493,6 +522,8 @@ function backingProviderId(attachment: TaskAttachment): string | null {
493
522
  }
494
523
 
495
524
  async function findAttachment(
525
+ req: IncomingMessage,
526
+ myAgentId: string | undefined,
496
527
  taskId: string,
497
528
  attachmentId: string,
498
529
  res: ServerResponse,
@@ -501,6 +532,10 @@ async function findAttachment(
501
532
  notFound(res, "Task not found");
502
533
  return null;
503
534
  }
535
+ if (!(await canReadSession(req, myAgentId, taskId))) {
536
+ jsonError(res, SESSION_READ_DENIED, 403);
537
+ return null;
538
+ }
504
539
  const attachment = (await getTaskAttachments(taskId)).find((item) => item.id === attachmentId);
505
540
  if (!attachment) {
506
541
  notFound(res, "Attachment not found");
package/src/http/index.ts CHANGED
@@ -116,6 +116,7 @@ import { handlePagesPublic } from "./pages-public";
116
116
  import { handlePoll } from "./poll";
117
117
  import { handlePricing } from "./pricing";
118
118
  import { handlePromptTemplates } from "./prompt-templates";
119
+ import { handleRanking } from "./ranking";
119
120
  import { handleRealtimeAsset, handleRealtimeTicket } from "./realtime";
120
121
  import { handleRepos } from "./repos";
121
122
  import { handleRooms } from "./rooms";
@@ -403,10 +404,11 @@ const httpServer = createHttpServer(async (req, res) => {
403
404
  () => handleExtensions(req, res, pathSegments, queryParams, myAgentId),
404
405
  () => handleFavorites(req, res, pathSegments, queryParams, myAgentId),
405
406
  () => handleUsers(req, res, pathSegments, queryParams),
406
- () => handleSessions(req, res, pathSegments, queryParams),
407
+ () => handleSessions(req, res, pathSegments, queryParams, myAgentId),
407
408
  () => handleInboxState(req, res, pathSegments, queryParams),
408
409
  () => handleTelemetryUi(req, res, pathSegments, queryParams, myAgentId),
409
410
  () => handleUsedBy(req, res, pathSegments, queryParams, myAgentId),
411
+ () => handleRanking(req, res, pathSegments, queryParams),
410
412
  () => handleFleetBenchmark(req, res, pathSegments, queryParams),
411
413
  () => handleTaskTemplates(req, res, pathSegments, queryParams),
412
414
  () => handleMcp(req, res, transports, transportActivity, mcpSessionAgents),
@@ -44,7 +44,7 @@ import { AgentMemorySchema, AgentMemoryScopeSchema, AgentMemorySourceSchema } fr
44
44
  import { getRequestAuth } from "../utils/request-auth-context";
45
45
  import { scrubSecrets } from "../utils/secret-scrubber";
46
46
  import { rejectGuest } from "./request-principal";
47
- import { route } from "./route-def";
47
+ import { bodyTask, route } from "./route-def";
48
48
  import { jsonError, parseQueryParams } from "./utils";
49
49
 
50
50
  // ─── Response Schemas ────────────────────────────────────────────────────────
@@ -68,6 +68,7 @@ const indexMemory = route({
68
68
  method: "post",
69
69
  path: "/api/memory/index",
70
70
  pattern: ["api", "memory", "index"],
71
+ session: bodyTask("sourceTaskId"),
71
72
  summary: "Ingest content into memory system (async embedding)",
72
73
  tags: ["Memory"],
73
74
  // The gate only bites when the key that lands on the rows (here, `sourcePath`) sits under a
@@ -687,6 +688,7 @@ const rateMemory = route({
687
688
  method: "post",
688
689
  path: "/api/memory/rate",
689
690
  pattern: ["api", "memory", "rate"],
691
+ session: { none: "worker-only: it needs X-Agent-ID, which a user token cannot send" },
690
692
  summary: "Submit RatingEvents to update memory usefulness posteriors",
691
693
  tags: ["Memory"],
692
694
  auth: { apiKey: true, agentId: true },
@@ -0,0 +1,367 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { z } from "zod";
3
+ import { getDbClient, upsertSwarmConfig } from "../be/db";
4
+ import {
5
+ buildListing,
6
+ mintRankingClaim,
7
+ PUBLIC_RANKING_ENABLED_KEY,
8
+ RANKING_CATEGORIES,
9
+ rankingEntryFile,
10
+ rankingFormSchema,
11
+ rankingLeaveUrl,
12
+ rankingPrUrl,
13
+ readTelemetryRanking,
14
+ TELEMETRY_RANKING_KEY,
15
+ type TelemetryRanking,
16
+ } from "../ranking/telemetry-ranking";
17
+ import { isTelemetryEnabled, telemetry } from "../telemetry";
18
+ import { isEnvFlagEnabled } from "../utils/env-flag";
19
+ import {
20
+ ORG_IDENTITY_KEYS,
21
+ type OrgIdentityStatus,
22
+ orgIdentityStatus,
23
+ } from "../utils/org-identity";
24
+ import { ensureConfigAdmin } from "./config";
25
+ import { scheduleIntegrationsReload } from "./core";
26
+ import { route } from "./route-def";
27
+ import { globalConfig, telemetryProxyEndpoint } from "./used-by";
28
+
29
+ // ─── Schemas ─────────────────────────────────────────────────────────────────
30
+
31
+ const ListingSchema = z.object({
32
+ v: z.literal(1),
33
+ claim: z.string(),
34
+ name: z.string(),
35
+ domain: z.string(),
36
+ category: z.enum(RANKING_CATEGORIES),
37
+ subcategory: z.string().nullable(),
38
+ description: z.string().nullable(),
39
+ sourceCodeUrl: z.string().nullable(),
40
+ updatedAt: z.string(),
41
+ });
42
+
43
+ const RankingStateSchema = z.object({
44
+ eligible: z.boolean(),
45
+ missing: z.array(z.enum(ORG_IDENTITY_KEYS)),
46
+ telemetryOn: z.boolean(),
47
+ enabled: z.boolean(),
48
+ /** The org identity the listing would copy. */
49
+ name: z.string().nullable(),
50
+ domain: z.string().nullable(),
51
+ listing: ListingSchema.nullable(),
52
+ /** False when the stored listing was built for another website: a new PR is needed. */
53
+ listingMatchesDomain: z.boolean(),
54
+ fileJson: z.string().nullable(),
55
+ prUrl: z.string().nullable(),
56
+ verifyUrl: z.string().nullable(),
57
+ });
58
+ export type RankingState = z.infer<typeof RankingStateSchema>;
59
+
60
+ const OptInResponseSchema = z.object({
61
+ domain: z.string(),
62
+ claim: z.string(),
63
+ listing: ListingSchema,
64
+ fileJson: z.string(),
65
+ prUrl: z.string(),
66
+ verifyUrl: z.string(),
67
+ });
68
+
69
+ const OptOutResponseSchema = z.object({
70
+ enabled: z.literal(false),
71
+ leaveUrl: z.string().nullable(),
72
+ });
73
+
74
+ // ─── Route Definitions ───────────────────────────────────────────────────────
75
+
76
+ const getRanking = route({
77
+ method: "get",
78
+ path: "/api/ranking",
79
+ pattern: ["api", "ranking"],
80
+ summary: "Public ranking state",
81
+ description:
82
+ "Whether this install can join the public agent-swarm.dev ranking (telemetry on, organization name and website set), whether it is opted in, and its stored listing. The listing carries the private ranking claim, so only a config admin can read it.",
83
+ tags: ["Telemetry"],
84
+ responses: {
85
+ 200: { description: "Ranking state", schema: RankingStateSchema },
86
+ 401: { description: "Unauthorized" },
87
+ 403: { description: "Only a config admin can read the ranking state" },
88
+ },
89
+ rbac: { permission: "config.write.any" },
90
+ });
91
+
92
+ const optIn = route({
93
+ method: "post",
94
+ path: "/api/ranking/opt-in",
95
+ pattern: ["api", "ranking", "opt-in"],
96
+ summary: "Opt this install into the public ranking",
97
+ description:
98
+ "Builds the telemetry_ranking listing from the organization name and website plus the chosen category, stores it, turns PUBLIC_RANKING_ENABLED on and sends ranking.opted_in. The install is ranked only after a ranking PR with the returned file is merged into desplega-ai/agent-swarm.",
99
+ tags: ["Telemetry"],
100
+ body: rankingFormSchema,
101
+ responses: {
102
+ 200: { description: "Opted in", schema: OptInResponseSchema },
103
+ 400: { description: "A listing field is invalid" },
104
+ 401: { description: "Unauthorized" },
105
+ 403: { description: "Only a config admin can opt in" },
106
+ 409: {
107
+ description:
108
+ "telemetry_off: telemetry is off or the install has no ID. org_identity_missing: the organization name or website is not set (`missing` lists which).",
109
+ },
110
+ },
111
+ rbac: { permission: "config.write.any" },
112
+ });
113
+
114
+ const optOut = route({
115
+ method: "post",
116
+ path: "/api/ranking/opt-out",
117
+ pattern: ["api", "ranking", "opt-out"],
118
+ summary: "Leave the public ranking",
119
+ description:
120
+ "Turns PUBLIC_RANKING_ENABLED off and sends ranking.opted_out, so workers stop sending ranking.usage. Returns the GitHub page that deletes the ranking entry.",
121
+ tags: ["Telemetry"],
122
+ responses: {
123
+ 200: { description: "Opted out", schema: OptOutResponseSchema },
124
+ 401: { description: "Unauthorized" },
125
+ 403: { description: "Only a config admin can opt out" },
126
+ },
127
+ rbac: { permission: "config.write.any" },
128
+ });
129
+
130
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
131
+
132
+ const RANKING_CONFIG_KEYS = new Set<string>([...ORG_IDENTITY_KEYS, PUBLIC_RANKING_ENABLED_KEY]);
133
+
134
+ /**
135
+ * The org identity from global config. `changed` carries a value just written
136
+ * or deleted, since `globalConfig` falls back to `process.env`, which the
137
+ * debounced reload has not updated yet.
138
+ */
139
+ async function currentIdentity(changed?: {
140
+ key: string;
141
+ value: string | null;
142
+ }): Promise<OrgIdentityStatus> {
143
+ const read = async (key: string) =>
144
+ changed?.key === key ? changed.value : await globalConfig(key);
145
+ return orgIdentityStatus({
146
+ SWARM_ORG_NAME: await read("SWARM_ORG_NAME"),
147
+ SWARM_ORG_WEBSITE: await read("SWARM_ORG_WEBSITE"),
148
+ });
149
+ }
150
+
151
+ async function storedListing(): Promise<TelemetryRanking | null> {
152
+ return readTelemetryRanking(await globalConfig(TELEMETRY_RANKING_KEY));
153
+ }
154
+
155
+ async function rankingEnabled(): Promise<boolean> {
156
+ const raw = await globalConfig(PUBLIC_RANKING_ENABLED_KEY);
157
+ return isEnvFlagEnabled(PUBLIC_RANKING_ENABLED_KEY, false, {
158
+ [PUBLIC_RANKING_ENABLED_KEY]: raw,
159
+ });
160
+ }
161
+
162
+ async function telemetryReady(): Promise<boolean> {
163
+ return isTelemetryEnabled() && Boolean(await globalConfig("telemetry_installation_id"));
164
+ }
165
+
166
+ async function verifyUrl(listing: Pick<TelemetryRanking, "domain" | "claim">): Promise<string> {
167
+ const params = new URLSearchParams({ domain: listing.domain, claim: listing.claim });
168
+ return `${await telemetryProxyEndpoint("/v1/ranking/verify")}?${params.toString()}`;
169
+ }
170
+
171
+ async function setEnabled(enabled: boolean): Promise<void> {
172
+ await upsertSwarmConfig({
173
+ scope: "global",
174
+ key: PUBLIC_RANKING_ENABLED_KEY,
175
+ value: String(enabled),
176
+ });
177
+ }
178
+
179
+ function emitOptedIn(listing: TelemetryRanking): void {
180
+ telemetry.ranking(
181
+ "opted_in",
182
+ { listing: JSON.stringify(listing) },
183
+ { orgName: listing.name, orgWebsite: listing.domain },
184
+ );
185
+ }
186
+
187
+ function emitOptedOut(domain: string): void {
188
+ telemetry.ranking("opted_out", { domain });
189
+ }
190
+
191
+ export async function buildRankingState(): Promise<RankingState> {
192
+ const [identity, listing, enabled, telemetryOn] = await Promise.all([
193
+ currentIdentity(),
194
+ storedListing(),
195
+ rankingEnabled(),
196
+ telemetryReady(),
197
+ ]);
198
+ const listingMatchesDomain = Boolean(listing && listing.domain === identity.website);
199
+ const current = listingMatchesDomain ? listing : null;
200
+ return {
201
+ eligible: telemetryOn && identity.ok,
202
+ missing: identity.missing,
203
+ telemetryOn,
204
+ enabled: enabled && listingMatchesDomain,
205
+ name: identity.name,
206
+ domain: identity.website,
207
+ listing,
208
+ listingMatchesDomain,
209
+ fileJson: current ? rankingEntryFile(current) : null,
210
+ prUrl: current ? rankingPrUrl(current) : null,
211
+ verifyUrl: current ? await verifyUrl(current) : null,
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Keep the listing in step with the org identity after a global config write.
217
+ * A renamed org rebuilds the listing with the same claim and re-sends it; a
218
+ * cleared or placeholder name, a changed or cleared website, or the setting
219
+ * turned off by hand opts the install out.
220
+ */
221
+ export async function syncRankingAfterConfigChange(
222
+ key: string,
223
+ value: string | null,
224
+ ): Promise<void> {
225
+ if (!RANKING_CONFIG_KEYS.has(key)) return;
226
+ const listing = await storedListing();
227
+ if (!listing) return;
228
+ if (key === PUBLIC_RANKING_ENABLED_KEY) {
229
+ if (!isEnvFlagEnabled(key, false, { [key]: value ?? undefined })) {
230
+ emitOptedOut(listing.domain);
231
+ }
232
+ return;
233
+ }
234
+ if (!(await rankingEnabled())) return;
235
+
236
+ const identity = await currentIdentity({ key, value });
237
+ let rebuilt: TelemetryRanking | null = null;
238
+ if (identity.ok && identity.website === listing.domain) {
239
+ if (identity.name === listing.name) return;
240
+ try {
241
+ rebuilt = buildListing(identity, listing, listing.claim);
242
+ } catch {
243
+ // A name the listing cannot carry (over 60 characters) leaves the ranking.
244
+ }
245
+ }
246
+ if (!rebuilt) {
247
+ await setEnabled(false);
248
+ emitOptedOut(listing.domain);
249
+ return;
250
+ }
251
+ await upsertSwarmConfig({
252
+ scope: "global",
253
+ key: TELEMETRY_RANKING_KEY,
254
+ value: JSON.stringify(rebuilt),
255
+ });
256
+ emitOptedIn(rebuilt);
257
+ }
258
+
259
+ function conflict(res: ServerResponse, body: Record<string, unknown>): void {
260
+ res.writeHead(409, { "Content-Type": "application/json" });
261
+ res.end(JSON.stringify(body));
262
+ }
263
+
264
+ // ─── Handler ─────────────────────────────────────────────────────────────────
265
+
266
+ export async function handleRanking(
267
+ req: IncomingMessage,
268
+ res: ServerResponse,
269
+ pathSegments: string[],
270
+ queryParams: URLSearchParams,
271
+ ): Promise<boolean> {
272
+ if (getRanking.match(req.method, pathSegments)) {
273
+ const parsed = await getRanking.parse(req, res, pathSegments, queryParams);
274
+ if (!parsed) return true;
275
+ // The state carries the claim and the PR that proves ownership of the listing.
276
+ if (!(await ensureConfigAdmin(req, res, "config.write.any"))) return true;
277
+ getRanking.respond(res, 200, await buildRankingState());
278
+ return true;
279
+ }
280
+
281
+ if (optIn.match(req.method, pathSegments)) {
282
+ const parsed = await optIn.parse(req, res, pathSegments, queryParams);
283
+ if (!parsed) return true;
284
+ if (!(await ensureConfigAdmin(req, res, "config.write.any"))) return true;
285
+
286
+ if (!(await telemetryReady())) {
287
+ conflict(res, {
288
+ error: "telemetry_off",
289
+ message: "Turn telemetry on first: the ranking counts tokens from telemetry.",
290
+ });
291
+ return true;
292
+ }
293
+ const identity = await currentIdentity();
294
+ if (!identity.ok || !identity.website) {
295
+ conflict(res, {
296
+ error: "org_identity_missing",
297
+ message: "Set the organization name and website first",
298
+ missing: identity.missing,
299
+ });
300
+ return true;
301
+ }
302
+
303
+ const website = identity.website;
304
+ const db = getDbClient();
305
+ // Read the stored claim under the write lock: two concurrent first opt-ins
306
+ // must return the same claim, or the one merged into community/ranking is lost.
307
+ const built = await db.transaction(async () => {
308
+ const stored = await storedListing();
309
+ const claim = stored?.domain === website ? stored.claim : mintRankingClaim();
310
+ let listing: TelemetryRanking;
311
+ try {
312
+ listing = buildListing(identity, parsed.body, claim);
313
+ } catch (error) {
314
+ return { ok: false as const, error };
315
+ }
316
+ await upsertSwarmConfig({
317
+ scope: "global",
318
+ key: TELEMETRY_RANKING_KEY,
319
+ value: JSON.stringify(listing),
320
+ });
321
+ await setEnabled(true);
322
+ db.afterCommit(() => emitOptedIn(listing));
323
+ return { ok: true as const, listing };
324
+ });
325
+ if (!built.ok) {
326
+ const issue = built.error instanceof z.ZodError ? built.error.issues[0] : undefined;
327
+ res.writeHead(400, { "Content-Type": "application/json" });
328
+ res.end(
329
+ JSON.stringify({
330
+ error: issue
331
+ ? `Invalid ${issue.path.join(".") || "listing"}: ${issue.message}`
332
+ : "Invalid listing",
333
+ }),
334
+ );
335
+ return true;
336
+ }
337
+ const { listing } = built;
338
+ scheduleIntegrationsReload();
339
+
340
+ optIn.respond(res, 200, {
341
+ domain: listing.domain,
342
+ claim: listing.claim,
343
+ listing,
344
+ fileJson: rankingEntryFile(listing),
345
+ prUrl: rankingPrUrl(listing),
346
+ verifyUrl: await verifyUrl(listing),
347
+ });
348
+ return true;
349
+ }
350
+
351
+ if (optOut.match(req.method, pathSegments)) {
352
+ const parsed = await optOut.parse(req, res, pathSegments, queryParams);
353
+ if (!parsed) return true;
354
+ if (!(await ensureConfigAdmin(req, res, "config.write.any"))) return true;
355
+ const listing = await storedListing();
356
+ await setEnabled(false);
357
+ if (listing) emitOptedOut(listing.domain);
358
+ scheduleIntegrationsReload();
359
+ optOut.respond(res, 200, {
360
+ enabled: false,
361
+ leaveUrl: listing ? rankingLeaveUrl(listing.domain) : null,
362
+ });
363
+ return true;
364
+ }
365
+
366
+ return false;
367
+ }