@desplega.ai/agent-swarm 1.166.0 → 1.168.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 (221) hide show
  1. package/dist/acp-adapter-zhejfecx.js +34 -0
  2. package/dist/{actions-qz3m692w.js → actions-7jg840nr.js} +25 -25
  3. package/dist/{amp-adapter-j1xbmsqz.js → amp-adapter-ye6rnetm.js} +4 -4
  4. package/dist/{anthropic-messages-hst62ws9.js → anthropic-messages-13yn502s.js} +4 -4
  5. package/dist/{app-43vrdmv8.js → app-ffes2kyf.js} +10 -9
  6. package/dist/{assistant-ertffmka.js → assistant-fhm5smyz.js} +26 -26
  7. package/dist/{azure-openai-responses-mh8tvf78.js → azure-openai-responses-9st34pfz.js} +5 -5
  8. package/dist/{boot-reembed-998jtpdg.js → boot-reembed-20q3nzvg.js} +9 -8
  9. package/dist/{boot-reembed-s7k7c6v2.js → boot-reembed-jvfadhsk.js} +9 -8
  10. package/dist/{boot-scrub-sweep-nepsk4t1.js → boot-scrub-sweep-jtfajzve.js} +10 -9
  11. package/dist/{boot-seeds-vvzs1zhk.js → boot-seeds-9qt0j8j2.js} +12 -11
  12. package/dist/{claude-adapter-2zvmekrp.js → claude-adapter-a8znhthz.js} +24 -22
  13. package/dist/{claude-managed-adapter-s49wbk8t.js → claude-managed-adapter-tzwxy803.js} +4 -4
  14. package/dist/{claude-managed-setup-cvhqq8qn.js → claude-managed-setup-nrhfx5b0.js} +3 -3
  15. package/dist/{claude-sdk-session-kkbxtw5q.js → claude-sdk-session-7x7chdrs.js} +7608 -7596
  16. package/dist/{cli-zsh093hk.js → cli-014vns2y.js} +63 -1
  17. package/dist/{cli-8kgvmkak.js → cli-0jngabtb.js} +1 -1
  18. package/dist/{cli-qvfk83fy.js → cli-13xwcqvj.js} +2 -2
  19. package/dist/{cli-0nhdwxd5.js → cli-43jg9xdw.js} +3 -3
  20. package/dist/{cli-cpfmqz3n.js → cli-47zfzshm.js} +5 -5
  21. package/dist/{cli-zy7vwsne.js → cli-5qkcdv8c.js} +16 -9
  22. package/dist/{cli-cwxhbf43.js → cli-5t5my0h8.js} +85 -2
  23. package/dist/{cli-y59h2pk9.js → cli-69egj654.js} +1 -1
  24. package/dist/{cli-68r1j4sg.js → cli-6bpvv8h4.js} +3 -3
  25. package/dist/{cli-yshaazs1.js → cli-74ez9b66.js} +63 -20
  26. package/dist/{cli-32bca7nr.js → cli-7avy4v8w.js} +1 -1
  27. package/dist/{cli-f2n17zhp.js → cli-7mhy3ths.js} +21 -18
  28. package/dist/{cli-q38n4bq0.js → cli-95zs84qw.js} +3 -3
  29. package/dist/{cli-fn697bnt.js → cli-9q0bh411.js} +21 -8
  30. package/dist/{cli-rggdq8wq.js → cli-9q24yyvs.js} +3 -3
  31. package/dist/cli-a35hzdve.js +33 -0
  32. package/dist/{cli-3qn4r334.js → cli-aj1e0h0d.js} +20 -14
  33. package/dist/{cli-rsy933yz.js → cli-bcspch6h.js} +30 -19
  34. package/dist/{cli-x3x0qwky.js → cli-bxqez1p0.js} +51 -23
  35. package/dist/{cli-ng97fjq7.js → cli-cmxkbzzs.js} +33 -7
  36. package/dist/{cli-df56tqdw.js → cli-ee0402n1.js} +198 -70
  37. package/dist/{cli-mwegs4af.js → cli-ew0c3a1j.js} +3 -3
  38. package/dist/{cli-ysnyhws9.js → cli-ewhwpyrb.js} +54 -51
  39. package/dist/{cli-j2jbr8af.js → cli-fhj4y16f.js} +1 -1
  40. package/dist/{cli-8t229cmr.js → cli-fqq06kkb.js} +30 -17
  41. package/dist/{cli-jvj6a0cv.js → cli-g6gx2dn1.js} +54 -19
  42. package/dist/{cli-nexwh8zg.js → cli-g7k7zbcz.js} +12 -5
  43. package/dist/{cli-ecknp7p1.js → cli-j05x7pnb.js} +10 -10
  44. package/dist/{cli-gt8azyet.js → cli-jb931ba2.js} +1 -1
  45. package/dist/{cli-nvvfd8bq.js → cli-jbzbr36n.js} +4091 -3793
  46. package/dist/{cli-3ddybbbx.js → cli-jvmtxqtc.js} +26 -14
  47. package/dist/{cli-pkke6geq.js → cli-km4x66j0.js} +83 -65
  48. package/dist/{cli-b0f70z24.js → cli-mn8qkd8v.js} +1 -1
  49. package/dist/{cli-0qjcsxgz.js → cli-nctfv2yy.js} +99 -9
  50. package/dist/{cli-4r1sjfc4.js → cli-ng1pmdx6.js} +10 -10
  51. package/dist/cli-nkqjj42q.js +104 -0
  52. package/dist/{cli-aqcey741.js → cli-p5jqk8fr.js} +1 -1
  53. package/dist/{cli-66zh26sp.js → cli-pgehz8e1.js} +57 -17
  54. package/dist/cli-q1vnz8wv.js +96 -0
  55. package/dist/{cli-fj86xr3c.js → cli-qd97v6z2.js} +2 -2
  56. package/dist/{cli-p4ztb80h.js → cli-r7eeddkq.js} +13 -8
  57. package/dist/{cli-8ssjez7e.js → cli-rhy7z1rp.js} +22 -11
  58. package/dist/{cli-vzc73wet.js → cli-rr5z1j4p.js} +87 -69
  59. package/dist/{cli-4mevd1hf.js → cli-s9y81s7j.js} +5 -5
  60. package/dist/{cli-dw2q9f7g.js → cli-svah6b6w.js} +4 -4
  61. package/dist/{cli-h3x613ze.js → cli-tc5zec7v.js} +6 -6
  62. package/dist/{cli-ttbsse3f.js → cli-tmhsxhb8.js} +1 -1
  63. package/dist/{cli-feh3dkah.js → cli-v1w7pbd8.js} +2 -1
  64. package/dist/{cli-10zmp1p7.js → cli-vr5avem2.js} +27 -32
  65. package/dist/{cli-bzr0ftht.js → cli-wnb9b2g3.js} +19 -0
  66. package/dist/{cli-krqm5f11.js → cli-xezn9nkh.js} +16 -13
  67. package/dist/{cli-8kt0bmgx.js → cli-xf713zz0.js} +2 -2
  68. package/dist/{cli-6zcfw0x7.js → cli-y195hv1a.js} +1 -1
  69. package/dist/{cli-x7kpr72a.js → cli-ytmmyj7f.js} +2 -2
  70. package/dist/{cli-v2a8x45d.js → cli-z48ggfyq.js} +11 -6
  71. package/dist/{cli-qbksc292.js → cli-zy39d433.js} +2 -0
  72. package/dist/cli.js +28 -28
  73. package/dist/{cloudflare-workers-ai-system-one-tt484t61.js → cloudflare-workers-ai-system-one-sta45jf9.js} +7 -5
  74. package/dist/{codex-adapter-dw1wxqt8.js → codex-adapter-n63k33d3.js} +18 -18
  75. package/dist/{codex-login-terbdsqq.js → codex-login-g1cyt5zm.js} +1 -1
  76. package/dist/{codex-session-runner-3cgb8y1g.js → codex-session-runner-xkxfd81a.js} +18 -18
  77. package/dist/{commands-mhxam6z2.js → commands-q4mfhn51.js} +9 -8
  78. package/dist/{cursor-adapter-2qda3st7.js → cursor-adapter-v8mm6bp5.js} +5 -5
  79. package/dist/{db-sjks418k.js → db-1t0bj3pc.js} +9 -8
  80. package/dist/{dispatcher-1es759rn.js → dispatcher-k1fhavcf.js} +24 -24
  81. package/dist/{dsh-adapter-bek4cyw9.js → dsh-adapter-5423p70m.js} +5 -5
  82. package/dist/{easter-egg-3d-mtpnw06s.js → easter-egg-3d-66zxervv.js} +2 -2
  83. package/dist/{execute-s4ccjq3n.js → execute-h4jgevyw.js} +61 -11
  84. package/dist/{google-generative-ai-d6nphg3q.js → google-generative-ai-b8zxrpax.js} +5 -5
  85. package/dist/{google-vertex-cpshkref.js → google-vertex-nrdd697t.js} +5 -5
  86. package/dist/{grok-adapter-ar9cw9jg.js → grok-adapter-phrndeb8.js} +18 -8
  87. package/dist/{handlers-1gkbhktr.js → handlers-59ywqwzh.js} +27 -27
  88. package/dist/{hook-vxa3tcsy.js → hook-atj0swc2.js} +14 -14
  89. package/dist/{hook-ds2zxq9v.js → hook-mew1chq9.js} +42 -31
  90. package/dist/{http-3h21z9md.js → http-ef2fnn9v.js} +953 -98
  91. package/dist/{index-n99fycq7.js → index-48pb9erw.js} +24 -24
  92. package/dist/{index-bn6cy8ps.js → index-9fc2h7ww.js} +24 -24
  93. package/dist/{index-9b65j1m5.js → index-gr69c43q.js} +9 -8
  94. package/dist/{index-f8xnqrye.js → index-h26wjcfy.js} +43 -24
  95. package/dist/{index-dkfxpkmm.js → index-w2yhye23.js} +25 -25
  96. package/dist/{keepalive-3xspa9jw.js → keepalive-qhcqz56v.js} +11 -10
  97. package/dist/{lead-6qphc124.js → lead-hpk5r3b1.js} +47 -47
  98. package/dist/{llama-cpp-classify-tgj35k8d.js → llama-cpp-classify-6erb7wwv.js} +3 -1
  99. package/dist/{maintenance-0teem1bb.js → maintenance-nvkyp2xe.js} +9 -8
  100. package/dist/{mistral-conversations-8445ddjn.js → mistral-conversations-059y51zt.js} +4 -4
  101. package/dist/{node-9sg7ajby.js → node-qm9eb6z0.js} +1 -1
  102. package/dist/{oauth-refresh-sweep-sh9q25xp.js → oauth-refresh-sweep-ngskthwh.js} +10 -9
  103. package/dist/{onboard-54qmnqxe.js → onboard-yfnkqhxc.js} +2 -2
  104. package/dist/{openai-codex-responses-9ynm88zy.js → openai-codex-responses-jzxkta9b.js} +8 -7
  105. package/dist/{openai-completions-nhqwjmaw.js → openai-completions-663yncfq.js} +4 -4
  106. package/dist/openai-decisions-vj9nkpf8.js +162 -0
  107. package/dist/{openai-responses-xx1c4kgm.js → openai-responses-m3g43rrt.js} +5 -5
  108. package/dist/{opencode-adapter-wjfa2wvd.js → opencode-adapter-yjyqynzf.js} +7 -7
  109. package/dist/{openrouter-images-8yx3487g.js → openrouter-images-kr60n6b9.js} +1 -1
  110. package/dist/{otel-impl-ycqzp2a1.js → otel-impl-hhm64r6m.js} +1 -1
  111. package/dist/{pi-messages-vxdt8v7j.js → pi-messages-xszk613n.js} +1 -1
  112. package/dist/{pi-mono-adapter-e77e9zst.js → pi-mono-adapter-0eg8kw2c.js} +68 -51
  113. package/dist/{pricing-refresh-atnkngqs.js → pricing-refresh-35f91nx2.js} +11 -10
  114. package/dist/{rbac-roles-j78wdksm.js → rbac-roles-97w370qj.js} +10 -9
  115. package/dist/{rbac-roles-9pjphh9q.js → rbac-roles-z6sje3gy.js} +9 -8
  116. package/dist/{render-v2-pxjs49fx.js → render-v2-n4v66bj3.js} +10 -9
  117. package/dist/{runtime-v2t1r79e.js → runtime-h9ha1mq6.js} +4 -4
  118. package/dist/{setup-ymej0xtx.js → setup-m3hhyv5f.js} +2 -2
  119. package/dist/{typesafe-system-one-datfr82p.js → typesafe-system-one-e988vty7.js} +7 -5
  120. package/dist/{virtual-modules-wm8mxdxx.js → virtual-modules-ftr9kwe8.js} +11 -11
  121. package/dist/{work-objects-3nh4ymzb.js → work-objects-mxf2c842.js} +27 -27
  122. package/dist/{worker-qa9fkz5s.js → worker-9t07z1gq.js} +47 -47
  123. package/openapi.json +72 -1
  124. package/package.json +10 -10
  125. package/src/be/memory/providers/openai-embedding.ts +7 -2
  126. package/src/be/memory/raters/llm-summarizer.ts +7 -2
  127. package/src/be/modelsdev-cache.json +61 -0
  128. package/src/be/script-connections.ts +40 -6
  129. package/src/be/seed-pricing.ts +84 -53
  130. package/src/be/swarm-config-guard.ts +14 -0
  131. package/src/commands/provider-credentials.ts +28 -5
  132. package/src/commands/runner.ts +7 -12
  133. package/src/extensions/catalog.generated.json +17 -0
  134. package/src/heartbeat/heartbeat.ts +91 -19
  135. package/src/hooks/hook.ts +72 -27
  136. package/src/http/mcp.ts +5 -0
  137. package/src/http/onboarding.ts +2 -0
  138. package/src/http/script-connections.ts +35 -0
  139. package/src/providers/acp-targets.ts +10 -5
  140. package/src/providers/amp-adapter.ts +1 -1
  141. package/src/providers/claude-adapter.ts +32 -0
  142. package/src/providers/claude-background-keepalive.ts +100 -0
  143. package/src/providers/claude-sdk-session.ts +6 -0
  144. package/src/providers/codex-adapter.ts +30 -3
  145. package/src/providers/codex-oauth/auth-json.ts +21 -4
  146. package/src/providers/codex-oauth/types.ts +2 -0
  147. package/src/providers/dsh-adapter.ts +11 -2
  148. package/src/providers/grok-adapter.ts +18 -2
  149. package/src/providers/opencode-adapter.ts +21 -5
  150. package/src/providers/pi-mono-extension.ts +56 -25
  151. package/src/providers/pricing-sources.md +2 -0
  152. package/src/scheduler/scheduler.ts +82 -13
  153. package/src/scripts-runtime/executors/registry.ts +1 -1
  154. package/src/server.ts +63 -3
  155. package/src/tests/acp-adapter.test.ts +152 -12
  156. package/src/tests/ci-unit-test-report.test.ts +73 -0
  157. package/src/tests/claude-background-keepalive-wiring.test.ts +220 -0
  158. package/src/tests/claude-background-keepalive.fixture.ts +162 -0
  159. package/src/tests/claude-background-keepalive.test.ts +139 -0
  160. package/src/tests/claude-default-route.test.ts +75 -0
  161. package/src/tests/claude-hook-output.test.ts +233 -0
  162. package/src/tests/codex-adapter-pool-auth-revalidate.test.ts +4 -2
  163. package/src/tests/codex-adapter.test.ts +166 -26
  164. package/src/tests/codex-oauth-auth-timestamps.test.ts +76 -0
  165. package/src/tests/codex-oauth.test.ts +4 -1
  166. package/src/tests/connection-embedded-auth.test.ts +51 -0
  167. package/src/tests/context-window.test.ts +2 -2
  168. package/src/tests/credential-check.test.ts +51 -1
  169. package/src/tests/docs-index-footprint.test.js +3 -3
  170. package/src/tests/dsh-adapter.test.ts +24 -2
  171. package/src/tests/enabled-tools.test.ts +269 -0
  172. package/src/tests/entrypoint-codex-oauth-seed.test.ts +12 -0
  173. package/src/tests/extensions-catalog.test.ts +1 -0
  174. package/src/tests/extensions-example-slack-reply-gate.test.ts +756 -0
  175. package/src/tests/grok-adapter.test.ts +13 -0
  176. package/src/tests/haiku-5-5-pricing.test.ts +38 -0
  177. package/src/tests/heartbeat-checklist.test.ts +158 -1
  178. package/src/tests/onboarding.test.ts +44 -0
  179. package/src/tests/opencode-adapter.test.ts +66 -3
  180. package/src/tests/opencode-plugin.test.ts +37 -0
  181. package/src/tests/openrouter-attribution-call-sites.test.ts +204 -0
  182. package/src/tests/openrouter-base-url.test.ts +30 -39
  183. package/src/tests/pi-mono-extension.test.ts +161 -2
  184. package/src/tests/pricing-refresh.test.ts +70 -1
  185. package/src/tests/reasoning-effort.test.ts +3 -1
  186. package/src/tests/schedule-target-type.test.ts +136 -0
  187. package/src/tests/script-connections-http.test.ts +45 -0
  188. package/src/tests/script-connections-mcp.test.ts +41 -0
  189. package/src/tests/script-executor-registry.test.ts +18 -0
  190. package/src/tests/send-task-self-send.test.ts +107 -0
  191. package/src/tests/telemetry-trigger.test.ts +12 -1
  192. package/src/tests/workflow-llm.test.ts +14 -0
  193. package/src/tests/workflow-system-one-decision-providers.test.ts +33 -0
  194. package/src/tools/request-human-input.ts +7 -2
  195. package/src/tools/script-connections/tool.ts +35 -3
  196. package/src/tools/send-task.ts +9 -1
  197. package/src/utils/enabled-tools.ts +27 -0
  198. package/src/utils/internal-ai/complete-structured.ts +11 -3
  199. package/src/utils/openrouter-base-url.ts +23 -0
  200. package/src/workflows/executors/raw-llm.ts +1 -0
  201. package/src/workflows/executors/system-one-decision.ts +2 -0
  202. package/src/workflows/executors/validate.ts +1 -0
  203. package/src/workflows/executors/workflow-llm.ts +9 -2
  204. package/templates/extensions/README.md +1 -0
  205. package/templates/extensions/slack-reply-gate/README.md +98 -0
  206. package/templates/extensions/slack-reply-gate/hooks.ts +582 -0
  207. package/templates/extensions/slack-reply-gate/manifest.json +8 -0
  208. package/templates/skills/agent-browser/SKILL.md +2 -0
  209. package/templates/skills/agent-browser/content.md +2 -0
  210. package/templates/skills/code-quality/content.md +1 -0
  211. package/templates/skills/heartbeat-runbook/content.md +1 -1
  212. package/templates/skills/swarm-scripts/SKILL.md +10 -0
  213. package/templates/skills/swarm-scripts/content.md +10 -0
  214. package/templates/skills/work-on-task/SKILL.md +4 -0
  215. package/templates/skills/work-on-task/content.md +4 -0
  216. package/templates/skills/workflow-iterate/content.md +9 -0
  217. package/dist/acp-adapter-yzfxn8vj.js +0 -23
  218. package/dist/cli-3dpj7atn.js +0 -11
  219. package/dist/cli-gvcgmx69.js +0 -183
  220. package/dist/{cli-jhm6hzjn.js → cli-mxvnnv5q.js} +7 -7
  221. package/dist/{codex-hook-d2rkvf39.js → codex-hook-15dgc4cb.js} +1 -1
