@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
@@ -2,6 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { z } from "zod";
3
3
  import { getSwarmConfigs, upsertSwarmConfig } from "../be/db";
4
4
  import { isTelemetryEnabled, trackRelayed } from "../telemetry";
5
+ import { orgIdentityStatus } from "../utils/org-identity";
5
6
  import { normalizeOrgWebsite, TELEMETRY_PROXY_ORIGIN } from "../utils/org-website";
6
7
  import { ensureConfigAdmin } from "./config";
7
8
  import { scheduleIntegrationsReload } from "./core";
@@ -46,7 +47,8 @@ const usedBy = route({
46
47
 
47
48
  // ─── Helpers ─────────────────────────────────────────────────────────────────
48
49
 
49
- async function globalConfig(key: string): Promise<string | undefined> {
50
+ /** A global config value, falling back to the process env. */
51
+ export async function globalConfig(key: string): Promise<string | undefined> {
50
52
  const stored = (await getSwarmConfigs({ scope: "global", key }))?.[0]?.value?.trim();
51
53
  return stored || process.env[key]?.trim() || undefined;
52
54
  }
@@ -79,8 +81,14 @@ export async function handleUsedBy(
79
81
  if (!(await ensureConfigAdmin(req, res, "config.write.any"))) return true;
80
82
 
81
83
  const { granted } = parsed.body;
82
- const currentName = await globalConfig("SWARM_ORG_NAME");
83
- const currentWebsite = normalizeOrgWebsite(await globalConfig("SWARM_ORG_WEBSITE"));
84
+ // The shared identity reader. The grant keeps its own rule (any non-empty
85
+ // name), so it does not apply the ranking's placeholder-name check.
86
+ const current = orgIdentityStatus({
87
+ SWARM_ORG_NAME: await globalConfig("SWARM_ORG_NAME"),
88
+ SWARM_ORG_WEBSITE: await globalConfig("SWARM_ORG_WEBSITE"),
89
+ });
90
+ const currentName = current.name ?? undefined;
91
+ const currentWebsite = current.website;
84
92
  const grantedName = granted ? undefined : await globalConfig(GRANTED_NAME_KEY);
85
93
  const grantedWebsite = granted
86
94
  ? null
@@ -555,12 +555,14 @@ registerTemplate({
555
555
  header: "",
556
556
  defaultBody: `{{prompt}}
557
557
 
558
- [App action] app={{app_id}} action={{action_name}} input={{input_json}}`,
558
+ [App action] app={{app_id}} action={{action_name}} input={{input_json}}
559
+ Caller (server-verified): {{caller_json}}`,
559
560
  variables: [
560
561
  { name: "prompt", description: "The task prompt configured on the app action" },
561
562
  { name: "app_id", description: "The app identifier" },
562
563
  { name: "action_name", description: "The invoked action name" },
563
564
  { name: "input_json", description: "The action input serialized as JSON" },
565
+ { name: "caller_json", description: "The server-verified action caller serialized as JSON" },
564
566
  ],
565
567
  category: "task_lifecycle",
566
568
  });
@@ -44,7 +44,7 @@ import type {
44
44
  * default; the image installs exactly this version and the per-task settings
45
45
  * set `amp.updates.mode: "disabled"`. Bump it deliberately, with a live run.
46
46
  */
47
- export const AMP_PACKAGE = "@ampcode/cli@0.0.1792296040-g5ce754";
47
+ export const AMP_PACKAGE = "@ampcode/cli@0.0.1792324855-g9c86a5";
48
48
 
49
49
  /** MCP server name. Amp exposes its tools as `agent_swarm` / `store_progress` (dashes become underscores). */
50
50
  const AMP_MCP_SERVER_NAME = "agent-swarm";
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The `telemetry_ranking` listing: what an install opted into the public ranking
3
+ * shows on agent-swarm.dev/ranking. Stored stringified in the global
4
+ * `swarm_config` key `telemetry_ranking` and sent as the `listing` property of
5
+ * `ranking.opted_in`.
6
+ *
7
+ * The proxy owns the contract (`src/telemetry-contract/ranking/`, vendored by
8
+ * `bun run sync:telemetry-contract`). This schema and the proxy's Go decoder are
9
+ * both held to its fixtures. Pure: imported by the API and the dashboard.
10
+ */
11
+ import { z } from "zod";
12
+ import { RANKING_TAXONOMY } from "../telemetry-contract/ranking-taxonomy.gen";
13
+ import type { OrgIdentityStatus } from "../utils/org-identity";
14
+ import { normalizeOrgWebsite } from "../utils/org-website";
15
+
16
+ export { RANKING_TAXONOMY };
17
+
18
+ export const TELEMETRY_RANKING_KEY = "telemetry_ranking";
19
+ export const PUBLIC_RANKING_ENABLED_KEY = "PUBLIC_RANKING_ENABLED";
20
+ export const TELEMETRY_RANKING_MAX_BYTES = 2048;
21
+
22
+ export const RANKING_CATEGORIES = Object.keys(RANKING_TAXONOMY) as [
23
+ keyof typeof RANKING_TAXONOMY,
24
+ ...(keyof typeof RANKING_TAXONOMY)[],
25
+ ];
26
+ export const RANKING_CLAIM_PATTERN = /^rk_[0-9a-f]{32}$/;
27
+
28
+ const hostname = z.string().refine((v) => normalizeOrgWebsite(v) === v, "bare hostname");
29
+ const nullableText = (max: number) => z.string().trim().min(1).max(max).nullable();
30
+
31
+ function inCategory(category: string, subcategory: string | null): boolean {
32
+ if (subcategory === null) return true;
33
+ const subs: readonly string[] = RANKING_TAXONOMY[category as keyof typeof RANKING_TAXONOMY];
34
+ return subs?.includes(subcategory) ?? false;
35
+ }
36
+
37
+ export const telemetryRankingV1 = z
38
+ .strictObject({
39
+ v: z.literal(1),
40
+ claim: z.string().regex(RANKING_CLAIM_PATTERN),
41
+ name: z.string().trim().min(1).max(60),
42
+ domain: hostname,
43
+ category: z.enum(RANKING_CATEGORIES),
44
+ subcategory: z
45
+ .string()
46
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/)
47
+ .max(40)
48
+ .nullable(),
49
+ description: nullableText(160),
50
+ sourceCodeUrl: z
51
+ .url({ protocol: /^https$/ })
52
+ .max(200)
53
+ .nullable(),
54
+ updatedAt: z.iso.datetime(),
55
+ })
56
+ .refine((l) => inCategory(l.category, l.subcategory), {
57
+ path: ["subcategory"],
58
+ message: "not in this category",
59
+ });
60
+
61
+ /** Discriminated on `v`; a v2 is added here, never by editing v1. */
62
+ export const telemetryRankingSchema = z.discriminatedUnion("v", [telemetryRankingV1]);
63
+ export type TelemetryRanking = z.infer<typeof telemetryRankingSchema>;
64
+
65
+ export function parseTelemetryRanking(raw: string): TelemetryRanking {
66
+ if (new TextEncoder().encode(raw).length > TELEMETRY_RANKING_MAX_BYTES) {
67
+ throw new Error(`telemetry_ranking exceeds ${TELEMETRY_RANKING_MAX_BYTES} bytes`);
68
+ }
69
+ return telemetryRankingSchema.parse(JSON.parse(raw));
70
+ }
71
+
72
+ /** The stored listing, or null when it is missing or no longer valid. */
73
+ export function readTelemetryRanking(raw: string | null | undefined): TelemetryRanking | null {
74
+ if (!raw?.trim()) return null;
75
+ try {
76
+ return parseTelemetryRanking(raw);
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /** What the admin picks in the ranking form. Name and domain are never typed here. */
83
+ export const rankingFormSchema = z.object({
84
+ category: z.enum(RANKING_CATEGORIES),
85
+ subcategory: z.string().nullable().optional(),
86
+ description: z.string().nullable().optional(),
87
+ sourceCodeUrl: z.string().nullable().optional(),
88
+ });
89
+ export type RankingForm = z.infer<typeof rankingFormSchema>;
90
+
91
+ /** `rk_` + 32 lowercase hex characters from the platform CSPRNG. */
92
+ export function mintRankingClaim(): string {
93
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
94
+ return `rk_${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`;
95
+ }
96
+
97
+ const blankToNull = (value: string | null | undefined) => value?.trim() || null;
98
+
99
+ /**
100
+ * Build and validate the listing. Name and domain are copied from the org
101
+ * identity (`SWARM_ORG_NAME`, `SWARM_ORG_WEBSITE`); throws when the identity is
102
+ * not set or a form field breaks the contract.
103
+ */
104
+ export function buildListing(
105
+ identity: OrgIdentityStatus,
106
+ form: RankingForm,
107
+ claim: string,
108
+ now: Date = new Date(),
109
+ ): TelemetryRanking {
110
+ if (!identity.ok || !identity.name || !identity.website) {
111
+ throw new Error(`Org identity is missing: ${identity.missing.join(", ")}`);
112
+ }
113
+ const listing = {
114
+ v: 1 as const,
115
+ claim,
116
+ name: identity.name,
117
+ domain: identity.website,
118
+ category: form.category,
119
+ subcategory: blankToNull(form.subcategory),
120
+ description: blankToNull(form.description),
121
+ sourceCodeUrl: blankToNull(form.sourceCodeUrl),
122
+ updatedAt: now.toISOString(),
123
+ };
124
+ return parseTelemetryRanking(JSON.stringify(listing));
125
+ }
126
+
127
+ /** The `community/ranking/<domain>.json` file that approves this install. */
128
+ export function rankingEntryFile(listing: Pick<TelemetryRanking, "domain" | "claim">): string {
129
+ return `${JSON.stringify({ $schema: "./schema.json", domain: listing.domain, claim: listing.claim }, null, 2)}\n`;
130
+ }
131
+
132
+ export const RANKING_REPO = "desplega-ai/agent-swarm";
133
+
134
+ /** GitHub's "new file" page, prefilled with the entry, as a PR from the admin's fork. */
135
+ export function rankingPrUrl(listing: Pick<TelemetryRanking, "domain" | "claim">): string {
136
+ const params = new URLSearchParams({
137
+ filename: `community/ranking/${listing.domain}.json`,
138
+ value: rankingEntryFile(listing),
139
+ message: `chore(ranking): add ${listing.domain}`,
140
+ });
141
+ return `https://github.com/${RANKING_REPO}/new/main?${params.toString()}`;
142
+ }
143
+
144
+ /** GitHub's delete page for an entry, to leave the ranking for good. */
145
+ export function rankingLeaveUrl(domain: string): string {
146
+ return `https://github.com/${RANKING_REPO}/delete/main/community/ranking/${domain}.json`;
147
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Worker side of the public ranking: the `ranking.usage` properties for one
3
+ * session. Pure, so the runner and its test share the gate.
4
+ */
5
+ import { isEnvFlagEnabled } from "../utils/env-flag";
6
+ import { orgIdentityStatus } from "../utils/org-identity";
7
+
8
+ export interface SessionTokens {
9
+ inputTokens?: number | null;
10
+ outputTokens?: number | null;
11
+ cacheReadTokens?: number | null;
12
+ cacheWriteTokens?: number | null;
13
+ }
14
+
15
+ export interface RankingUsageProps {
16
+ /** The same model and provider `session.cost` reports for the session. */
17
+ model: string;
18
+ provider: string;
19
+ totalTokens: number;
20
+ inputTokens: number;
21
+ outputTokens: number;
22
+ cacheReadTokens?: number;
23
+ cacheWriteTokens?: number;
24
+ }
25
+
26
+ const tokens = (value: number | null | undefined) =>
27
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
28
+
29
+ /**
30
+ * Null unless telemetry is on, `PUBLIC_RANKING_ENABLED` is set and both org
31
+ * identity envs are set. Carries token counts plus the model and provider
32
+ * (for the per-model chart), never the task, agent or cost.
33
+ */
34
+ export function rankingUsageProps(
35
+ cost: SessionTokens,
36
+ session: { model: string; provider: string },
37
+ env: NodeJS.ProcessEnv = process.env,
38
+ ): RankingUsageProps | null {
39
+ if (!isEnvFlagEnabled("ANONYMIZED_TELEMETRY", true, env)) return null;
40
+ if (!isEnvFlagEnabled("PUBLIC_RANKING_ENABLED", false, env)) return null;
41
+ const identity = { SWARM_ORG_NAME: env.SWARM_ORG_NAME, SWARM_ORG_WEBSITE: env.SWARM_ORG_WEBSITE };
42
+ if (!orgIdentityStatus(identity).ok) return null;
43
+ const input = tokens(cost.inputTokens);
44
+ const output = tokens(cost.outputTokens);
45
+ const cacheRead = tokens(cost.cacheReadTokens);
46
+ const cacheWrite = tokens(cost.cacheWriteTokens);
47
+ return {
48
+ model: session.model,
49
+ provider: session.provider,
50
+ // The unified sum, as computeContextUsedUnified counts it.
51
+ totalTokens: input + cacheRead + cacheWrite + output,
52
+ inputTokens: input,
53
+ outputTokens: output,
54
+ ...(cost.cacheReadTokens != null ? { cacheReadTokens: cacheRead } : {}),
55
+ ...(cost.cacheWriteTokens != null ? { cacheWriteTokens: cacheWrite } : {}),
56
+ };
57
+ }
@@ -8,7 +8,20 @@ export type AdmissionGrant = {
8
8
  };
9
9
  };
10
10
 
11
- export type AdmissionRbac = { permission: PermissionVerb } | { ungated: string };
11
+ /**
12
+ * `alsoAdmits` names verbs that admit the route as well as `permission`, for a
13
+ * route that serves two features (each handler check still names its own verb).
14
+ */
15
+ export type AdmissionRbac =
16
+ | { permission: PermissionVerb; alsoAdmits?: readonly PermissionVerb[] }
17
+ | { ungated: string };
18
+
19
+ function grantedVerb(
20
+ rbac: { permission: PermissionVerb; alsoAdmits?: readonly PermissionVerb[] },
21
+ grant: AdmissionGrant,
22
+ ): PermissionVerb | undefined {
23
+ return [rbac.permission, ...(rbac.alsoAdmits ?? [])].find((verb) => grant.verbs.has(verb));
24
+ }
12
25
 
13
26
  export type AdmissionDecision =
14
27
  | { allow: true; verb?: PermissionVerb }
@@ -29,10 +42,11 @@ export function decideAdmission(input: {
29
42
  }
30
43
 
31
44
  if (input.rbac && "permission" in input.rbac) {
32
- const verb = input.rbac.permission;
33
- if (input.grant.verbs.has(verb)) {
34
- return { allow: true, verb };
45
+ const granted = grantedVerb(input.rbac, input.grant);
46
+ if (granted) {
47
+ return { allow: true, verb: granted };
35
48
  }
49
+ const verb = input.rbac.permission;
36
50
  return { allow: false, reason: `admission: missing permission '${verb}'`, verb };
37
51
  }
38
52
 
@@ -54,10 +68,11 @@ export function decideToolAdmission(input: {
54
68
  }
55
69
 
56
70
  if (input.rbac && "permission" in input.rbac) {
57
- const verb = input.rbac.permission;
58
- if (input.grant.verbs.has(verb)) {
59
- return { allow: true, verb };
71
+ const granted = grantedVerb(input.rbac, input.grant);
72
+ if (granted) {
73
+ return { allow: true, verb: granted };
60
74
  }
75
+ const verb = input.rbac.permission;
61
76
  return { allow: false, reason: `admission: missing permission '${verb}'`, verb };
62
77
  }
63
78
 
@@ -285,6 +285,8 @@ export const LEGACY_POLICY = {
285
285
  "task.action.own": requesterOwnsTask,
286
286
  "task.fs.mutate": taskFsMutate,
287
287
  "task.parent.attach": taskFsMutate,
288
+ "session.share": operatorOrUser,
289
+ "session.presence": operatorOrUser,
288
290
  "task.progress.write": taskProgressWrite,
289
291
  "favorite.write.own": anyAuthenticated,
290
292
  "memory.learning.inject": leadOnly,
@@ -89,6 +89,15 @@ export const PERMISSIONS = {
89
89
  "Write a task's progress, status, or output (its assignee, a lead, a human, or anyone while unassigned).",
90
90
  namespace: "task",
91
91
  },
92
+ "session.share": {
93
+ description:
94
+ "Change who can view or edit a session the principal owns (the owner check runs in the handler).",
95
+ namespace: "task",
96
+ },
97
+ "session.presence": {
98
+ description: "Join the presence room of a session the principal can view.",
99
+ namespace: "task",
100
+ },
92
101
  "favorite.write.own": {
93
102
  description: "Set a favorite the caller owns.",
94
103
  namespace: "favorite",
@@ -1,6 +1,7 @@
1
1
  import type { IncomingMessage } from "node:http";
2
2
  import { getAgentById, getTaskById } from "../be/db";
3
3
  import { getUserGrant } from "../be/rbac-roles";
4
+ import { getSessionRoot, sessionAccessForRoot } from "../be/session-shares";
4
5
  import { getCombConfig } from "../comb/config";
5
6
  import { mcpOverflowAuthError } from "../kv-overflow";
6
7
  import { reservedNamespaceError } from "../kv-reserved-namespaces";
@@ -19,6 +20,8 @@ export type RoomAuthorizationInfo = RoomNamespaceInfo & {
19
20
  callOrigin?: "http" | "mcp" | "ws";
20
21
  userId?: string;
21
22
  isOperator?: boolean;
23
+ /** The user an operator-key dashboard tab picked (`X-Swarm-User-Id`), captured on its ticket. */
24
+ dashboardUserId?: string;
22
25
  };
23
26
 
24
27
  export type ResolvedRoomNamespace = {
@@ -39,6 +42,7 @@ export type RoomNamespaceOperation =
39
42
 
40
43
  const COMB_PRESENCE_NAMESPACE = /^presence:comb:[A-Za-z0-9_-]{1,64}:[A-Za-z0-9_-]{1,64}$/;
41
44
  const COMB_PRESENCE_OPERATIONS = new Set<RoomNamespaceOperation>(["join", "leave", "presence"]);
45
+ const SESSION_PRESENCE_NAMESPACE = /^presence:session:([A-Za-z0-9_-]{1,64})$/;
42
46
 
43
47
  function pageNamespace(pageId: string): string | null {
44
48
  try {
@@ -162,6 +166,10 @@ export async function authorizeRoomNamespace(
162
166
  return null;
163
167
  }
164
168
 
169
+ if (namespace.startsWith("presence:session:")) {
170
+ return authorizeSessionPresence(namespace, info, access);
171
+ }
172
+
165
173
  const reservedError = reservedNamespaceError(namespace);
166
174
  if (reservedError) return reservedError;
167
175
 
@@ -203,3 +211,64 @@ export async function authorizeRoomNamespace(
203
211
 
204
212
  return null;
205
213
  }
214
+
215
+ /**
216
+ * Bus topic published after a session's shares change. Sockets in that
217
+ * session's presence room re-check access and are evicted when it ended.
218
+ */
219
+ export function sessionAccessTopic(rootTaskId: string): string {
220
+ return `session-access:${rootTaskId}`;
221
+ }
222
+
223
+ /** The root task id of a `presence:session:<rootTaskId>` namespace, else undefined. */
224
+ export function sessionPresenceRoot(namespace: string): string | undefined {
225
+ return SESSION_PRESENCE_NAMESPACE.exec(namespace)?.[1];
226
+ }
227
+
228
+ /**
229
+ * `presence:session:<rootTaskId>`: who is viewing (and typing in) a session.
230
+ * Presence-only, dashboard-only, and gated on read access so it never reveals
231
+ * who is inside a private session. An operator-key tab with no picked user
232
+ * keeps the access it has everywhere else.
233
+ */
234
+ async function authorizeSessionPresence(
235
+ namespace: string,
236
+ info: RoomAuthorizationInfo,
237
+ access: boolean | RoomNamespaceOperation,
238
+ ): Promise<string | null> {
239
+ const match = SESSION_PRESENCE_NAMESPACE.exec(namespace);
240
+ if (!match) return "invalid session presence namespace";
241
+ if (info.pageId || info.agentId || (!info.isOperator && !info.userId)) {
242
+ return "Session presence requires dashboard authentication";
243
+ }
244
+ if (typeof access !== "string" || !COMB_PRESENCE_OPERATIONS.has(access)) {
245
+ return "Session presence rooms only allow join, leave, and presence";
246
+ }
247
+ const principal = info.isOperator
248
+ ? ({ kind: "operator" } as const)
249
+ : ({ kind: "user", userId: info.userId! } as const);
250
+ if (
251
+ !can({
252
+ principal,
253
+ verb: "session.presence",
254
+ resource: { kind: "kv-namespace", namespace },
255
+ source: info.callOrigin === "mcp" ? "mcp" : "http",
256
+ }).allow
257
+ ) {
258
+ return "Session presence requires the session.presence permission";
259
+ }
260
+ if (info.userId && isRbacEnabled()) {
261
+ const grant = await getUserGrant(info.userId);
262
+ if (!grant.grantsAll && !grant.verbs.has("session.presence")) {
263
+ return "Session presence requires the session.presence permission";
264
+ }
265
+ }
266
+ const viewerId = info.isOperator ? info.dashboardUserId : info.userId;
267
+ if (info.isOperator && !viewerId) return null;
268
+ const root = await getSessionRoot(match[1]!);
269
+ if (!root || root.id !== match[1]) return "session not found";
270
+ if ((await sessionAccessForRoot(viewerId ?? null, root)) === "none") {
271
+ return "You don't have access to this session";
272
+ }
273
+ return null;
274
+ }
@@ -3,7 +3,10 @@ import type { HttpRequestAuth } from "../utils/request-auth-context";
3
3
  export const REALTIME_TICKET_TTL_MS = 60_000;
4
4
  export const REALTIME_TICKET_CAPACITY = 10_000;
5
5
 
6
- export type RealtimeTicketAuth = Extract<HttpRequestAuth, { kind: "operator" | "user" }>;
6
+ export type RealtimeTicketAuth = Extract<HttpRequestAuth, { kind: "operator" | "user" }> & {
7
+ /** The user an operator-key dashboard tab picked (`X-Swarm-User-Id`), for session presence. */
8
+ dashboardUserId?: string;
9
+ };
7
10
 
8
11
  type StoredTicket = {
9
12
  auth: RealtimeTicketAuth;
@@ -10,7 +10,12 @@ import { extractAndVerifyCookie } from "../utils/page-session";
10
10
  import type { HttpRequestAuth } from "../utils/request-auth-context";
11
11
  import { scrubSecrets } from "../utils/secret-scrubber";
12
12
  import { registerSessionTokenConnection } from "../utils/session-token-connections";
13
- import { authorizeRoomNamespace, resolveRoomNamespace } from "./auth";
13
+ import {
14
+ authorizeRoomNamespace,
15
+ resolveRoomNamespace,
16
+ sessionAccessTopic,
17
+ sessionPresenceRoot,
18
+ } from "./auth";
14
19
  import { realtimeBus } from "./bus";
15
20
  import {
16
21
  addWorkerSubscription,
@@ -64,6 +69,7 @@ type Identity = {
64
69
  pageId?: string;
65
70
  userId?: string;
66
71
  isOperator?: boolean;
72
+ dashboardUserId?: string;
67
73
  };
68
74
  type Viewer = { userId: string; name: string; kind: "user" | "guest" | "agent" };
69
75
  type AuthenticatedConnection = {
@@ -81,7 +87,7 @@ function header(req: IncomingMessage, name: string): string | undefined {
81
87
 
82
88
  function identityFromHttpAuth(
83
89
  req: IncomingMessage,
84
- auth: HttpRequestAuth,
90
+ auth: HttpRequestAuth & { dashboardUserId?: string },
85
91
  ): AuthenticatedConnection {
86
92
  if (auth.kind === "controller") throw new Error("Controller tokens cannot use realtime");
87
93
  if (auth.kind === "agent") {
@@ -110,6 +116,7 @@ function identityFromHttpAuth(
110
116
  auth.kind === "agent" ? (auth.taskId ?? undefined) : header(req, "x-source-task-id"),
111
117
  userId: auth.kind === "user" ? auth.userId : undefined,
112
118
  isOperator: auth.kind === "operator",
119
+ dashboardUserId: auth.kind === "operator" ? auth.dashboardUserId : undefined,
113
120
  } satisfies Identity,
114
121
  me: {
115
122
  userId: auth.kind === "user" ? auth.userId : (agentId ?? guestId),
@@ -228,7 +235,12 @@ function connect(
228
235
  )
229
236
  : undefined;
230
237
  void auth.sessionToken?.check().catch(() => ws.close(1008, "Session token revoked or expired"));
231
- const rooms = new Map<string, { room: LiveRoom; version: number; stop: () => void }>();
238
+ // `suspended`: a session presence room whose access is being re-checked
239
+ // after a share change; nothing is forwarded until the check passes.
240
+ const rooms = new Map<
241
+ string,
242
+ { room: LiveRoom; version: number; stop: () => void; suspended?: boolean }
243
+ >();
232
244
  const channels = new Map<string, () => void>();
233
245
  const pending = new Map<number, number>();
234
246
  const clientId = crypto.getRandomValues(new Uint32Array(1))[0]!;
@@ -313,6 +325,9 @@ function connect(
313
325
  if (namespace.startsWith("presence:comb:") && msg.name !== "default") {
314
326
  throw new Error("Comb presence uses the default room");
315
327
  }
328
+ if (namespace.startsWith("presence:session:") && msg.name !== "default") {
329
+ throw new Error("Session presence uses the default room");
330
+ }
316
331
  const denied = await authorizeRoomNamespace(namespace, auth.identity, msg.op, msg.name);
317
332
  if (denied) throw new Error(typeof denied === "string" ? denied : "Forbidden");
318
333
  if (closed) return;
@@ -352,12 +367,14 @@ function connect(
352
367
  room = await getRoom(namespace, msg.name, msg.schemaVersion, { create: false });
353
368
  } catch (error) {
354
369
  if (!(error instanceof Error) || error.message !== "room does not exist") throw error;
355
- // Creating a room is a write. Comb presence rooms take only presence
356
- // operations, so they check creation as a join.
370
+ // Creating a room is a write. Comb and session presence rooms take
371
+ // only presence operations, so they check creation as a join.
357
372
  const creationDenied = await authorizeRoomNamespace(
358
373
  namespace,
359
374
  auth.identity,
360
- namespace.startsWith("presence:comb:") ? "join" : true,
375
+ namespace.startsWith("presence:comb:") || namespace.startsWith("presence:session:")
376
+ ? "join"
377
+ : true,
361
378
  );
362
379
  if (creationDenied) throw new Error(creationDenied);
363
380
  if (closed) return;
@@ -365,6 +382,7 @@ function connect(
365
382
  }
366
383
  if (closed) return;
367
384
  const stopRoom = realtimeBus.subscribe(key, (event) => {
385
+ if (rooms.get(key)?.suspended) return;
368
386
  const view = event as ReturnType<typeof roomView> & { type: string };
369
387
  const type = view.type;
370
388
  if (type === "deleted") {
@@ -387,17 +405,67 @@ function connect(
387
405
  .catch(() => ws.close(1011, "Room reset failed"));
388
406
  }
389
407
  });
390
- const stopPresence = realtimeBus.subscribe(`presence:${key}`, (peers) =>
391
- send({ type: "presence", name: msg.name, namespace, peers }),
392
- );
408
+ const stopPresence = realtimeBus.subscribe(`presence:${key}`, (peers) => {
409
+ if (rooms.get(key)?.suspended) return;
410
+ send({ type: "presence", name: msg.name, namespace, peers });
411
+ });
412
+ const sessionRoot = sessionPresenceRoot(namespace);
413
+ let accessCheck = 0;
414
+ // A share change can end this viewer's read access: stop forwarding
415
+ // at once, then evict, or resume if access remains.
416
+ const stopAccess = sessionRoot
417
+ ? realtimeBus.subscribe(sessionAccessTopic(sessionRoot), () => {
418
+ const joined = rooms.get(key);
419
+ if (!joined) return;
420
+ joined.suspended = true;
421
+ const check = ++accessCheck;
422
+ void authorizeRoomNamespace(namespace, auth.identity, "join")
423
+ .catch(() => "Session access check failed")
424
+ .then((denied) => {
425
+ const current = rooms.get(key);
426
+ if (closed || !current || check !== accessCheck) return;
427
+ if (denied) {
428
+ leave(key);
429
+ send({ type: "error", name: msg.name, namespace, error: denied });
430
+ return;
431
+ }
432
+ current.suspended = false;
433
+ send({
434
+ type: "presence",
435
+ name: msg.name,
436
+ namespace,
437
+ peers: [...current.room.awareness.getStates().values()],
438
+ });
439
+ });
440
+ })
441
+ : undefined;
393
442
  rooms.set(key, {
394
443
  room,
395
444
  version: msg.schemaVersion,
396
445
  stop: () => {
397
446
  stopRoom();
398
447
  stopPresence();
448
+ stopAccess?.();
399
449
  },
450
+ suspended: sessionRoot !== undefined,
400
451
  });
452
+ if (sessionRoot) {
453
+ // A share change published while the room loaded reached no
454
+ // subscriber, so check again now that the access subscriber is
455
+ // live. Anything later is that subscriber's to handle.
456
+ const check = ++accessCheck;
457
+ const denied = await authorizeRoomNamespace(namespace, auth.identity, "join").catch(
458
+ () => "Session access check failed",
459
+ );
460
+ if (closed) return;
461
+ if (denied) {
462
+ leave(key);
463
+ throw new Error(denied);
464
+ }
465
+ const current = rooms.get(key);
466
+ if (!current) throw new Error("You don't have access to this session");
467
+ if (check === accessCheck) current.suspended = false;
468
+ }
401
469
  room.awareness.states.set(clientId, { ...auth.me, data: {} });
402
470
  room.awareness.meta.set(clientId, { clock: 1, lastUpdated: Date.now() });
403
471
  publishPresence(room);
@@ -97,6 +97,10 @@ export function splitSlackSectionText(text: string): string[] {
97
97
  if (splitIdx < MAX_SECTION_LENGTH / 2) {
98
98
  // No good break point at all, hard split
99
99
  splitIdx = MAX_SECTION_LENGTH;
100
+ // Keep a surrogate pair (emoji, astral char) together: never end a
101
+ // chunk on a lone high surrogate.
102
+ const prev = remaining.charCodeAt(splitIdx - 1);
103
+ if (prev >= 0xd800 && prev <= 0xdbff) splitIdx -= 1;
100
104
  }
101
105
  chunks.push(remaining.slice(0, splitIdx));
102
106
  remaining = remaining.slice(splitIdx).trimStart();
@@ -104,6 +108,20 @@ export function splitSlackSectionText(text: string): string[] {
104
108
  return chunks;
105
109
  }
106
110
 
111
+ // Slack's hard cap on section text.
112
+ const SLACK_SECTION_TEXT_LIMIT = 3000;
113
+
114
+ /**
115
+ * Default blocks for a tool message sent without explicit `blocks`: one
116
+ * mrkdwn section per chunk, so text over the section limit still sends.
117
+ * Text Slack accepts in one section stays one section, so links and code
118
+ * fences are never split below the limit.
119
+ */
120
+ export function buildMrkdwnSectionBlocks(text: string): SlackBlock[] {
121
+ if (text.length <= SLACK_SECTION_TEXT_LIMIT) return [sectionBlock(text)];
122
+ return splitSlackSectionText(text).map((chunk) => sectionBlock(chunk));
123
+ }
124
+
107
125
  // --- Block primitives ---
108
126
 
109
127
  function contextBlock(...elements: string[]): SlackBlock {