@@ -0,0 +1,582 @@
1
+ import { type ApiCtx, block, type SwarmExtension } from "swarm-extension";
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * slack-reply-gate
6
+ *
7
+ * Every human message in a Slack thread the swarm takes part in is buffered and
8
+ * flushed into a Lead task ("[Thread follow-up — N message(s) buffered]"), even
9
+ * "lol", ":joy:" or two people bantering. This hook asks TypeSafe Jev whether
10
+ * Lead should answer, and drops the wake-up when the answer is no.
11
+ *
12
+ * Hook: `pre.task.create`, origin "slack", description carrying the
13
+ * thread-buffer header. `pre.slack.route` cannot be used: the buffered thread
14
+ * path returns before that hook is dispatched, and its result can only
15
+ * re-target a message, never drop it.
16
+ *
17
+ * Rules:
18
+ * - A message that @mentions Lead passes without a Jev call.
19
+ * - Otherwise one Jev `choice` question classifies the message into a reason;
20
+ * reply=false only for reaction_only | banter_between_others |
21
+ * not_addressed_to_lead, and only when the summed probability of those
22
+ * three labels is >= minConfidence (a banter/reaction split is still a skip).
23
+ * - Fails OPEN on every error, timeout or missing key.
24
+ *
25
+ * Transport (config.provider): Jev is served by TypeSafe directly and by
26
+ * OpenRouter's Decisions endpoint. Both take the same {model, state, questions}
27
+ * body and return the same `answers` shape. `auto` uses TYPESAFE_API_KEY when
28
+ * set, else OPENROUTER_API_KEY.
29
+ *
30
+ * modes (config.mode):
31
+ * off -> never evaluate
32
+ * shadow -> evaluate + record, never block (default)
33
+ * enforce -> record, block the task when reply=false, and mark the
34
+ * triggering Slack message with :mute: (config.muteReaction)
35
+ *
36
+ * Muting: no swarm tool or ctx method adds a Slack reaction, so the hook calls
37
+ * the Slack Web API (reactions.remove / reactions.add) with the bot token. It
38
+ * first removes the bot's own acceptance reactions (:eyes:, :heavy_plus_sign:,
39
+ * :zap:, :speech_balloon:, or their SLACK_REACTION_* overrides), the same set
40
+ * the engine clears when it finalizes a task, then adds :mute:. With
41
+ * muteReaction "" it only removes them: a true no-op on the message. It runs after
42
+ * the block decision returns, so a slow or failing Slack call never delays or
43
+ * changes the drop; its errors go to the same KV namespace.
44
+ *
45
+ * Every decision lands in KV namespace `ext:slack-reply-gate`.
46
+ */
47
+
48
+ export const config = z.object({
49
+ mode: z.enum(["off", "shadow", "enforce"]).default("shadow"),
50
+ timeoutMs: z.number().int().positive().default(3000),
51
+ provider: z.enum(["auto", "typesafe", "openrouter"]).default("auto"),
52
+ /** Jev model on the TypeSafe transport. */
53
+ model: z.string().default("jev-latest"),
54
+ /** Jev model on the OpenRouter transport. */
55
+ openrouterModel: z.string().default("typesafe/jev-1.13"),
56
+ minConfidence: z.number().min(0).max(1).default(0.55),
57
+ contextMessages: z.number().int().min(0).max(20).default(6),
58
+ leadAliases: z.array(z.string()).default(["lead"]),
59
+ botSlackUserIds: z.array(z.string()).default([]),
60
+ /** Explicit TypeSafe key; otherwise TYPESAFE_API_KEY from the API process env. */
61
+ apiKey: z.string().optional(),
62
+ /**
63
+ * Reaction for a dropped message in enforce mode. "" only removes the bot's
64
+ * acceptance reaction(s) and adds nothing.
65
+ */
66
+ muteReaction: z.string().default("mute"),
67
+ slackTimeoutMs: z.number().int().positive().default(5000),
68
+ });
69
+
70
+ type Cfg = z.infer<typeof config>;
71
+ type Swarm = ApiCtx["swarm"];
72
+
73
+ const NS = "ext:slack-reply-gate";
74
+ const TYPESAFE_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
75
+ const OPENROUTER_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
76
+ const HEADER_LINE_RE = /(?:^|\n)\[Thread follow-up — \d+ message\(s\) buffered\]\n/g;
77
+ const CTX_OPEN = "<thread_context>";
78
+ const CTX_CLOSE = "</thread_context>";
79
+ // The dispatcher cancels a handler after 5 s; leave room for the KV writes.
80
+ const MAX_TIMEOUT_MS = 4000;
81
+
82
+ export const REASONS = {
83
+ direct_ask:
84
+ "Asks Lead (or the swarm, the bot, 'you' meaning the AI) a question or for something, explicitly or clearly implied.",
85
+ followup_to_lead:
86
+ "Answers, confirms, corrects or continues something Lead or another swarm agent ([Agent]) just said or asked, so Lead needs it to proceed.",
87
+ instruction_to_lead:
88
+ "Gives a task, instruction, request or decision for the AI to act on, even without naming it (for example 'can you create X', 'ship it', 'do it').",
89
+ reaction_only:
90
+ "Only a reaction: emoji, laughter (lol, haha, jaja), 'boom!', 'nice', 'thanks', '+1', with no request and nothing new for Lead.",
91
+ banter_between_others:
92
+ "Chat between the humans, or between other people and other bots, that is not aimed at Lead.",
93
+ not_addressed_to_lead:
94
+ "Addressed to a specific other person or another assistant, or an FYI that needs no answer from Lead.",
95
+ other: "None of the above, or unclear.",
96
+ } as const;
97
+
98
+ export type Reason = keyof typeof REASONS;
99
+ const SKIP_REASONS: ReadonlySet<string> = new Set([
100
+ "reaction_only",
101
+ "banter_between_others",
102
+ "not_addressed_to_lead",
103
+ ]);
104
+
105
+ const cfgOf = (raw: unknown): Cfg => {
106
+ const parsed = config.safeParse(raw ?? {});
107
+ return parsed.success ? parsed.data : config.parse({});
108
+ };
109
+
110
+ // kv keys accept [a-zA-Z0-9._:/%-]
111
+ const safeKey = (raw: string | undefined | null): string =>
112
+ (raw && raw.length > 0 ? raw : "unknown").replace(/[^a-zA-Z0-9._:-]/g, "_").slice(0, 120);
113
+
114
+ const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
115
+
116
+ /**
117
+ * Locate the engine's follow-up header (src/slack/thread-buffer.ts): at the start of the
118
+ * description, or right after the closing `</thread_context>`. Thread context quotes old
119
+ * messages verbatim, so a header (or a `</thread_context>`) quoted inside it is skipped.
120
+ */
121
+ const findHeader = (description: string): { index: number; end: number } | null => {
122
+ for (const m of description.matchAll(HEADER_LINE_RE)) {
123
+ const index = m.index! + (m[0].startsWith("\n") ? 1 : 0);
124
+ const before = description.slice(0, index);
125
+ const open = before.indexOf(CTX_OPEN);
126
+ if (open < 0 || before.trimEnd().endsWith(CTX_CLOSE)) {
127
+ return { index, end: m.index! + m[0].length };
128
+ }
129
+ }
130
+ return null;
131
+ };
132
+
133
+ /**
134
+ * Split a buffered follow-up description into thread context and new messages, or null
135
+ * when the description is not a buffered follow-up. Only `messages` is new text.
136
+ */
137
+ export const parseFollowUp = (
138
+ description: string,
139
+ ): { context: string[]; messages: string[] } | null => {
140
+ const header = findHeader(description);
141
+ if (!header) return null;
142
+ const before = description.slice(0, header.index).trimEnd();
143
+ const open = before.indexOf(CTX_OPEN);
144
+ const context =
145
+ open >= 0
146
+ ? before
147
+ .slice(open + CTX_OPEN.length, before.length - CTX_CLOSE.length)
148
+ .split(/\n(?=<@[A-Z0-9]+[|>]|\[Agent\]:)/)
149
+ .map((m) => m.trim())
150
+ .filter(Boolean)
151
+ : [];
152
+ const messages = description
153
+ .slice(header.end)
154
+ .split("\n---\n")
155
+ .map((m) => m.trim())
156
+ .filter(Boolean);
157
+ return { context, messages };
158
+ };
159
+
160
+ /** True when the new text addresses Lead with an @mention. */
161
+ export const mentionsLead = (text: string, aliases: readonly string[]): boolean => {
162
+ // The buffer rewrites a mention of the swarm's own bot to `<@U…> (that's you)`.
163
+ if (/<@[A-Z0-9]+>\s*\(that's you\)/.test(text)) return true;
164
+ const names = aliases
165
+ .map((a) => a.trim())
166
+ .filter(Boolean)
167
+ .map(escapeRe);
168
+ if (names.length === 0) return false;
169
+ const alt = names.join("|");
170
+ return (
171
+ new RegExp(`(^|[^\\w@])@(${alt})\\b`, "i").test(text) ||
172
+ new RegExp(`<@[A-Z0-9]+\\|(${alt})>`, "i").test(text)
173
+ );
174
+ };
175
+
176
+ const secretCache = new Map<string, { value: string; at: number }>();
177
+ const KEY_TTL_MS = 5 * 60 * 1000;
178
+ const usable = (v: string): boolean => Boolean(v) && !v.startsWith("[REDACTED");
179
+ const envOf = (name: string): string => String(process.env[name] ?? "");
180
+
181
+ /**
182
+ * Resolve a secret: explicit value, then the API process env. The API process loads
183
+ * global swarm_config rows into process.env at boot and on config reload.
184
+ * ctx.swarm.config_get cannot serve it: the SDK scrubs secrets to "[REDACTED:<name>]".
185
+ */
186
+ const secret = (name: string, explicit?: string): string => {
187
+ const cached = secretCache.get(name);
188
+ if (cached && Date.now() - cached.at < KEY_TTL_MS) return cached.value;
189
+ const value = [String(explicit ?? ""), envOf(name)].find(usable) ?? "";
190
+ if (usable(value)) secretCache.set(name, { value, at: Date.now() });
191
+ return value;
192
+ };
193
+
194
+ /** Test hook: forget cached secrets. */
195
+ export const resetKeyCache = (): void => {
196
+ secretCache.clear();
197
+ };
198
+
199
+ export type JevTransport = {
200
+ provider: "typesafe" | "openrouter";
201
+ endpoint: string;
202
+ key: string;
203
+ model: string;
204
+ };
205
+
206
+ /**
207
+ * Pick the Jev transport. `auto` prefers TypeSafe and falls back to OpenRouter.
208
+ * Throws when the chosen provider has no usable key; the handler fails open.
209
+ */
210
+ export const resolveTransport = (cfg: Cfg): JevTransport => {
211
+ const typesafe = (): JevTransport | null => {
212
+ const key = secret("TYPESAFE_API_KEY", cfg.apiKey);
213
+ return usable(key)
214
+ ? { provider: "typesafe", endpoint: TYPESAFE_ENDPOINT, key, model: cfg.model }
215
+ : null;
216
+ };
217
+ const openrouter = (): JevTransport | null => {
218
+ const key = secret("OPENROUTER_API_KEY");
219
+ return usable(key)
220
+ ? { provider: "openrouter", endpoint: OPENROUTER_ENDPOINT, key, model: cfg.openrouterModel }
221
+ : null;
222
+ };
223
+ const transport =
224
+ cfg.provider === "typesafe"
225
+ ? typesafe()
226
+ : cfg.provider === "openrouter"
227
+ ? openrouter()
228
+ : (typesafe() ?? openrouter());
229
+ if (transport) return transport;
230
+ throw new Error(
231
+ cfg.provider === "typesafe"
232
+ ? "no TYPESAFE_API_KEY"
233
+ : cfg.provider === "openrouter"
234
+ ? "no OPENROUTER_API_KEY"
235
+ : "no TYPESAFE_API_KEY or OPENROUTER_API_KEY",
236
+ );
237
+ };
238
+
239
+ const SLACK_API = "https://slack.com/api";
240
+ // The engine's acceptance reactions (src/slack/reaction-shortcode.ts), by config key.
241
+ const ACCEPTANCE_REACTIONS: ReadonlyArray<[string, string]> = [
242
+ ["SLACK_REACTION_ACCEPTED", "eyes"],
243
+ ["SLACK_REACTION_BUFFERED", "heavy_plus_sign"],
244
+ ["SLACK_REACTION_NOW", "zap"],
245
+ ["SLACK_REACTION_STEERED", "speech_balloon"],
246
+ ];
247
+ const SHORTCODE_RE = /^[a-z0-9_+'-]+(::skin-tone-[2-6])?$/;
248
+ const shortcode = (raw: string): string | null => {
249
+ const s = raw.trim().replace(/^:/, "").replace(/:$/, "").toLowerCase();
250
+ return s && SHORTCODE_RE.test(s) ? s : null;
251
+ };
252
+
253
+ /** The acceptance reactions the engine may have put on the message, deduplicated. */
254
+ export const acceptanceReactions = (): string[] => [
255
+ ...new Set(ACCEPTANCE_REACTIONS.map(([key, fallback]) => shortcode(envOf(key)) ?? fallback)),
256
+ ];
257
+
258
+ const slackCall = async (
259
+ method: string,
260
+ token: string,
261
+ body: Record<string, string>,
262
+ timeoutMs: number,
263
+ ): Promise<{ ok: boolean; error?: string }> => {
264
+ const controller = new AbortController();
265
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
266
+ try {
267
+ const res = await fetch(`${SLACK_API}/${method}`, {
268
+ method: "POST",
269
+ headers: {
270
+ "Content-Type": "application/json; charset=utf-8",
271
+ Authorization: `Bearer ${token}`,
272
+ },
273
+ body: JSON.stringify(body),
274
+ signal: controller.signal,
275
+ });
276
+ if (!res.ok) return { ok: false, error: `http_${res.status}` };
277
+ const data = (await res.json()) as { ok?: boolean; error?: string };
278
+ return { ok: data?.ok === true, error: data?.error };
279
+ } finally {
280
+ clearTimeout(timer);
281
+ }
282
+ };
283
+
284
+ export type MuteResult = { removed: string[]; added: boolean; errors: string[] };
285
+
286
+ /**
287
+ * Replace the bot's acceptance reaction(s) on one message with `name`, or only
288
+ * remove them when `name` is "". `reactions.remove` only removes the calling
289
+ * bot's own reaction, so a human's :eyes: stays. Never throws: every failure
290
+ * lands in `errors`.
291
+ */
292
+ export const muteMessage = async (
293
+ token: string,
294
+ channel: string,
295
+ timestamp: string,
296
+ name: string,
297
+ timeoutMs: number,
298
+ ): Promise<MuteResult> => {
299
+ const result: MuteResult = { removed: [], added: false, errors: [] };
300
+ const call = (method: string, reaction: string) =>
301
+ slackCall(method, token, { channel, timestamp, name: reaction }, timeoutMs).catch(
302
+ (err): { ok: boolean; error?: string } => ({ ok: false, error: String(err).slice(0, 120) }),
303
+ );
304
+ const removals = acceptanceReactions().filter((r) => r !== name);
305
+ const removed = await Promise.all(removals.map((r) => call("reactions.remove", r)));
306
+ removed.forEach((res, i) => {
307
+ const reaction = removals[i]!;
308
+ if (res.ok) result.removed.push(reaction);
309
+ else if (res.error !== "no_reaction" && res.error !== "invalid_name")
310
+ result.errors.push(`remove ${reaction}: ${res.error ?? "unknown"}`);
311
+ });
312
+ if (!name) return result;
313
+ const added = await call("reactions.add", name);
314
+ if (added.ok || added.error === "already_reacted") result.added = true;
315
+ else result.errors.push(`add ${name}: ${added.error ?? "unknown"}`);
316
+ return result;
317
+ };
318
+
319
+ // In-flight mutes, so tests can await the work the handler does not wait for.
320
+ const pendingMutes = new Set<Promise<void>>();
321
+ /** Test hook: wait for every in-flight mute. */
322
+ export const settleMutes = async (): Promise<void> => {
323
+ await Promise.allSettled([...pendingMutes]);
324
+ };
325
+
326
+ export type JevVerdict = {
327
+ reason: string;
328
+ confidence: number | null;
329
+ probabilities: Record<string, number> | null;
330
+ latencyMs: number;
331
+ };
332
+
333
+ /**
334
+ * One Jev call: classify the newest message into a reason. Throws on any failure.
335
+ * TypeSafe and OpenRouter share the request body and the `answers` response shape.
336
+ */
337
+ export const askJev = async (
338
+ input: {
339
+ messages: string[];
340
+ context: string[];
341
+ sender: string;
342
+ leadNames: readonly string[];
343
+ },
344
+ transport: JevTransport,
345
+ cfg: Cfg,
346
+ outer?: AbortSignal,
347
+ ): Promise<JevVerdict> => {
348
+ const controller = new AbortController();
349
+ const timer = setTimeout(() => controller.abort(), Math.min(cfg.timeoutMs, MAX_TIMEOUT_MS));
350
+ const onOuterAbort = () => controller.abort();
351
+ outer?.addEventListener("abort", onOuterAbort);
352
+ const t0 = Date.now();
353
+ try {
354
+ const res = await fetch(transport.endpoint, {
355
+ method: "POST",
356
+ headers: {
357
+ "Content-Type": "application/json",
358
+ Authorization: `Bearer ${transport.key}`,
359
+ },
360
+ body: JSON.stringify({
361
+ state: {
362
+ role: "Decide whether Lead, the coordinating AI agent of a team's agent swarm, should answer a new Slack message in a thread it takes part in. Lead is woken by every message in the thread, including ones not meant for it. Answering noise wastes everyone's time; missing a real ask is worse.",
363
+ lead_names: input.leadNames,
364
+ recent_thread_messages: input.context,
365
+ new_message: input.messages.join("\n---\n"),
366
+ new_message_sender: input.sender,
367
+ },
368
+ model: transport.model,
369
+ questions: {
370
+ reason: {
371
+ type: "choice",
372
+ instructions:
373
+ "Which label best describes new_message from Lead's point of view? Use recent_thread_messages to tell who it is talking to. Lines starting with [Agent] are swarm bots.",
374
+ criteria: REASONS,
375
+ },
376
+ },
377
+ }),
378
+ signal: controller.signal,
379
+ });
380
+ if (!res.ok) throw new Error(`${transport.provider} ${res.status}`);
381
+ const body = (await res.json()) as {
382
+ answers?: { reason?: { choice?: unknown; confidence?: unknown; probabilities?: unknown } };
383
+ } | null;
384
+ const answer = body?.answers?.reason;
385
+ const reason = typeof answer?.choice === "string" ? answer.choice : "";
386
+ if (!(reason in REASONS)) throw new Error(`unexpected choice: ${String(reason).slice(0, 60)}`);
387
+ const confidence = typeof answer?.confidence === "number" ? answer.confidence : null;
388
+ const probabilities =
389
+ answer?.probabilities && typeof answer.probabilities === "object"
390
+ ? (answer.probabilities as Record<string, number>)
391
+ : null;
392
+ return { reason, confidence, probabilities, latencyMs: Date.now() - t0 };
393
+ } finally {
394
+ clearTimeout(timer);
395
+ outer?.removeEventListener("abort", onOuterAbort);
396
+ }
397
+ };
398
+
399
+ /** Probability that the message needs no reply: the summed mass of the skip labels. */
400
+ export const skipProbability = (verdict: JevVerdict): number | null => {
401
+ if (verdict.probabilities) {
402
+ let sum = 0;
403
+ for (const [label, p] of Object.entries(verdict.probabilities)) {
404
+ if (SKIP_REASONS.has(label) && typeof p === "number") sum += p;
405
+ }
406
+ return sum;
407
+ }
408
+ return verdict.confidence;
409
+ };
410
+
411
+ /** Map a Jev verdict to the typed decision. An unsure skip verdict replies. */
412
+ export const decide = (
413
+ verdict: JevVerdict,
414
+ minConfidence: number,
415
+ ): { reply: boolean; reason: Reason; skipP: number | null; lowConfidence: boolean } => {
416
+ const reason = verdict.reason as Reason;
417
+ const skipP = skipProbability(verdict);
418
+ if (!SKIP_REASONS.has(reason)) return { reply: true, reason, skipP, lowConfidence: false };
419
+ const lowConfidence = skipP !== null && skipP < minConfidence;
420
+ return { reply: lowConfidence, reason, skipP, lowConfidence };
421
+ };
422
+
423
+ const record = async (
424
+ swarm: Swarm,
425
+ entry: Record<string, unknown>,
426
+ counters: string[],
427
+ prefix: "d" | "m" = "d",
428
+ ) => {
429
+ const at = new Date().toISOString();
430
+ const thread = safeKey(`${entry.channelId ?? ""}_${entry.threadTs ?? ""}`);
431
+ const value = { at, ...entry };
432
+ await Promise.allSettled([
433
+ swarm.kv_set({ namespace: NS, key: `${prefix}:${Date.now()}:${thread}`, value }),
434
+ // `last` stays the latest decision; mute outcomes only get their own row.
435
+ ...(prefix === "d" ? [swarm.kv_set({ namespace: NS, key: "last", value })] : []),
436
+ ...counters.map((c) => swarm.kv_incr({ namespace: NS, key: safeKey(c) })),
437
+ ]);
438
+ };
439
+
440
+ /** Mute the triggering message and log the outcome. Never throws. */
441
+ const muteTrigger = async (
442
+ swarm: Swarm,
443
+ cfg: Cfg,
444
+ base: Record<string, unknown>,
445
+ ): Promise<void> => {
446
+ try {
447
+ const channel = String(base.channelId ?? "");
448
+ const ts = String(base.triggerTs ?? "");
449
+ if (!channel || !ts) throw new Error("no slackChannelId or slackTriggerMessageTs");
450
+ const token = secret("SLACK_BOT_TOKEN");
451
+ if (!usable(token)) throw new Error("no SLACK_BOT_TOKEN");
452
+ const result = await muteMessage(token, channel, ts, cfg.muteReaction, cfg.slackTimeoutMs);
453
+ // "" adds nothing: success is clearing the acceptance reaction(s).
454
+ const done = cfg.muteReaction ? "muted" : "unreacted";
455
+ const ok = (result.added || !cfg.muteReaction) && result.errors.length === 0;
456
+ const action = ok ? done : "mute-error";
457
+ await record(swarm, { ...base, action, ...result }, [action], "m");
458
+ } catch (err) {
459
+ await record(
460
+ swarm,
461
+ { ...base, action: "mute-error", errors: [String(err).slice(0, 300)] },
462
+ ["mute-error"],
463
+ "m",
464
+ ).catch(() => {});
465
+ }
466
+ };
467
+
468
+ const extension: SwarmExtension = (api) => {
469
+ api.on("pre.task.create", async (event, ctx) => {
470
+ if (event.origin !== "slack") return;
471
+ // Only buffered follow-ups. A direct @mention task never carries the header outside
472
+ // its thread context.
473
+ const followUp = parseFollowUp(event.description);
474
+ if (!followUp) return;
475
+
476
+ const cfg = cfgOf(ctx.config);
477
+ if (cfg.mode === "off") return;
478
+
479
+ const opts = event.options;
480
+ const base = {
481
+ mode: cfg.mode,
482
+ channelId: opts.slackChannelId,
483
+ threadTs: opts.slackThreadTs,
484
+ triggerTs: opts.slackTriggerMessageTs,
485
+ senderSlackId: opts.slackUserId,
486
+ };
487
+
488
+ try {
489
+ // A draft follow-up carries downloaded files: always let Lead see them.
490
+ if (opts.status === "draft") {
491
+ await record(ctx.swarm, { ...base, action: "pass", reason: "has_files" }, [
492
+ "total",
493
+ "files",
494
+ ]);
495
+ return;
496
+ }
497
+
498
+ // The mention check reads only the new messages, never the thread context.
499
+ const { context, messages } = followUp;
500
+ const preview = messages.join(" | ").slice(0, 300);
501
+
502
+ if (messages.some((m) => mentionsLead(m, cfg.leadAliases))) {
503
+ await record(ctx.swarm, { ...base, action: "pass", reason: "mention", preview }, [
504
+ "total",
505
+ "mention",
506
+ ]);
507
+ return;
508
+ }
509
+
510
+ const transport = resolveTransport(cfg);
511
+
512
+ const sender =
513
+ opts.slackUserId && cfg.botSlackUserIds.includes(opts.slackUserId)
514
+ ? "bot"
515
+ : opts.requestedByUserId
516
+ ? "human (known teammate)"
517
+ : "unknown (not a known teammate; may be a bot or an external person)";
518
+
519
+ const verdict = await askJev(
520
+ {
521
+ messages,
522
+ context: context.slice(-cfg.contextMessages).map((m) => m.slice(0, 500)),
523
+ sender,
524
+ leadNames: cfg.leadAliases,
525
+ },
526
+ transport,
527
+ cfg,
528
+ ctx.signal,
529
+ );
530
+ const decision = decide(verdict, cfg.minConfidence);
531
+
532
+ const skip = !decision.reply;
533
+ const action = skip ? (cfg.mode === "enforce" ? "skipped" : "shadow-skip") : "pass";
534
+ await record(
535
+ ctx.swarm,
536
+ {
537
+ ...base,
538
+ action,
539
+ reply: decision.reply,
540
+ reason: decision.reason,
541
+ confidence: verdict.confidence,
542
+ skipP: decision.skipP,
543
+ lowConfidence: decision.lowConfidence,
544
+ latencyMs: verdict.latencyMs,
545
+ provider: transport.provider,
546
+ sender,
547
+ preview,
548
+ },
549
+ ["total", skip ? action : "reply", `reason:${decision.reason}`],
550
+ );
551
+
552
+ if (skip && cfg.mode === "enforce") {
553
+ // Not awaited: the block must return inside the dispatcher's 5 s budget
554
+ // whatever Slack does, and a failed reaction never changes the drop.
555
+ // An empty (or invalid) muteReaction still clears the acceptance reaction(s).
556
+ const muteReaction = shortcode(cfg.muteReaction) ?? "";
557
+ const pending = muteTrigger(ctx.swarm, { ...cfg, muteReaction }, base);
558
+ pendingMutes.add(pending);
559
+ void pending.finally(() => pendingMutes.delete(pending));
560
+ return block(
561
+ `slack-reply-gate: no reply needed (${decision.reason}${decision.skipP !== null ? `, p(skip) ${decision.skipP.toFixed(2)}` : ""})`,
562
+ );
563
+ }
564
+ return;
565
+ } catch (err) {
566
+ // Fail open, always.
567
+ try {
568
+ await record(
569
+ ctx.swarm,
570
+ { ...base, action: "fail-open", error: String(err).slice(0, 300) },
571
+ ["total", "error"],
572
+ );
573
+ } catch {
574
+ /* ignore */
575
+ }
576
+ ctx.log.warn("slack-reply-gate: failing open", { error: String(err) });
577
+ return;
578
+ }
579
+ });
580
+ };
581
+
582
+ export default extension;
@@ -0,0 +1,8 @@
1
+ {
2
+ "$schema": "../manifest.schema.json",
3
+ "name": "slack-reply-gate",
4
+ "description": "Asks Jev (TypeSafe or OpenRouter) whether Lead should answer a buffered Slack thread follow-up, and drops the wake-up when it should not",
5
+ "version": "1.2.0",
6
+ "runtime": "api",
7
+ "assets": { "hooks": "hooks.ts" }
8
+ }
@@ -47,6 +47,8 @@ agent-browser close
47
47
 
48
48
  ## Recording
49
49
 
50
+ Pass `record start` an absolute path (`/tmp/<topic>/raw.webm`). A relative path resolves against the agent-browser daemon's cwd, not yours, and fails with `ffmpeg write failed: Broken pipe` while `doctor` stays green.
51
+
50
52
  Default: record with `--cursor`, drive every supported pointer action (`click`, `mouse move`, `drag`) with `--human`, and ship the **1.5x video**. Keep the 1x original only if a reviewer asks for it. Human pointer movement follows an eased curve; use `--seed <n>` on `mouse move` to make the take reproducible instead of using a bare move.
51
53
 
52
54
  Open the page first, then record the interaction:
@@ -42,6 +42,8 @@ agent-browser close
42
42
 
43
43
  ## Recording
44
44
 
45
+ Pass `record start` an absolute path (`/tmp/<topic>/raw.webm`). A relative path resolves against the agent-browser daemon's cwd, not yours, and fails with `ffmpeg write failed: Broken pipe` while `doctor` stays green.
46
+
45
47
  Default: record with `--cursor`, drive every supported pointer action (`click`, `mouse move`, `drag`) with `--human`, and ship the **1.5x video**. Keep the 1x original only if a reviewer asks for it. Human pointer movement follows an eased curve; use `--seed <n>` on `mouse move` to make the take reproducible instead of using a bare move.
46
48
 
47
49
  Open the page first, then record the interaction:
@@ -38,6 +38,7 @@ The Repository Guidelines carry `allowMerge` and `mergeChecks`.
38
38
 
39
39
  ## Review a PR
40
40
 
41
+ 0. Re-review check. If you reviewed this PR before, compare `gh pr view <number> --json headRefOid --jq .headRefOid` with the `commit_id` of your last review (`gh api repos/<owner>/<repo>/pulls/<number>/reviews`). Same SHA: reuse that verdict, link it and stop. New SHA: review the diff since that commit, then run the full list below. If the new head merged or rebased main, also read every conflict resolution (files both sides touched), check migration numbering and order against main, grep for stale migration numbers, and confirm CI is green at the exact head you review.
41
42
  1. CI status first, including the fork checks below before treating CI as evidence. Failing CI is a REQUEST_CHANGES. Name the failing checks in the review.
42
43
  2. Detect a GitHub fork PR with `gh pr view <number> --json isCrossRepository --jq .isCrossRepository`.
43
44
  3. For a GitHub fork PR, inspect held runs with `SHA=$(gh pr view <number> --json headRefOid --jq .headRefOid); gh api --paginate "repos/<owner>/<repo>/actions/runs?head_sha=$SHA" --jq '.workflow_runs[] | "\(.conclusion // .status)|\(.name)"'`; `gh pr checks` and `statusCheckRollup` can omit them.
@@ -27,7 +27,7 @@ Two kinds of sections:
27
27
 
28
28
  ## Handle a heartbeat-checklist task
29
29
 
30
- 0. Quiet check. Take the fast path when three things hold: the system status shows no failed, stalled or reboot-interrupted task; no mention has gone unanswered since the last heartbeat; and no tracked item in the task's runbook snapshot is at or past its date. On the fast path, run the two step 3 scripts. If both are clean, complete with one line that names the zero counts and skip steps 1, 2 and 4-7. Anything non-zero means continue at step 1.
30
+ 0. Quiet check. Take the fast path when three things hold: every failed, stalled or reboot-interrupted task in the system status was already named in the previous heartbeat-checklist task's output (newest completed one via `get-tasks`); no mention has gone unanswered since the last heartbeat; and no tracked item in the task's runbook snapshot is at or past its date. On the fast path, run the two step 3 scripts. If they report nothing the previous heartbeat had not already triaged, complete with one line citing the previous heartbeat task id and the counts, and skip steps 1, 2 and 4-7. Anything new means continue at step 1.
31
31
  1. Read the latest runbook. The snapshot in the task may be stale.
32
32
  2. Prune first. Check every tracked item against its lift trigger. Remove resolved, stale, and past-date items.
33
33
  3. Run the seeded scripts: `script-run` with name `schedule-health`, then `task-failure-audit`, both with `args: { days: 1, publishPage: false }`. They report failing schedules and failure clusters. Check any other standing order in the runbook yourself.
@@ -142,6 +142,16 @@ function rowsToObjects(res: any): any[] {
142
142
 
143
143
  `ctx.swarm.db_query` throttles at about three concurrent calls. A wider `Promise.all` fan-out can return 429 responses with no `rows` key, so `res?.data?.rows ?? []` misreads throttling as a clean zero. Check the response status and `data.error` before reading `rows`. Serialize queries or cap concurrency at three.
144
144
 
145
+ ### Response traps
146
+
147
+ - Every `ctx.swarm.*` response passes the secret scrubber. Text shaped like a secret-looking `key=value` assignment comes back as `[REDACTED:<key>]`, so code, HTML or profile text read through `kv_get`, `db_query` or a page read can differ from the stored bytes. Never write such a read back verbatim. Read stored text as `hex(...)` through `db_query`, decode it in the script, and refuse to publish or write when the result contains `[REDACTED:`.
148
+ - `db_query` rejects any SQL containing `;`, even inside a string literal. Pass such literals through `params`.
149
+ - `db_query` caps rows without an error (1000 in scripts). Aggregate in SQL and confirm totals with `COUNT(*)`.
150
+ - `kv_get` returns the entry at `data`: read `res.data.value`. The MCP tool shape `entry.value` reads `undefined` in a script.
151
+ - `script_run` returns an envelope (`result`, `truncated`, `durationMs`, `stdout`, `stderr`, `exitCode`). The callee payload is at `.result`. Take key names from a real response: a guessed key that is absent reads as a false zero.
152
+ - An `argsSchema` validation error fires before the body runs and repeats on every retry. Fix the args instead of retrying.
153
+ - Write a dedup or idempotency marker only after the step succeeds. A marker written after a failure blocks the next real attempt.
154
+
145
155
  Common tables: `agent_tasks`, `session_logs`, `agent_memory`, `scheduled_tasks`, `agents`. `session_logs` has no `tool_name` column. Tool names sit inside the `content` JSON column. Extract them with `instr` and `substr` in SQL, or parse the JSON in the script.
146
156
 
147
157
  ## Progress from a script
@@ -137,6 +137,16 @@ function rowsToObjects(res: any): any[] {
137
137
 
138
138
  `ctx.swarm.db_query` throttles at about three concurrent calls. A wider `Promise.all` fan-out can return 429 responses with no `rows` key, so `res?.data?.rows ?? []` misreads throttling as a clean zero. Check the response status and `data.error` before reading `rows`. Serialize queries or cap concurrency at three.
139
139
 
140
+ ### Response traps
141
+
142
+ - Every `ctx.swarm.*` response passes the secret scrubber. Text shaped like a secret-looking `key=value` assignment comes back as `[REDACTED:<key>]`, so code, HTML or profile text read through `kv_get`, `db_query` or a page read can differ from the stored bytes. Never write such a read back verbatim. Read stored text as `hex(...)` through `db_query`, decode it in the script, and refuse to publish or write when the result contains `[REDACTED:`.
143
+ - `db_query` rejects any SQL containing `;`, even inside a string literal. Pass such literals through `params`.
144
+ - `db_query` caps rows without an error (1000 in scripts). Aggregate in SQL and confirm totals with `COUNT(*)`.
145
+ - `kv_get` returns the entry at `data`: read `res.data.value`. The MCP tool shape `entry.value` reads `undefined` in a script.
146
+ - `script_run` returns an envelope (`result`, `truncated`, `durationMs`, `stdout`, `stderr`, `exitCode`). The callee payload is at `.result`. Take key names from a real response: a guessed key that is absent reads as a false zero.
147
+ - An `argsSchema` validation error fires before the body runs and repeats on every retry. Fix the args instead of retrying.
148
+ - Write a dedup or idempotency marker only after the step succeeds. A marker written after a failure blocks the next real attempt.
149
+
140
150
  Common tables: `agent_tasks`, `session_logs`, `agent_memory`, `scheduled_tasks`, `agents`. `session_logs` has no `tool_name` column. Tool names sit inside the `content` JSON column. Extract them with `instr` and `substr` in SQL, or parse the JSON in the script.
141
151
 
142
152
  ## Progress from a script