@desplega.ai/agent-swarm 1.131.0 → 1.133.1

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 (265) hide show
  1. package/README.md +2 -2
  2. package/dist/{actions-w53mbns9.js → actions-cskpayd7.js} +11 -9
  3. package/dist/{anthropic-messages-rjmd2e7n.js → anthropic-messages-tpxtbx7b.js} +28 -12
  4. package/dist/{app-m9gwqsqv.js → app-ang77nbb.js} +8 -6
  5. package/dist/{assistant-bp65m6f3.js → assistant-b4exebdw.js} +16 -13
  6. package/dist/{azure-openai-responses-c0yjmbfd.js → azure-openai-responses-m3921t4y.js} +8 -8
  7. package/dist/{boot-reembed-62p0at2k.js → boot-reembed-ps2aftpb.js} +9 -7
  8. package/dist/{boot-reembed-xmfp6wdh.js → boot-reembed-znyk3nxb.js} +10 -8
  9. package/dist/{boot-scrub-logs-rr8q2dms.js → boot-scrub-logs-2ax3xgz1.js} +7 -5
  10. package/dist/{claude-adapter-2y47mrkd.js → claude-adapter-3ct8kgxw.js} +13 -9
  11. package/dist/{claude-managed-adapter-gv19tdew.js → claude-managed-adapter-akx4ntf2.js} +2 -2
  12. package/dist/{cli-t1xze5qh.js → cli-13w2hwkh.js} +1 -1
  13. package/dist/{cli-efxfnq6q.js → cli-1532szb1.js} +8 -6
  14. package/dist/{cli-d2tfkcga.js → cli-23d3rseb.js} +33 -17
  15. package/dist/{cli-nm5gtp1x.js → cli-2a75z9c5.js} +196 -7
  16. package/dist/{cli-fywms69x.js → cli-2t30rj0d.js} +1 -1
  17. package/dist/{cli-cvgjwnh1.js → cli-3c3tdgab.js} +10 -10
  18. package/dist/{cli-pm6xbh84.js → cli-3zzxa9jz.js} +46 -16
  19. package/dist/{cli-cdeg08wx.js → cli-4k6233gc.js} +1 -1
  20. package/dist/{cli-t55yw3a1.js → cli-5p2tz05r.js} +2 -2
  21. package/dist/{cli-0rcyq6d9.js → cli-5z2yhzvd.js} +125 -47
  22. package/dist/{cli-3kf51j15.js → cli-6zfq31nj.js} +9 -3
  23. package/dist/{cli-er3a4bb0.js → cli-8m9de10a.js} +6 -1
  24. package/dist/{cli-gm9cbhbq.js → cli-8t14vg9w.js} +27 -8
  25. package/dist/{cli-72q8m8gk.js → cli-9nfc2es8.js} +6 -6
  26. package/dist/{cli-5ze9rv97.js → cli-9ta3pwms.js} +11 -4
  27. package/dist/{cli-78xwvkhj.js → cli-avr0ns7z.js} +2 -2
  28. package/dist/{cli-n6h8qt8n.js → cli-c897wyhw.js} +12 -7
  29. package/dist/{cli-2q72qz2s.js → cli-dgk20ft7.js} +15 -6
  30. package/dist/cli-et1bbwqf.js +13 -0
  31. package/dist/{cli-bqw0mt1n.js → cli-f5w27pj3.js} +3 -3
  32. package/dist/{cli-2wadx7p2.js → cli-f8dre4bz.js} +2 -2
  33. package/dist/{cli-e7ckcg4v.js → cli-ftwpv451.js} +170 -387
  34. package/dist/{cli-g6b8x1h8.js → cli-g854s2dw.js} +1 -1
  35. package/dist/{cli-5kx36evn.js → cli-ggmdxeqa.js} +13 -8
  36. package/dist/cli-hkwfe3qj.js +530 -0
  37. package/dist/{cli-5dsbcjjw.js → cli-jqwnqx9m.js} +1 -1
  38. package/dist/{cli-9dr5qzc0.js → cli-ny122vh4.js} +21 -10
  39. package/dist/{cli-5v4rw6yd.js → cli-pvzqhbs9.js} +2 -2
  40. package/dist/cli-pzq5rjym.js +15 -0
  41. package/dist/{cli-xpxde7rm.js → cli-qes8ef67.js} +48 -30
  42. package/dist/{cli-sajgpkqg.js → cli-qs9hhsvb.js} +1723 -325
  43. package/dist/cli-qys3rhhz.js +27 -0
  44. package/dist/{cli-rzbpmxdr.js → cli-r6tpm37h.js} +2 -2
  45. package/dist/{cli-qv61hp37.js → cli-rch80c76.js} +2 -2
  46. package/dist/{cli-0258203w.js → cli-rpp0x4zy.js} +137 -17
  47. package/dist/{cli-5n6e5yfn.js → cli-s1k0wxhe.js} +12 -7
  48. package/dist/{cli-psh3c4va.js → cli-sfd9v7sj.js} +1 -1
  49. package/dist/{cli-70xqj0z3.js → cli-sh3ytsyj.js} +49 -39
  50. package/dist/{cli-zsspvvm2.js → cli-w1mp9jy7.js} +1 -1
  51. package/dist/{cli-d3x3x1c9.js → cli-xdb4mpnp.js} +2 -2
  52. package/dist/{cli-57khth04.js → cli-xmyqv00z.js} +120 -4
  53. package/dist/{cli-yw8vghx2.js → cli-xv8t8p3c.js} +65 -32
  54. package/dist/{cli-f1am9szv.js → cli-xxv5pn4f.js} +1 -1
  55. package/dist/{cli-t76vw5db.js → cli-y08jvxzx.js} +601 -140
  56. package/dist/{cli-a4jzdpa3.js → cli-zfbf3srj.js} +650 -245
  57. package/dist/{cli-a40rnf71.js → cli-zmq89k34.js} +6 -6
  58. package/dist/{cli-qmdnhpej.js → cli-zr9q011v.js} +23 -13
  59. package/dist/cli.js +22 -22
  60. package/dist/{codex-adapter-d24q75wk.js → codex-adapter-bef93pq4.js} +9 -7
  61. package/dist/{codex-hook-hq54t9ft.js → codex-hook-e8dba65p.js} +3 -2
  62. package/dist/{codex-session-runner-g50vcsex.js → codex-session-runner-5pkxys7x.js} +9 -7
  63. package/dist/{commands-c3nrc5hg.js → commands-e23s1bff.js} +9 -7
  64. package/dist/{db-nt7fg3tw.js → db-m3nabatn.js} +17 -5
  65. package/dist/{google-generative-ai-hysrd8qx.js → google-generative-ai-8maw55xh.js} +11 -8
  66. package/dist/{google-vertex-p5arrga0.js → google-vertex-8vjqmx8g.js} +11 -8
  67. package/dist/{handlers-fkr6swat.js → handlers-akazedvr.js} +16 -13
  68. package/dist/{hook-77wpvnjc.js → hook-ze4cpf0v.js} +55 -41
  69. package/dist/{hook-g019yehy.js → hook-zfqyyenw.js} +10 -7
  70. package/dist/{http-jewj0syk.js → http-sja0n6kw.js} +730 -150
  71. package/dist/index-0gr8vd6k.js +39 -0
  72. package/dist/{index-7n2xpbd4.js → index-354vkhdv.js} +154 -74
  73. package/dist/{index-070v4eyb.js → index-5qthek5t.js} +2 -3
  74. package/dist/{index-hfvggd0z.js → index-95t3cqq5.js} +16 -14
  75. package/dist/{index-9znhar3x.js → index-sea66619.js} +3 -4
  76. package/dist/{index-6gm5he8h.js → index-vpn36mma.js} +15 -13
  77. package/dist/{keepalive-j0fjvqfd.js → keepalive-3sp3meqj.js} +16 -10
  78. package/dist/{lead-1n8x30xe.js → lead-mefeewkf.js} +39 -36
  79. package/dist/{maintenance-gvev11sa.js → maintenance-8tbrbjfg.js} +10 -8
  80. package/dist/mistral-conversations-00zrp7g4.js +717 -0
  81. package/dist/{oauth-refresh-sweep-s9ecsvh0.js → oauth-refresh-sweep-srjwjz6m.js} +8 -6
  82. package/dist/{onboard-pvm5b38w.js → onboard-mt2tgyjg.js} +7 -7
  83. package/dist/{openai-codex-responses-5g27pd6f.js → openai-codex-responses-map32h2s.js} +18 -18
  84. package/dist/{openai-completions-3vkmfz2a.js → openai-completions-w871b1cq.js} +12 -11
  85. package/dist/{openai-responses-dg4t7j7a.js → openai-responses-b0j7xnw8.js} +15 -12
  86. package/dist/{opencode-adapter-1gm38aba.js → opencode-adapter-b39jefcj.js} +5 -3
  87. package/dist/{openrouter-images-g3gm8931.js → openrouter-images-srfkywy0.js} +4 -4
  88. package/dist/{otel-impl-p6jvgd9c.js → otel-impl-z6pxt3j9.js} +224 -9
  89. package/dist/{pi-mono-adapter-t091s27g.js → pi-mono-adapter-btvqmj58.js} +1138 -408
  90. package/dist/{pricing-refresh-k49rcyed.js → pricing-refresh-kyq8cezh.js} +9 -7
  91. package/dist/{rbac-roles-cr80g96t.js → rbac-roles-3ryfrfna.js} +8 -6
  92. package/dist/{rbac-roles-30pspvy7.js → rbac-roles-6qfvbee1.js} +9 -7
  93. package/dist/{render-v2-xm457ng1.js → render-v2-p61ppjey.js} +8 -6
  94. package/dist/{seed-pricing-yhpv35fr.js → seed-pricing-j56bbj4y.js} +8 -6
  95. package/dist/{setup-nytnmwwr.js → setup-tpr6c1kn.js} +2 -2
  96. package/dist/{worker-msytr2cw.js → worker-9w1v0mbb.js} +39 -36
  97. package/openapi.json +542 -16
  98. package/package.json +6 -6
  99. package/src/be/budget-refusal-notify.ts +14 -7
  100. package/src/be/db-queries/task-artifacts.ts +182 -0
  101. package/src/be/db.ts +783 -169
  102. package/src/be/events.ts +5 -0
  103. package/src/be/migrations/130_scratch_script_retention_grace.sql +6 -0
  104. package/src/be/migrations/131_session_logs_created_at_index.sql +2 -0
  105. package/src/be/migrations/132_multi_runtime_instances.sql +44 -0
  106. package/src/be/migrations/133_workflow_run_trigger_type.sql +12 -0
  107. package/src/be/migrations/135_backfill_task_pull_request_attachments.sql +228 -0
  108. package/src/be/migrations/136_task_requester_provenance.sql +37 -0
  109. package/src/be/migrations/137_memory_retrieval_composite_index.sql +1 -0
  110. package/src/be/multi-runtime.ts +430 -0
  111. package/src/be/scripts/db.ts +43 -1
  112. package/src/be/scripts/extract-schema.ts +3 -1
  113. package/src/be/scripts/retention.ts +164 -0
  114. package/src/be/scripts/run-saved.ts +16 -1
  115. package/src/be/scripts/typecheck.ts +3 -2
  116. package/src/be/seed-skills/index.ts +7 -0
  117. package/src/be/steering.ts +1 -1
  118. package/src/be/swarm-config-guard.ts +18 -0
  119. package/src/commands/credential-wait.ts +54 -0
  120. package/src/commands/onboard/steps/core-credentials.tsx +1 -1
  121. package/src/commands/onboard/steps/custom-templates.tsx +1 -1
  122. package/src/commands/onboard/steps/harness-credentials.tsx +1 -1
  123. package/src/commands/onboard/steps/health-check.tsx +1 -1
  124. package/src/commands/onboard/steps/start.tsx +1 -1
  125. package/src/commands/profile-sync-audit.ts +56 -0
  126. package/src/commands/profile-sync.ts +287 -15
  127. package/src/commands/provider-credentials.ts +46 -19
  128. package/src/commands/runner.ts +196 -33
  129. package/src/commands/templates.ts +22 -0
  130. package/src/github/handlers.ts +55 -9
  131. package/src/heartbeat/heartbeat.ts +71 -12
  132. package/src/hooks/hook.ts +49 -33
  133. package/src/http/active-sessions.ts +11 -1
  134. package/src/http/agents.ts +261 -30
  135. package/src/http/all-routes.ts +1 -0
  136. package/src/http/config.ts +13 -2
  137. package/src/http/core.ts +102 -4
  138. package/src/http/db-query-bounded.ts +313 -0
  139. package/src/http/db-query-shared.ts +249 -0
  140. package/src/http/db-query.ts +54 -42
  141. package/src/http/events.ts +2 -0
  142. package/src/http/index.ts +27 -2
  143. package/src/http/mcp-bridge.ts +37 -3
  144. package/src/http/mcp.ts +12 -0
  145. package/src/http/memory.ts +13 -2
  146. package/src/http/openapi.ts +1 -0
  147. package/src/http/poll.ts +70 -27
  148. package/src/http/route-def.ts +43 -9
  149. package/src/http/schedules.ts +2 -2
  150. package/src/http/scripts.ts +31 -4
  151. package/src/http/session-data.ts +44 -0
  152. package/src/http/tasks.ts +2 -2
  153. package/src/http/users.ts +74 -52
  154. package/src/http/webhooks.ts +5 -2
  155. package/src/http/workflows.ts +1 -4
  156. package/src/http/x.ts +14 -0
  157. package/src/integrations/kapso/inbound.ts +1 -1
  158. package/src/jira/outbound.ts +39 -8
  159. package/src/jira/webhook-lifecycle.ts +13 -2
  160. package/src/linear/outbound.ts +43 -10
  161. package/src/oauth/keepalive.ts +13 -2
  162. package/src/prompts/base-prompt.ts +1 -1
  163. package/src/prompts/session-templates.ts +45 -7
  164. package/src/providers/claude-adapter.ts +6 -0
  165. package/src/providers/claude-managed-models.ts +34 -10
  166. package/src/providers/codex-adapter.ts +6 -0
  167. package/src/providers/opencode-adapter.ts +6 -0
  168. package/src/providers/pi-mono-adapter.ts +8 -0
  169. package/src/providers/pricing-sources.md +24 -0
  170. package/src/queue-stall-alarm.ts +216 -0
  171. package/src/scheduler/scheduler.ts +7 -0
  172. package/src/script-workflows/executor.ts +2 -1
  173. package/src/scripts-runtime/executors/native.ts +2 -1
  174. package/src/scripts-runtime/executors/types.ts +5 -0
  175. package/src/scripts-runtime/loader.ts +5 -0
  176. package/src/scripts-runtime/swarm-config.ts +8 -0
  177. package/src/scripts-runtime/swarm-sdk.ts +7 -0
  178. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  179. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  180. package/src/tests/budget-claim-gate.test.ts +20 -0
  181. package/src/tests/claude-adapter.test.ts +32 -0
  182. package/src/tests/claude-managed-adapter.test.ts +38 -7
  183. package/src/tests/codex-adapter.test.ts +30 -0
  184. package/src/tests/create-task-validation.test.ts +128 -0
  185. package/src/tests/credential-wait.test.ts +67 -1
  186. package/src/tests/db-query.test.ts +711 -2
  187. package/src/tests/http-api-integration.test.ts +81 -0
  188. package/src/tests/http-users.test.ts +166 -1
  189. package/src/tests/identity-field-budget.test.ts +176 -0
  190. package/src/tests/mcp-tools-user.test.ts +34 -0
  191. package/src/tests/mcp-user-route.test.ts +17 -0
  192. package/src/tests/metrics-http.test.ts +44 -0
  193. package/src/tests/multi-runtime-registration.test.ts +2703 -0
  194. package/src/tests/openapi-response-contract.test.ts +24 -0
  195. package/src/tests/openapi-route-headers.test.ts +83 -0
  196. package/src/tests/opencode-adapter.test.ts +40 -0
  197. package/src/tests/outbound-listener-rejection.test.ts +138 -0
  198. package/src/tests/pi-mono-adapter.test.ts +98 -0
  199. package/src/tests/profile-sync-warning.test.ts +277 -0
  200. package/src/tests/profile-sync.test.ts +232 -6
  201. package/src/tests/prompt-template-session.test.ts +32 -3
  202. package/src/tests/queue-stall-alarm.test.ts +226 -0
  203. package/src/tests/requester-comms.test.ts +32 -0
  204. package/src/tests/runner-requester-profile.test.ts +38 -0
  205. package/src/tests/sandboxed-process.test.ts +45 -0
  206. package/src/tests/schedule-target-type.test.ts +38 -0
  207. package/src/tests/script-connections.test.ts +16 -3
  208. package/src/tests/scripts-external-api.test.ts +8 -3
  209. package/src/tests/scripts-http.test.ts +12 -0
  210. package/src/tests/scripts-retention.test.ts +384 -0
  211. package/src/tests/scripts-runtime-identity.test.ts +375 -0
  212. package/src/tests/scripts-runtime.test.ts +4 -3
  213. package/src/tests/sdk-allowlist.test.ts +47 -0
  214. package/src/tests/send-task-requested-by.test.ts +9 -0
  215. package/src/tests/session-costs.test.ts +506 -1
  216. package/src/tests/shutdown-error-scrubbing.test.ts +92 -0
  217. package/src/tests/steering-core.test.ts +28 -0
  218. package/src/tests/task-artifacts.test.ts +386 -0
  219. package/src/tests/task-attachments-schema.test.ts +17 -1
  220. package/src/tests/task-completion-idempotency.test.ts +57 -0
  221. package/src/tests/task-pull-request-backfill-migration.test.ts +321 -0
  222. package/src/tests/update-profile-api.test.ts +67 -39
  223. package/src/tests/update-profile-auth.test.ts +48 -4
  224. package/src/tests/user-attribution-migration.test.ts +54 -0
  225. package/src/tests/user-identity.test.ts +72 -0
  226. package/src/tests/workflow-async-v2.test.ts +39 -1
  227. package/src/tests/workflow-http-v2.test.ts +3 -2
  228. package/src/tests/workflow-mcp-trigger-schema.test.ts +52 -3
  229. package/src/tests/workflow-retry-v2.test.ts +45 -1
  230. package/src/tests/workflow-swarm-script.test.ts +14 -5
  231. package/src/tools/db-query.ts +18 -8
  232. package/src/tools/get-task-details.ts +24 -3
  233. package/src/tools/manage-user.ts +36 -3
  234. package/src/tools/poll-task.ts +93 -14
  235. package/src/tools/script-common.ts +5 -0
  236. package/src/tools/send-task.ts +1 -4
  237. package/src/tools/store-progress.ts +13 -2
  238. package/src/tools/swarm-config/delete-config.ts +9 -0
  239. package/src/tools/swarm-config/set-config.ts +3 -2
  240. package/src/tools/task-action.ts +30 -0
  241. package/src/tools/task-tool-ctx.ts +8 -1
  242. package/src/tools/update-profile.ts +16 -21
  243. package/src/tools/utils.ts +5 -0
  244. package/src/tools/workflows/trigger-workflow.ts +7 -1
  245. package/src/types.ts +165 -1
  246. package/src/utils/github-pull-request.ts +76 -0
  247. package/src/utils/identity-field-budget.ts +73 -0
  248. package/src/utils/multi-runtime.ts +20 -0
  249. package/src/utils/requester-comms.ts +24 -0
  250. package/src/utils/sandboxed-process.ts +40 -14
  251. package/src/workflows/engine.ts +22 -2
  252. package/src/workflows/executors/swarm-script.ts +24 -1
  253. package/src/workflows/resume.ts +19 -11
  254. package/src/workflows/retry-poller.ts +1 -0
  255. package/src/workflows/triggers.ts +4 -0
  256. package/templates/schedules/daily-compounding-reflection/content.md +12 -3
  257. package/templates/skills/db-query-guidance/config.json +14 -0
  258. package/templates/skills/db-query-guidance/content.md +57 -0
  259. package/dist/cli-3te4jdkm.js +0 -225
  260. package/dist/cli-bmze986d.js +0 -7
  261. package/dist/cli-kh3ba2zf.js +0 -607
  262. package/dist/index-hp1kdbjj.js +0 -36
  263. package/dist/mistral-conversations-81fwav0j.js +0 -30578
  264. package/dist/otel-nqa12wf3.js +0 -3149
  265. package/dist/{pi-messages-tqj8q6b9.js → pi-messages-sssy32x4.js} +3 -3
@@ -1,15 +1,19 @@
1
+ import {
2
+ IdentityFieldBudgetError,
3
+ checkIdentityFieldBudget,
4
+ init_identity_field_budget,
5
+ init_templates
6
+ } from "./cli-hkwfe3qj.js";
1
7
  import {
2
8
  configureDbResolver,
3
9
  getAllTemplateDefinitions,
4
- init_env_flag,
5
10
  init_registry,
6
11
  init_resolver,
7
12
  init_session_templates,
8
13
  init_steering_enabled,
9
- isEnvFlagEnabled,
10
14
  isSteeringEnabled,
11
15
  registerTemplate
12
- } from "./cli-xpxde7rm.js";
16
+ } from "./cli-qes8ef67.js";
13
17
  import {
14
18
  MAX_PROFILE_FILE_LENGTH,
15
19
  init_constants
@@ -18,18 +22,22 @@ import {
18
22
  deriveProviderFromKeyType,
19
23
  init_credentials
20
24
  } from "./cli-z2zcxes1.js";
25
+ import {
26
+ init_env_flag,
27
+ isEnvFlagEnabled
28
+ } from "./cli-qys3rhhz.js";
21
29
  import {
22
30
  exports_zod,
23
31
  init_zod
24
- } from "./cli-zsspvvm2.js";
32
+ } from "./cli-w1mp9jy7.js";
33
+ import {
34
+ init_package,
35
+ package_default
36
+ } from "./cli-9nfc2es8.js";
25
37
  import {
26
38
  init_secret_scrubber,
27
39
  scrubSecrets
28
40
  } from "./cli-4j2mrzag.js";
29
- import {
30
- init_package,
31
- package_default
32
- } from "./cli-72q8m8gk.js";
33
41
  import {
34
42
  _enum,
35
43
  array,
@@ -37,7 +45,7 @@ import {
37
45
  object,
38
46
  string,
39
47
  union
40
- } from "./cli-5dsbcjjw.js";
48
+ } from "./cli-jqwnqx9m.js";
41
49
  import {
42
50
  __commonJS,
43
51
  __esm,
@@ -2077,7 +2085,7 @@ function resolveTaskModelSelection(opts) {
2077
2085
  function isTerminalTaskStatus(status) {
2078
2086
  return TERMINAL_TASK_STATUSES.includes(status);
2079
2087
  }
2080
- var AssetKeySchema, AssetEntityTypeSchema, AssetProviderRefSchema, AssetKeyMappingSchema, AssetSummarySchema, ModelTierSchema, MODEL_TIERS, ReasoningEffortSchema, LEGACY_MODEL_TO_TIER, DEFAULT_MODEL_TIER_MAP, AgentTaskStatusSchema, TERMINAL_TASK_STATUSES, InboxMessageStatusSchema, InboxMessageSchema, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringStatusSchema, SteeringSourceSchema, SteeringMessageSchema, SteerOutcomeSchema, OnUnsupportedSchema, SteerResultSchema, PROVIDER_STEER_CAPABILITIES, FollowUpConfigSchema, RoutingAffinitySchema, AgentTaskSchema, TaskAttachmentKindSchema, attachmentCommonFields, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, IdentityEventTypeSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentAvatarSchema, AgentSchema, AgentCredStatusLiveTestSchema, AgentLatestModelSchema, AgentBedrockStatusSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChangeSourceSchema, VersionableFieldSchema, ContextVersionSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, AgentLogEventTypeSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostSourceSchema, SessionCostModelBreakdownSchema, SessionCostSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, SwarmEventSchema, ScheduledTaskTargetTypeSchema, ScheduledTaskSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, ActiveSessionSchema, RetryPolicySchema, ExecutorMetaSchema, ValidationResultSchema, StepValidationConfigSchema, SwarmScriptNodeConfigSchema, WorkflowNodeSchema, WorkflowEdgeSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, WebhookVerificationSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, WorkflowTemplateSchema, WorkflowSnapshotSchema, WorkflowSchema, WorkflowVersionSchema, PageContentTypeSchema, PageAuthModeSchema, PageSnapshotSchema, PageSchema, PageVersionSchema, MetricParamSchema, MetricVariableTypeSchema, MetricFormatSchema, MetricVisualizationSchema, MetricQuerySchema, MetricVariableSchema, MetricVizConfigSchema, MetricWidgetSchema, MetricDefinitionSchema, MetricSnapshotSchema, MetricSchema, MetricVersionSchema, WorkflowRunStatusSchema, WorkflowRunSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, ScriptRunKindSchema, ScriptRunSchema, ScriptRunListItemSchema, ScriptRunJournalEntrySchema, WorkflowRunStepStatusSchema, WorkflowRunStepSchema, WaitModeSchema, WaitStateStatusSchema, WaitStateRowSchema, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptRecordSchema, ScriptVersionRecordSchema, ScriptApiAuthModeSchema, ScriptApiRecordSchema, SkillTypeSchema, SkillScopeSchema, SkillSchema, AgentSkillSchema, SkillWithInstallInfoSchema, SkillFileSchema, McpServerTransportSchema, McpServerScopeSchema, McpAuthMethodSchema, McpServerSchema, AgentMcpServerSchema, McpServerWithInstallInfoSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, ContextSnapshotSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, BudgetRefusedTriggerSchema, KvValueTypeSchema, KV_NAME_REGEX, KvNamespaceSchema, KvKeySchema, KvEntrySchema;
2088
+ var AssetKeySchema, AssetEntityTypeSchema, AssetProviderRefSchema, AssetKeyMappingSchema, AssetSummarySchema, ModelTierSchema, MODEL_TIERS, ReasoningEffortSchema, LEGACY_MODEL_TO_TIER, DEFAULT_MODEL_TIER_MAP, AgentTaskStatusSchema, TERMINAL_TASK_STATUSES, InboxMessageStatusSchema, InboxMessageSchema, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringStatusSchema, SteeringSourceSchema, SteeringMessageSchema, SteerOutcomeSchema, OnUnsupportedSchema, SteerResultSchema, PROVIDER_STEER_CAPABILITIES, FollowUpConfigSchema, RoutingAffinitySchema, AgentTaskSchema, CreateTaskOptionsSchema, TaskAttachmentKindSchema, SERVER_GENERATED_ATTACHMENT_CAPABILITY = "_agentSwarmGeneratedBy", attachmentCapabilitiesSchema, attachmentCommonFields, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, UserCommsPrefsSchema, IdentityEventTypeSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentAvatarSchema, AgentSchema, AgentCredStatusLiveTestSchema, AgentLatestModelSchema, AgentBedrockStatusSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChangeSourceSchema, VersionableFieldSchema, ContextVersionSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, AgentLogEventTypeSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostSourceSchema, SessionCostModelBreakdownSchema, SessionCostSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, SwarmEventSchema, ScheduledTaskTargetTypeSchema, ScheduledTaskSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, ActiveSessionSchema, RuntimeInstanceStatusSchema, RuntimeInstanceSchema, RetryPolicySchema, ExecutorMetaSchema, ValidationResultSchema, StepValidationConfigSchema, SwarmScriptNodeConfigSchema, WorkflowNodeSchema, WorkflowEdgeSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, WebhookVerificationSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, WorkflowTemplateSchema, WorkflowSnapshotSchema, WorkflowSchema, WorkflowVersionSchema, PageContentTypeSchema, PageAuthModeSchema, PageSnapshotSchema, PageSchema, PageVersionSchema, MetricParamSchema, MetricVariableTypeSchema, MetricFormatSchema, MetricVisualizationSchema, MetricQuerySchema, MetricVariableSchema, MetricVizConfigSchema, MetricWidgetSchema, MetricDefinitionSchema, MetricSnapshotSchema, MetricSchema, MetricVersionSchema, WorkflowRunStatusSchema, WorkflowRunSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, ScriptRunKindSchema, ScriptRunSchema, ScriptRunListItemSchema, ScriptRunJournalEntrySchema, WorkflowRunStepStatusSchema, WorkflowRunStepSchema, WaitModeSchema, WaitStateStatusSchema, WaitStateRowSchema, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptRecordSchema, ScriptVersionRecordSchema, ScriptApiAuthModeSchema, ScriptApiRecordSchema, SkillTypeSchema, SkillScopeSchema, SkillSchema, AgentSkillSchema, SkillWithInstallInfoSchema, SkillFileSchema, McpServerTransportSchema, McpServerScopeSchema, McpAuthMethodSchema, McpServerSchema, AgentMcpServerSchema, McpServerWithInstallInfoSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, ContextSnapshotSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, BudgetRefusedTriggerSchema, KvValueTypeSchema, KV_NAME_REGEX, KvNamespaceSchema, KvKeySchema, KvEntrySchema;
2081
2089
  var init_types = __esm(() => {
2082
2090
  init_key();
2083
2091
  init_constants();
@@ -2361,12 +2369,62 @@ var init_types = __esm(() => {
2361
2369
  totalCostUsd: exports_zod.number().min(0).optional(),
2362
2370
  routingAffinity: RoutingAffinitySchema.optional()
2363
2371
  }).openapi("AgentTask");
2372
+ CreateTaskOptionsSchema = exports_zod.object({
2373
+ key: exports_zod.string().min(1).optional(),
2374
+ agentId: exports_zod.string().nullable().optional(),
2375
+ creatorAgentId: exports_zod.string().optional(),
2376
+ source: AgentTaskSourceSchema.optional(),
2377
+ taskType: exports_zod.string().max(50).optional(),
2378
+ tags: exports_zod.array(exports_zod.string()).optional(),
2379
+ priority: exports_zod.number().int().min(0).max(100).optional(),
2380
+ dependsOn: exports_zod.array(exports_zod.string()).optional(),
2381
+ offeredTo: exports_zod.string().optional(),
2382
+ status: exports_zod.enum(["backlog", "unassigned"]).optional(),
2383
+ slackChannelId: exports_zod.string().optional(),
2384
+ slackThreadTs: exports_zod.string().optional(),
2385
+ slackTriggerMessageTs: exports_zod.string().optional(),
2386
+ slackUserId: exports_zod.string().optional(),
2387
+ overrideSlackContext: exports_zod.boolean().optional(),
2388
+ vcsProvider: exports_zod.enum(["github", "gitlab"]).optional(),
2389
+ vcsRepo: exports_zod.string().optional(),
2390
+ vcsEventType: exports_zod.string().optional(),
2391
+ vcsNumber: exports_zod.number().int().optional(),
2392
+ vcsCommentId: exports_zod.number().int().optional(),
2393
+ vcsAuthor: exports_zod.string().optional(),
2394
+ vcsUrl: exports_zod.string().optional(),
2395
+ vcsInstallationId: exports_zod.number().int().optional(),
2396
+ vcsNodeId: exports_zod.string().optional(),
2397
+ agentmailInboxId: exports_zod.string().optional(),
2398
+ agentmailMessageId: exports_zod.string().optional(),
2399
+ agentmailThreadId: exports_zod.string().optional(),
2400
+ mentionMessageId: exports_zod.string().optional(),
2401
+ mentionChannelId: exports_zod.string().optional(),
2402
+ dir: exports_zod.string().optional(),
2403
+ parentTaskId: exports_zod.string().optional(),
2404
+ model: exports_zod.string().optional(),
2405
+ modelTier: ModelTierSchema.optional(),
2406
+ effort: ReasoningEffortSchema.optional(),
2407
+ scheduleId: exports_zod.string().optional(),
2408
+ workflowRunId: exports_zod.string().optional(),
2409
+ workflowRunStepId: exports_zod.string().optional(),
2410
+ sourceTaskId: exports_zod.string().optional(),
2411
+ outputSchema: exports_zod.record(exports_zod.string(), exports_zod.unknown()).optional(),
2412
+ inheritParentOutputSchema: exports_zod.boolean().optional(),
2413
+ followUpConfig: FollowUpConfigSchema.optional(),
2414
+ requestedByUserId: exports_zod.string().optional(),
2415
+ contextKey: exports_zod.string().optional(),
2416
+ bypassTrackerContextDedup: exports_zod.boolean().optional(),
2417
+ routingAffinity: RoutingAffinitySchema.optional()
2418
+ });
2364
2419
  TaskAttachmentKindSchema = exports_zod.enum(["agent-fs", "url", "shared-fs", "page"]);
2420
+ attachmentCapabilitiesSchema = exports_zod.record(exports_zod.string(), exports_zod.unknown()).refine((capabilities) => !(SERVER_GENERATED_ATTACHMENT_CAPABILITY in capabilities), {
2421
+ message: `${SERVER_GENERATED_ATTACHMENT_CAPABILITY} is reserved for server-generated attachments`
2422
+ });
2365
2423
  attachmentCommonFields = {
2366
2424
  name: exports_zod.string().min(1).describe("Display name for the attachment."),
2367
2425
  providerId: exports_zod.string().min(1).optional(),
2368
2426
  providerKey: exports_zod.string().min(1).optional(),
2369
- capabilities: exports_zod.record(exports_zod.string(), exports_zod.unknown()).optional(),
2427
+ capabilities: attachmentCapabilitiesSchema.optional(),
2370
2428
  mimeType: exports_zod.string().optional(),
2371
2429
  sizeBytes: exports_zod.number().int().min(0).optional(),
2372
2430
  sha256: exports_zod.string().optional(),
@@ -2437,6 +2495,11 @@ var init_types = __esm(() => {
2437
2495
  createdAt: exports_zod.iso.datetime(),
2438
2496
  lastUpdatedAt: exports_zod.iso.datetime()
2439
2497
  }).openapi("User");
2498
+ UserCommsPrefsSchema = exports_zod.object({
2499
+ tone: exports_zod.string().optional(),
2500
+ language: exports_zod.string().optional(),
2501
+ verbosity: exports_zod.string().optional()
2502
+ }).openapi("UserCommsPrefs");
2440
2503
  IdentityEventTypeSchema = exports_zod.enum([
2441
2504
  "auto_merge",
2442
2505
  "manual_merge",
@@ -2746,6 +2809,8 @@ var init_types = __esm(() => {
2746
2809
  "system.boot",
2747
2810
  "system.migration",
2748
2811
  "system.error",
2812
+ "system.profile_sync_rejected",
2813
+ "system.profile_sync_reconciled",
2749
2814
  "script.global_upsert",
2750
2815
  "schedule.deleted"
2751
2816
  ]);
@@ -2891,9 +2956,22 @@ var init_types = __esm(() => {
2891
2956
  taskDescription: exports_zod.string().nullable(),
2892
2957
  runnerSessionId: exports_zod.string().nullable(),
2893
2958
  providerSessionId: exports_zod.string().nullable(),
2959
+ runtimeInstanceId: exports_zod.string().nullable().optional(),
2894
2960
  startedAt: exports_zod.iso.datetime(),
2895
2961
  lastHeartbeatAt: exports_zod.iso.datetime()
2896
2962
  }).openapi("ActiveSession");
2963
+ RuntimeInstanceStatusSchema = exports_zod.enum(["active", "offline"]);
2964
+ RuntimeInstanceSchema = exports_zod.object({
2965
+ id: exports_zod.string(),
2966
+ agentId: exports_zod.string(),
2967
+ status: RuntimeInstanceStatusSchema,
2968
+ reportedSlots: exports_zod.number().int(),
2969
+ credentialReady: exports_zod.boolean().nullable().optional(),
2970
+ metadata: exports_zod.record(exports_zod.string(), exports_zod.unknown()).nullable(),
2971
+ lastSeenAt: exports_zod.iso.datetime(),
2972
+ createdAt: exports_zod.iso.datetime(),
2973
+ updatedAt: exports_zod.iso.datetime()
2974
+ }).openapi("RuntimeInstance");
2897
2975
  RetryPolicySchema = exports_zod.object({
2898
2976
  maxRetries: exports_zod.number().int().min(0).default(3),
2899
2977
  strategy: exports_zod.enum(["exponential", "static", "linear"]).default("exponential"),
@@ -3201,6 +3279,7 @@ var init_types = __esm(() => {
3201
3279
  triggerData: exports_zod.unknown().optional(),
3202
3280
  context: exports_zod.record(exports_zod.string(), exports_zod.unknown()).optional(),
3203
3281
  error: exports_zod.string().optional(),
3282
+ createdBy: exports_zod.string().optional(),
3204
3283
  startedAt: exports_zod.string(),
3205
3284
  lastUpdatedAt: exports_zod.string(),
3206
3285
  finishedAt: exports_zod.string().optional()
@@ -3564,6 +3643,58 @@ var init_types = __esm(() => {
3564
3643
  }).openapi("KvEntry");
3565
3644
  });
3566
3645
 
3646
+ // src/utils/github-pull-request.ts
3647
+ function parseGitHubPullRequestToken(token) {
3648
+ const candidate = token.replace(TRAILING_PROSE_PUNCTUATION_RE, "");
3649
+ const lowerCandidate = candidate.toLowerCase();
3650
+ if (!lowerCandidate.startsWith("https://github.com/") && !lowerCandidate.startsWith("http://github.com/") && !lowerCandidate.startsWith("github.com/")) {
3651
+ return null;
3652
+ }
3653
+ const withScheme = /^https?:\/\//i.test(candidate) ? candidate : `https://${candidate}`;
3654
+ let parsed;
3655
+ try {
3656
+ parsed = new URL(withScheme);
3657
+ } catch {
3658
+ return null;
3659
+ }
3660
+ if (parsed.host.toLowerCase() !== "github.com" || parsed.username.length > 0 || parsed.password.length > 0) {
3661
+ return null;
3662
+ }
3663
+ const [owner, repo, pull, numberText] = parsed.pathname.split("/").filter(Boolean);
3664
+ if (!owner || !repo || pull?.toLowerCase() !== "pull" || !numberText || !GITHUB_PATH_SEGMENT_RE.test(owner) || !GITHUB_PATH_SEGMENT_RE.test(repo) || !/^\d+$/.test(numberText)) {
3665
+ return null;
3666
+ }
3667
+ return {
3668
+ url: `https://github.com/${owner}/${repo}/pull/${numberText}`,
3669
+ owner,
3670
+ repo,
3671
+ number: Number(numberText)
3672
+ };
3673
+ }
3674
+ function extractGitHubPullRequestUrls(text) {
3675
+ if (!text)
3676
+ return [];
3677
+ const results = [];
3678
+ const seen = new Set;
3679
+ for (const match of text.matchAll(CANDIDATE_TOKEN_RE)) {
3680
+ const pullRequest = parseGitHubPullRequestToken(match[0]);
3681
+ if (!pullRequest)
3682
+ continue;
3683
+ const dedupeKey = pullRequest.url.toLowerCase();
3684
+ if (seen.has(dedupeKey))
3685
+ continue;
3686
+ seen.add(dedupeKey);
3687
+ results.push(pullRequest);
3688
+ }
3689
+ return results;
3690
+ }
3691
+ var CANDIDATE_TOKEN_RE, TRAILING_PROSE_PUNCTUATION_RE, GITHUB_PATH_SEGMENT_RE;
3692
+ var init_github_pull_request = __esm(() => {
3693
+ CANDIDATE_TOKEN_RE = /[^\s()[\]{}<>"'`]+/g;
3694
+ TRAILING_PROSE_PUNCTUATION_RE = /[)\]},.;:!]+$/;
3695
+ GITHUB_PATH_SEGMENT_RE = /^[\w.-]+$/;
3696
+ });
3697
+
3567
3698
  // src/utils/request-auth-context.ts
3568
3699
  import { AsyncLocalStorage } from "node:async_hooks";
3569
3700
  function setRequestAuth(req, auth) {
@@ -4302,136 +4433,6 @@ var init_oauth_encryption_backfill = __esm(() => {
4302
4433
  init_crypto();
4303
4434
  });
4304
4435
 
4305
- // src/commands/templates.ts
4306
- var init_templates = __esm(() => {
4307
- init_registry();
4308
- registerTemplate({
4309
- eventType: "task.trigger.assigned",
4310
- header: "",
4311
- defaultBody: `{{work_on_task_cmd}} {{task_id}}{{task_desc_section}}{{attachments_section}}{{output_instructions}}`,
4312
- variables: [
4313
- { name: "work_on_task_cmd", description: "Formatted /work-on-task command" },
4314
- { name: "task_id", description: "Task ID" },
4315
- { name: "task_desc_section", description: "Task description section or empty string" },
4316
- {
4317
- name: "attachments_section",
4318
- description: "Ready-to-run fetch recipe per task attachment (or empty string if none) — lets the agent download an attachment in one call instead of discovering the path/provider itself"
4319
- },
4320
- {
4321
- name: "output_instructions",
4322
- description: "Output format instructions (with outputSchema if present, or generic store-progress)"
4323
- }
4324
- ],
4325
- category: "task_lifecycle"
4326
- });
4327
- registerTemplate({
4328
- eventType: "task.trigger.offered",
4329
- header: "",
4330
- defaultBody: `{{review_offered_task_cmd}} {{task_id}}{{task_desc_section}}
4331
-
4332
- Accept if you have capacity and skills. Reject with a reason if you cannot handle it.`,
4333
- variables: [
4334
- { name: "review_offered_task_cmd", description: "Formatted /review-offered-task command" },
4335
- { name: "task_id", description: "Task ID" },
4336
- { name: "task_desc_section", description: "Task description section or empty string" }
4337
- ],
4338
- category: "task_lifecycle"
4339
- });
4340
- registerTemplate({
4341
- eventType: "task.trigger.unread_mentions",
4342
- header: "",
4343
- defaultBody: `You have {{mention_count}} mention(s) in chat channels.
4344
-
4345
- 1. Use \`read-messages\` with unreadOnly: true to see them
4346
- 2. Respond to questions or requests directed at you
4347
- 3. If a message requires work, create a task using \`send-task\``,
4348
- variables: [{ name: "mention_count", description: "Number of unread mentions or 'unread'" }],
4349
- category: "task_lifecycle"
4350
- });
4351
- registerTemplate({
4352
- eventType: "task.trigger.pool_available",
4353
- header: "",
4354
- defaultBody: `{{task_count}} task(s) available in the pool.
4355
-
4356
- 1. Run \`get-tasks\` with unassigned: true to browse
4357
- 2. Pick one matching your skills
4358
- 3. Run \`task-action\` with action: "claim" and taskId: "<id>"
4359
-
4360
- Note: Claims are first-come-first-serve. If claim fails, pick another.`,
4361
- variables: [{ name: "task_count", description: "Number of available pool tasks" }],
4362
- category: "task_lifecycle"
4363
- });
4364
- registerTemplate({
4365
- eventType: "task.trigger.channel_activity",
4366
- header: "",
4367
- defaultBody: `## Slack Channel Activity
4368
-
4369
- {{message_count}} new message(s) in monitored Slack channels:
4370
-
4371
- {{messages_detail}}
4372
- ## Your Task
4373
-
4374
- Review these messages and decide if any require action:
4375
- 1. If a message is a question or request, respond using \`slack-reply\` or create a task with \`send-task\`
4376
- 2. If a message is informational, no action needed
4377
- 3. Use \`slack-read\` with the channelId to get more context if needed`,
4378
- variables: [
4379
- { name: "message_count", description: "Number of new messages" },
4380
- {
4381
- name: "messages_detail",
4382
- description: "Formatted list of messages with channel and user info"
4383
- }
4384
- ],
4385
- category: "task_lifecycle"
4386
- });
4387
- registerTemplate({
4388
- eventType: "task.resumption.with_progress",
4389
- header: "",
4390
- defaultBody: `{{work_on_task_cmd}} {{task_id}}
4391
-
4392
- **RESUMED TASK** - This task was interrupted during a deployment and is being resumed.
4393
-
4394
- Task: "{{task_description}}"
4395
-
4396
- Previous Progress:
4397
- {{progress}}
4398
-
4399
- Continue from where you left off. Review the progress above and complete the remaining work.{{completion_instructions}}`,
4400
- variables: [
4401
- { name: "work_on_task_cmd", description: "Formatted /work-on-task command" },
4402
- { name: "task_id", description: "Task ID" },
4403
- { name: "task_description", description: "Original task description" },
4404
- { name: "progress", description: "Previous progress text" },
4405
- {
4406
- name: "completion_instructions",
4407
- description: "Completion instructions (empty for providers without MCP)"
4408
- }
4409
- ],
4410
- category: "task_lifecycle"
4411
- });
4412
- registerTemplate({
4413
- eventType: "task.resumption.no_progress",
4414
- header: "",
4415
- defaultBody: `{{work_on_task_cmd}} {{task_id}}
4416
-
4417
- **RESUMED TASK** - This task was interrupted during a deployment and is being resumed.
4418
-
4419
- Task: "{{task_description}}"
4420
-
4421
- No progress was saved before the interruption. Start the task fresh but be aware files may have been partially modified.{{completion_instructions}}`,
4422
- variables: [
4423
- { name: "work_on_task_cmd", description: "Formatted /work-on-task command" },
4424
- { name: "task_id", description: "Task ID" },
4425
- { name: "task_description", description: "Original task description" },
4426
- {
4427
- name: "completion_instructions",
4428
- description: "Completion instructions (empty for providers without MCP)"
4429
- }
4430
- ],
4431
- category: "task_lifecycle"
4432
- });
4433
- });
4434
-
4435
4436
  // src/tools/templates.ts
4436
4437
  var init_templates2 = __esm(() => {
4437
4438
  init_registry();
@@ -4712,7 +4713,7 @@ function promoteSteeringToTask(task, message) {
4712
4713
  source: message.source === "script" ? "api" : message.source,
4713
4714
  taskType: "follow-up",
4714
4715
  parentTaskId: task.id,
4715
- requestedByUserId: message.createdByUserId ?? task.requestedByUserId,
4716
+ requestedByUserId: message.createdByUserId,
4716
4717
  bypassTrackerContextDedup: true
4717
4718
  });
4718
4719
  }
@@ -4915,7 +4916,15 @@ var init_swarm_config_guard = __esm(() => {
4915
4916
  return null;
4916
4917
  return "Invalid BEDROCK_AUTH_MODE value (must be one of: sdk, bearer)";
4917
4918
  },
4919
+ AGENT_MAX_TASKS: (value) => {
4920
+ const str = String(value).trim();
4921
+ if (!/^\d+$/.test(str) || Number(str) < 1 || Number(str) > 100) {
4922
+ return "Invalid AGENT_MAX_TASKS (must be an integer between 1 and 100)";
4923
+ }
4924
+ return null;
4925
+ },
4918
4926
  ...booleanValidators([
4927
+ "MULTI_RUNTIME_ENABLED",
4919
4928
  "STEERING_ENABLED",
4920
4929
  "MEMORY_HYBRID_SEARCH",
4921
4930
  "MEMORY_GRAPH_EXPANSION",
@@ -4938,7 +4947,8 @@ var init_swarm_config_guard = __esm(() => {
4938
4947
  "MCP_OAUTH_ALLOW_PRIVATE_HOSTS",
4939
4948
  "OTEL_TRACE_POLL",
4940
4949
  "ANONYMIZED_TELEMETRY",
4941
- "SWARM_HIDE_CLOUD_PROMO"
4950
+ "SWARM_HIDE_CLOUD_PROMO",
4951
+ "DB_QUERY_BOUNDED_ENABLED"
4942
4952
  ]),
4943
4953
  ...enumValidator("SLACK_THREAD_STEERING", ["lead", "all"]),
4944
4954
  ...enumValidator("SLACK_THREAD_STEERING_MODE", ["steer", "queue"]),
@@ -4953,8 +4963,13 @@ var init_swarm_config_guard = __esm(() => {
4953
4963
  "WORKFLOW_MAX_ITERATIONS",
4954
4964
  "WORKFLOW_MAX_STEPS_PER_RUN",
4955
4965
  "SCHEDULER_INTERVAL_MS",
4966
+ "RUNTIME_STALE_THRESHOLD_MIN",
4956
4967
  "SCRIPT_RUN_CONCURRENCY_CAP",
4957
- "WORKER_API_READY_TIMEOUT_SECONDS"
4968
+ "WORKER_API_READY_TIMEOUT_SECONDS",
4969
+ "DB_QUERY_HTTP_BUDGET_MS",
4970
+ "DB_QUERY_HTTP_MAX_ROWS",
4971
+ "DB_QUERY_MCP_BUDGET_MS",
4972
+ "DB_QUERY_MCP_MAX_ROWS"
4958
4973
  ], 1),
4959
4974
  ...integerValidators(["HEARTBEAT_MAX_AUTO_ASSIGN"], 0),
4960
4975
  MEMORY_MIN_SIMILARITY: (value) => validateFloatRange("MEMORY_MIN_SIMILARITY", value, 0, 1, "between 0 and 1 inclusive"),
@@ -5246,6 +5261,7 @@ __export(exports_db, {
5246
5261
  updateAgentName: () => updateAgentName,
5247
5262
  updateAgentMaxTasks: () => updateAgentMaxTasks,
5248
5263
  updateAgentCredentialState: () => updateAgentCredentialState,
5264
+ updateAgentCredentialMissing: () => updateAgentCredentialMissing,
5249
5265
  updateAgentCredStatus: () => updateAgentCredStatus,
5250
5266
  updateAgentActivity: () => updateAgentActivity,
5251
5267
  updateActiveSessionProviderSessionId: () => updateActiveSessionProviderSessionId,
@@ -5268,6 +5284,7 @@ __export(exports_db, {
5268
5284
  searchSkills: () => searchSkills,
5269
5285
  resumeTask: () => resumeTask,
5270
5286
  resolveWaitState: () => resolveWaitState,
5287
+ resolveSqliteVecExtensionPath: () => resolveSqliteVecExtensionPath,
5271
5288
  resolvePromptTemplate: () => resolvePromptTemplate,
5272
5289
  resolveApprovalRequest: () => resolveApprovalRequest,
5273
5290
  resetTasksNotified: () => resetTasksNotified,
@@ -5282,6 +5299,7 @@ __export(exports_db, {
5282
5299
  releaseStaleMentionProcessing: () => releaseStaleMentionProcessing,
5283
5300
  releaseMentionProcessing: () => releaseMentionProcessing,
5284
5301
  rejectTask: () => rejectTask,
5302
+ recordTaskPullRequestAttachments: () => recordTaskPullRequestAttachments,
5285
5303
  recordSlackMessage: () => recordSlackMessage,
5286
5304
  recordKeyUsage: () => recordKeyUsage,
5287
5305
  recordKeyRateLimitWindows: () => recordKeyRateLimitWindows,
@@ -5507,6 +5525,7 @@ __export(exports_db, {
5507
5525
  getBudgetRefusalNotification: () => getBudgetRefusalNotification,
5508
5526
  getBudget: () => getBudget,
5509
5527
  getAvailableKeyIndices: () => getAvailableKeyIndices,
5528
+ getAttributionByPerson: () => getAttributionByPerson,
5510
5529
  getAssetKeyMappingByProvider: () => getAssetKeyMappingByProvider,
5511
5530
  getAssetKeyMapping: () => getAssetKeyMapping,
5512
5531
  getApprovalRequestByStepId: () => getApprovalRequestByStepId,
@@ -5640,6 +5659,7 @@ __export(exports_db, {
5640
5659
  assignUnassignedTaskPending: () => assignUnassignedTaskPending,
5641
5660
  agentQueries: () => agentQueries,
5642
5661
  acceptTask: () => acceptTask,
5662
+ __resetSqliteVecExtensionPathCacheForTests: () => __resetSqliteVecExtensionPathCacheForTests,
5643
5663
  UNATTRIBUTED_USER_ID: () => UNATTRIBUTED_USER_ID,
5644
5664
  SKILL_FILE_LIMITS: () => SKILL_FILE_LIMITS,
5645
5665
  MAX_EMPTY_POLLS: () => MAX_EMPTY_POLLS,
@@ -5672,6 +5692,24 @@ function taskContextForTelemetry(task) {
5672
5692
  function isSqliteVecAvailable() {
5673
5693
  return sqliteVecAvailable;
5674
5694
  }
5695
+ function resolveSqliteVecExtensionPath() {
5696
+ if (cachedSqliteVecExtensionPath !== null)
5697
+ return cachedSqliteVecExtensionPath;
5698
+ const extensionPath = process.env.SQLITE_VEC_EXTENSION_PATH;
5699
+ if (extensionPath) {
5700
+ cachedSqliteVecExtensionPath = extensionPath;
5701
+ return cachedSqliteVecExtensionPath;
5702
+ }
5703
+ try {
5704
+ cachedSqliteVecExtensionPath = require_sqlite_vec().getLoadablePath();
5705
+ } catch {
5706
+ cachedSqliteVecExtensionPath = undefined;
5707
+ }
5708
+ return cachedSqliteVecExtensionPath;
5709
+ }
5710
+ function __resetSqliteVecExtensionPathCacheForTests() {
5711
+ cachedSqliteVecExtensionPath = null;
5712
+ }
5675
5713
  function loadSqliteVec(database) {
5676
5714
  sqliteVecAvailable = false;
5677
5715
  try {
@@ -5933,6 +5971,10 @@ function updateAgentCredentialState(agentId, ready, missing) {
5933
5971
  resetEmptyPollCount(agentId);
5934
5972
  return row ? rowToAgent(row) : null;
5935
5973
  }
5974
+ function updateAgentCredentialMissing(agentId, missing) {
5975
+ const json = missing && missing.length > 0 ? JSON.stringify(missing) : null;
5976
+ getDb().prepare("UPDATE agents SET credentialMissing = ?, lastUpdatedAt = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?").run(json, agentId);
5977
+ }
5936
5978
  function createAgent(agent) {
5937
5979
  const id = agent.id ?? crypto.randomUUID();
5938
5980
  const maxTasks = agent.maxTasks ?? 1;
@@ -6040,7 +6082,9 @@ function deleteAgent(id) {
6040
6082
  return result.changes > 0;
6041
6083
  }
6042
6084
  function getActiveTaskCount(agentId) {
6043
- const result = getDb().prepare("SELECT COUNT(*) as count FROM agent_tasks WHERE agentId = ? AND status = 'in_progress'").get(agentId);
6085
+ const result = getDb().prepare(`SELECT COUNT(*) as count FROM agent_tasks
6086
+ WHERE (agentId = ? AND status = 'in_progress')
6087
+ OR (offeredTo = ? AND status = 'reviewing')`).get(agentId, agentId);
6044
6088
  return result?.count ?? 0;
6045
6089
  }
6046
6090
  function hasCapacity(agentId) {
@@ -6583,9 +6627,18 @@ function updateTaskTitle(taskId, title) {
6583
6627
  return row ? rowToAgentTask(row) : null;
6584
6628
  }
6585
6629
  function updateTaskVcs(taskId, vcs) {
6586
- const row = getDb().prepare(`UPDATE agent_tasks
6587
- SET vcsProvider = ?, vcsRepo = ?, vcsNumber = ?, vcsUrl = ?, lastUpdatedAt = ?
6588
- WHERE id = ? RETURNING *`).get(vcs.vcsProvider, vcs.vcsRepo, vcs.vcsNumber, vcs.vcsUrl, new Date().toISOString(), taskId);
6630
+ const row = getDb().transaction(() => {
6631
+ const updated = getDb().prepare(`UPDATE agent_tasks
6632
+ SET vcsProvider = ?, vcsRepo = ?, vcsNumber = ?, vcsUrl = ?, lastUpdatedAt = ?
6633
+ WHERE id = ? RETURNING *`).get(vcs.vcsProvider, vcs.vcsRepo, vcs.vcsNumber, vcs.vcsUrl, new Date().toISOString(), taskId);
6634
+ if (updated) {
6635
+ reconcileTaskPullRequestAttachments(taskId, updated.agentId, [
6636
+ updated.output,
6637
+ vcs.vcsProvider === "github" ? vcs.vcsUrl : null
6638
+ ]);
6639
+ }
6640
+ return updated;
6641
+ })();
6589
6642
  return row ? rowToAgentTask(row) : null;
6590
6643
  }
6591
6644
  function getTasksByAgentId(agentId) {
@@ -7020,13 +7073,24 @@ function completeTask(id, output) {
7020
7073
  if (isTerminalTaskStatus(oldTask.status)) {
7021
7074
  return null;
7022
7075
  }
7023
- const finishedAt = new Date().toISOString();
7024
- let row = taskQueries.updateStatus().get("completed", finishedAt, id);
7076
+ const row = getDb().transaction(() => {
7077
+ const finishedAt = new Date().toISOString();
7078
+ let completed = taskQueries.updateStatus().get("completed", finishedAt, id);
7079
+ if (!completed)
7080
+ return null;
7081
+ if (output) {
7082
+ completed = taskQueries.setOutput().get(scrubSecrets(output), id);
7083
+ }
7084
+ if (completed) {
7085
+ reconcileTaskPullRequestAttachments(id, completed.agentId, [
7086
+ completed.output,
7087
+ completed.vcsProvider === "github" ? completed.vcsUrl : null
7088
+ ]);
7089
+ }
7090
+ return completed;
7091
+ })();
7025
7092
  if (!row)
7026
7093
  return null;
7027
- if (output) {
7028
- row = taskQueries.setOutput().get(scrubSecrets(output), id);
7029
- }
7030
7094
  if (row && oldTask) {
7031
7095
  emitTaskLifecycleTelemetryAfterCommit("completed", {
7032
7096
  taskId: id,
@@ -7044,17 +7108,15 @@ function completeTask(id, output) {
7044
7108
  newValue: "completed"
7045
7109
  });
7046
7110
  } catch {}
7047
- try {
7048
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7049
- workflowEventBus.emit("task.completed", {
7050
- taskId: id,
7051
- output,
7052
- agentId: row.agentId,
7053
- workflowRunId: row.workflowRunId,
7054
- workflowRunStepId: row.workflowRunStepId
7055
- });
7111
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7112
+ workflowEventBus.emit("task.completed", {
7113
+ taskId: id,
7114
+ output,
7115
+ agentId: row.agentId,
7116
+ workflowRunId: row.workflowRunId,
7117
+ workflowRunStepId: row.workflowRunStepId
7056
7118
  });
7057
- } catch {}
7119
+ }).catch((err) => console.error("[db] task.completed event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
7058
7120
  try {
7059
7121
  promotePendingSteeringForTask(id, "Task completed before steering was delivered");
7060
7122
  } catch (error) {
@@ -7091,17 +7153,15 @@ function failTask(id, reason) {
7091
7153
  metadata: { reason: scrubbedReason }
7092
7154
  });
7093
7155
  } catch {}
7094
- try {
7095
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7096
- workflowEventBus.emit("task.failed", {
7097
- taskId: id,
7098
- failureReason: reason,
7099
- agentId: row.agentId,
7100
- workflowRunId: row.workflowRunId,
7101
- workflowRunStepId: row.workflowRunStepId
7102
- });
7156
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7157
+ workflowEventBus.emit("task.failed", {
7158
+ taskId: id,
7159
+ failureReason: reason,
7160
+ agentId: row.agentId,
7161
+ workflowRunId: row.workflowRunId,
7162
+ workflowRunStepId: row.workflowRunStepId
7103
7163
  });
7104
- } catch {}
7164
+ }).catch((err) => console.error("[db] task.failed event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
7105
7165
  try {
7106
7166
  promotePendingSteeringForTask(id, "Task failed before steering was delivered");
7107
7167
  } catch (error) {
@@ -7121,7 +7181,16 @@ function overwriteTerminalTaskResultText(id, patch) {
7121
7181
  return null;
7122
7182
  const output = patch.output !== undefined ? scrubSecrets(patch.output) : task.output ?? null;
7123
7183
  const failureReason = patch.failureReason !== undefined ? scrubSecrets(patch.failureReason) : task.failureReason ?? null;
7124
- const row = taskQueries.setTerminalResultText().get(output, failureReason, id) ?? null;
7184
+ const row = getDb().transaction(() => {
7185
+ const updated = taskQueries.setTerminalResultText().get(output, failureReason, id) ?? null;
7186
+ if (updated && patch.output !== undefined) {
7187
+ reconcileTaskPullRequestAttachments(id, updated.agentId, [
7188
+ updated.output,
7189
+ updated.vcsProvider === "github" ? updated.vcsUrl : null
7190
+ ]);
7191
+ }
7192
+ return updated;
7193
+ })();
7125
7194
  return row ? rowToAgentTask(row) : task;
7126
7195
  }
7127
7196
  function cancelTask(id, reason) {
@@ -7152,16 +7221,14 @@ function cancelTask(id, reason) {
7152
7221
  metadata: reason ? { reason } : undefined
7153
7222
  });
7154
7223
  } catch {}
7155
- try {
7156
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7157
- workflowEventBus.emit("task.cancelled", {
7158
- taskId: id,
7159
- agentId: row.agentId,
7160
- workflowRunId: row.workflowRunId,
7161
- workflowRunStepId: row.workflowRunStepId
7162
- });
7224
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7225
+ workflowEventBus.emit("task.cancelled", {
7226
+ taskId: id,
7227
+ agentId: row.agentId,
7228
+ workflowRunId: row.workflowRunId,
7229
+ workflowRunStepId: row.workflowRunStepId
7163
7230
  });
7164
- } catch {}
7231
+ }).catch((err) => console.error("[db] task.cancelled event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
7165
7232
  try {
7166
7233
  promotePendingSteeringForTask(id, "Task was cancelled before steering was delivered");
7167
7234
  } catch (error) {
@@ -7208,18 +7275,16 @@ function supersedeTask(id, args) {
7208
7275
  metadata: { reason: args.reason, resumeTaskId: args.resumeTaskId }
7209
7276
  });
7210
7277
  } catch {}
7211
- try {
7212
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7213
- workflowEventBus.emit("task.superseded", {
7214
- taskId: id,
7215
- reason: args.reason,
7216
- resumeTaskId: args.resumeTaskId,
7217
- agentId: row.agentId,
7218
- workflowRunId: row.workflowRunId,
7219
- workflowRunStepId: row.workflowRunStepId
7220
- });
7278
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7279
+ workflowEventBus.emit("task.superseded", {
7280
+ taskId: id,
7281
+ reason: args.reason,
7282
+ resumeTaskId: args.resumeTaskId,
7283
+ agentId: row.agentId,
7284
+ workflowRunId: row.workflowRunId,
7285
+ workflowRunStepId: row.workflowRunStepId
7221
7286
  });
7222
- } catch {}
7287
+ }).catch((err) => console.error("[db] task.superseded event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
7223
7288
  try {
7224
7289
  cascadeFailDependents(id, "superseded");
7225
7290
  } catch (err) {
@@ -7373,15 +7438,13 @@ function updateTaskProgress(id, progress) {
7373
7438
  newValue: scrubbedProgress
7374
7439
  });
7375
7440
  } catch {}
7376
- try {
7377
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7378
- workflowEventBus.emit("task.progress", {
7379
- taskId: id,
7380
- progress: scrubbedProgress,
7381
- agentId: row.agentId
7382
- });
7441
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
7442
+ workflowEventBus.emit("task.progress", {
7443
+ taskId: id,
7444
+ progress: scrubbedProgress,
7445
+ agentId: row.agentId
7383
7446
  });
7384
- } catch {}
7447
+ }).catch((err) => console.error("[db] task.progress event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
7385
7448
  }
7386
7449
  return row ? rowToAgentTask(row) : null;
7387
7450
  }
@@ -7446,6 +7509,55 @@ function insertTaskAttachment(input) {
7446
7509
  return attachment;
7447
7510
  })();
7448
7511
  }
7512
+ function pullRequestKey(pullRequest) {
7513
+ return `${pullRequest.owner.toLowerCase()}/${pullRequest.repo.toLowerCase()}#${pullRequest.number}`;
7514
+ }
7515
+ function recordTaskPullRequestAttachments(taskId, agentId, text) {
7516
+ const pullRequests = extractGitHubPullRequestUrls(text);
7517
+ if (pullRequests.length === 0)
7518
+ return [];
7519
+ const existingPullRequests = new Set(getDb().prepare("SELECT url FROM task_attachments WHERE task_id = ? AND kind = 'url' AND url IS NOT NULL").all(taskId).flatMap((row) => extractGitHubPullRequestUrls(row.url)).map(pullRequestKey));
7520
+ const stored = [];
7521
+ for (const pullRequest of pullRequests) {
7522
+ const dedupeKey = pullRequestKey(pullRequest);
7523
+ if (existingPullRequests.has(dedupeKey))
7524
+ continue;
7525
+ stored.push(insertTaskAttachment({
7526
+ taskId,
7527
+ agentId,
7528
+ name: `GitHub pull request #${pullRequest.number}`,
7529
+ kind: "url",
7530
+ url: pullRequest.url,
7531
+ providerId: GENERATED_PULL_REQUEST_PROVIDER_ID,
7532
+ capabilities: {
7533
+ [SERVER_GENERATED_ATTACHMENT_CAPABILITY]: GENERATED_PULL_REQUEST_SOURCE
7534
+ },
7535
+ intent: GENERATED_PULL_REQUEST_INTENT,
7536
+ description: GENERATED_PULL_REQUEST_DESCRIPTION
7537
+ }));
7538
+ existingPullRequests.add(dedupeKey);
7539
+ }
7540
+ return stored;
7541
+ }
7542
+ function reconcileTaskPullRequestAttachments(taskId, agentId, sourceTexts) {
7543
+ const desiredPullRequests = sourceTexts.flatMap(extractGitHubPullRequestUrls);
7544
+ const desiredKeys = new Set(desiredPullRequests.map(pullRequestKey));
7545
+ const generatedRows = getDb().prepare(`SELECT id, name, url
7546
+ FROM task_attachments
7547
+ WHERE task_id = ?
7548
+ AND kind = 'url'
7549
+ AND url IS NOT NULL
7550
+ AND json_extract(capabilities, '$.${SERVER_GENERATED_ATTACHMENT_CAPABILITY}') = ?`).all(taskId, GENERATED_PULL_REQUEST_SOURCE);
7551
+ for (const row of generatedRows) {
7552
+ const pullRequest = extractGitHubPullRequestUrls(row.url)[0];
7553
+ const expectedName = pullRequest ? `GitHub pull request #${pullRequest.number}` : null;
7554
+ if (!pullRequest || row.name !== expectedName || !desiredKeys.has(pullRequestKey(pullRequest))) {
7555
+ getDb().run("DELETE FROM task_attachments WHERE id = ?", [row.id]);
7556
+ }
7557
+ }
7558
+ return recordTaskPullRequestAttachments(taskId, agentId, desiredPullRequests.map((pullRequest) => pullRequest.url).join(`
7559
+ `));
7560
+ }
7449
7561
  function insertTaskAttachmentRow(input) {
7450
7562
  const db2 = getDb();
7451
7563
  if (input.sha256) {
@@ -7986,6 +8098,11 @@ function findRecentSimilarTasks(opts) {
7986
8098
  return getDb().prepare(query).all(...params).map(rowToAgentTask);
7987
8099
  }
7988
8100
  function createTaskExtended(task, options) {
8101
+ if (typeof task !== "string" || task.trim().length === 0) {
8102
+ throw new Error("createTaskExtended: 'task' must be a non-empty string");
8103
+ }
8104
+ options = CreateTaskOptionsSchema.parse(options ?? {});
8105
+ let requestedByUserIdInherited = false;
7989
8106
  const id = crypto.randomUUID();
7990
8107
  const now = new Date().toISOString();
7991
8108
  const status = options?.offeredTo ? "offered" : options?.agentId ? "pending" : options?.status === "backlog" ? "backlog" : "unassigned";
@@ -8052,6 +8169,7 @@ function createTaskExtended(task, options) {
8052
8169
  }
8053
8170
  if (parent.requestedByUserId && !options.requestedByUserId) {
8054
8171
  options.requestedByUserId = parent.requestedByUserId;
8172
+ requestedByUserIdInherited = true;
8055
8173
  }
8056
8174
  if (parent.key && !options.key) {
8057
8175
  options.key = parent.key;
@@ -8121,8 +8239,8 @@ function createTaskExtended(task, options) {
8121
8239
  vcsInstallationId, vcsNodeId,
8122
8240
  agentmailInboxId, agentmailMessageId, agentmailThreadId,
8123
8241
  mentionMessageId, mentionChannelId, dir, parentTaskId, model, modelTier, effort, scheduleId,
8124
- workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, contextKey, routingAffinity, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by
8125
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(id, assetKey, options?.agentId ?? null, options?.creatorAgentId ?? null, task, status, options?.source ?? "mcp", options?.taskType ?? null, JSON.stringify(options?.tags ?? []), options?.priority ?? 50, JSON.stringify(options?.dependsOn ?? []), options?.offeredTo ?? null, options?.offeredTo ? now : null, options?.slackChannelId ?? null, options?.slackThreadTs ?? null, options?.slackTriggerMessageTs ?? null, options?.slackUserId ?? null, options?.vcsProvider ?? null, options?.vcsRepo ?? null, options?.vcsEventType ?? null, options?.vcsNumber ?? null, options?.vcsCommentId ?? null, options?.vcsAuthor ?? null, options?.vcsUrl ?? null, options?.vcsInstallationId ?? null, options?.vcsNodeId ?? null, options?.agentmailInboxId ?? null, options?.agentmailMessageId ?? null, options?.agentmailThreadId ?? null, options?.mentionMessageId ?? null, options?.mentionChannelId ?? null, options?.dir ?? null, options?.parentTaskId ?? null, options?.model ?? null, options?.modelTier ?? null, options?.effort ?? null, options?.scheduleId ?? null, options?.workflowRunId ?? null, options?.workflowRunStepId ?? null, options?.outputSchema ? JSON.stringify(options.outputSchema) : null, options?.followUpConfig ? JSON.stringify(options.followUpConfig) : null, options?.requestedByUserId ?? null, options?.contextKey ?? null, options?.routingAffinity ? JSON.stringify(options.routingAffinity) : null, package_default.version, now, now, auditUserId, auditUserId);
8242
+ workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, requestedByUserIdInherited, contextKey, routingAffinity, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by
8243
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(id, assetKey, options?.agentId ?? null, options?.creatorAgentId ?? null, task, status, options?.source ?? "mcp", options?.taskType ?? null, JSON.stringify(options?.tags ?? []), options?.priority ?? 50, JSON.stringify(options?.dependsOn ?? []), options?.offeredTo ?? null, options?.offeredTo ? now : null, options?.slackChannelId ?? null, options?.slackThreadTs ?? null, options?.slackTriggerMessageTs ?? null, options?.slackUserId ?? null, options?.vcsProvider ?? null, options?.vcsRepo ?? null, options?.vcsEventType ?? null, options?.vcsNumber ?? null, options?.vcsCommentId ?? null, options?.vcsAuthor ?? null, options?.vcsUrl ?? null, options?.vcsInstallationId ?? null, options?.vcsNodeId ?? null, options?.agentmailInboxId ?? null, options?.agentmailMessageId ?? null, options?.agentmailThreadId ?? null, options?.mentionMessageId ?? null, options?.mentionChannelId ?? null, options?.dir ?? null, options?.parentTaskId ?? null, options?.model ?? null, options?.modelTier ?? null, options?.effort ?? null, options?.scheduleId ?? null, options?.workflowRunId ?? null, options?.workflowRunStepId ?? null, options?.outputSchema ? JSON.stringify(options.outputSchema) : null, options?.followUpConfig ? JSON.stringify(options.followUpConfig) : null, options?.requestedByUserId ?? null, requestedByUserIdInherited ? 1 : 0, options?.contextKey ?? null, options?.routingAffinity ? JSON.stringify(options.routingAffinity) : null, package_default.version, now, now, auditUserId, auditUserId);
8126
8244
  if (!row)
8127
8245
  throw new Error("Failed to create task");
8128
8246
  try {
@@ -8141,19 +8259,17 @@ function createTaskExtended(task, options) {
8141
8259
  hasParent: !!row.parentTaskId,
8142
8260
  priority: row.priority
8143
8261
  }, (task2) => task2 !== null);
8144
- try {
8145
- import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
8146
- workflowEventBus.emit("task.created", {
8147
- taskId: row.id,
8148
- task: row.task,
8149
- source: row.source,
8150
- tags: options?.tags ?? [],
8151
- agentId: row.agentId,
8152
- workflowRunId: row.workflowRunId,
8153
- workflowRunStepId: row.workflowRunStepId
8154
- });
8262
+ import("./event-bus-axn823e9.js").then(({ workflowEventBus }) => {
8263
+ workflowEventBus.emit("task.created", {
8264
+ taskId: row.id,
8265
+ task: row.task,
8266
+ source: row.source,
8267
+ tags: options?.tags ?? [],
8268
+ agentId: row.agentId,
8269
+ workflowRunId: row.workflowRunId,
8270
+ workflowRunStepId: row.workflowRunStepId
8155
8271
  });
8156
- } catch {}
8272
+ }).catch((err) => console.error("[db] task.created event not emitted:", scrubSecrets(err instanceof Error ? err.message : String(err))));
8157
8273
  return rowToAgentTask(row);
8158
8274
  }
8159
8275
  function claimTask(taskId, agentId) {
@@ -8424,6 +8540,24 @@ function updateAgentProfile(id, updates, meta) {
8424
8540
  const current = database.prepare("SELECT * FROM agents WHERE id = ?").get(id);
8425
8541
  if (!current)
8426
8542
  return null;
8543
+ for (const field of BUDGETED_IDENTITY_FIELDS) {
8544
+ const nextValue = updates[field];
8545
+ if (nextValue === undefined)
8546
+ continue;
8547
+ const result = checkIdentityFieldBudget({
8548
+ field,
8549
+ currentValue: current[field] ?? "",
8550
+ nextValue
8551
+ });
8552
+ if (!result.ok) {
8553
+ throw new IdentityFieldBudgetError(result, computeContentHash(current[field] ?? ""), computeContentHash(nextValue));
8554
+ }
8555
+ }
8556
+ if (updates.name !== undefined) {
8557
+ const existingAgent = database.prepare("SELECT * FROM agents WHERE name = ? AND id != ?").get(updates.name, id);
8558
+ if (existingAgent)
8559
+ throw new Error("Agent name already exists");
8560
+ }
8427
8561
  for (const field of VERSIONABLE_FIELDS) {
8428
8562
  const newValue = updates[field];
8429
8563
  if (newValue === undefined || newValue === null)
@@ -8451,6 +8585,7 @@ function updateAgentProfile(id, updates, meta) {
8451
8585
  const avatarJson = updates.avatar ? JSON.stringify(updates.avatar) : null;
8452
8586
  const now = new Date().toISOString();
8453
8587
  const row = database.prepare(`UPDATE agents SET
8588
+ name = COALESCE(?, name),
8454
8589
  description = COALESCE(?, description),
8455
8590
  role = COALESCE(?, role),
8456
8591
  capabilities = COALESCE(?, capabilities),
@@ -8462,18 +8597,12 @@ function updateAgentProfile(id, updates, meta) {
8462
8597
  heartbeatMd = COALESCE(?, heartbeatMd),
8463
8598
  avatar = CASE WHEN ? = 1 THEN ? ELSE avatar END,
8464
8599
  lastUpdatedAt = ?
8465
- WHERE id = ? RETURNING *`).get(updates.description ?? null, updates.role ?? null, updates.capabilities ? JSON.stringify(updates.capabilities) : null, updates.claudeMd ?? null, updates.soulMd ?? null, updates.identityMd ?? null, updates.setupScript ?? null, updates.toolsMd ?? null, updates.heartbeatMd ?? null, avatarProvided ? 1 : 0, avatarJson, now, id);
8600
+ WHERE id = ? RETURNING *`).get(updates.name ?? null, updates.description ?? null, updates.role ?? null, updates.capabilities ? JSON.stringify(updates.capabilities) : null, updates.claudeMd ?? null, updates.soulMd ?? null, updates.identityMd ?? null, updates.setupScript ?? null, updates.toolsMd ?? null, updates.heartbeatMd ?? null, avatarProvided ? 1 : 0, avatarJson, now, id);
8466
8601
  return row ? rowToAgent(row) : null;
8467
8602
  })();
8468
8603
  }
8469
8604
  function updateAgentName(id, newName) {
8470
- const existingAgent = getDb().prepare("SELECT * FROM agents WHERE name = ? AND id != ?").get(newName, id);
8471
- if (existingAgent) {
8472
- throw new Error("Agent name already exists");
8473
- }
8474
- const now = new Date().toISOString();
8475
- const row = getDb().prepare("UPDATE agents SET name = ?, lastUpdatedAt = ? WHERE id = ? RETURNING *").get(newName, now, id);
8476
- return row ? rowToAgent(row) : null;
8605
+ return updateAgentProfile(id, { name: newName });
8477
8606
  }
8478
8607
  function rowToChannel(row) {
8479
8608
  return {
@@ -9017,13 +9146,14 @@ function getSessionCostSummary(opts) {
9017
9146
  params.push(opts.agentId);
9018
9147
  }
9019
9148
  if (opts.userId === UNATTRIBUTED_USER_ID) {
9020
- conditions.push("t.requestedByUserId IS NULL");
9149
+ conditions.push(`(t.requestedByUserId IS NULL OR ${HUMAN_FREE_SQL})`);
9021
9150
  } else if (opts.userId) {
9022
- conditions.push("t.requestedByUserId = ?");
9151
+ conditions.push(`(t.requestedByUserId = ? AND NOT ${HUMAN_FREE_SQL})`);
9023
9152
  params.push(opts.userId);
9024
9153
  }
9025
9154
  const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
9026
- const totalsRow = getDb().prepare(`SELECT
9155
+ const totalsRow = getDb().prepare(`WITH RECURSIVE ${HUMAN_FREE_TASKS_CTE}
9156
+ SELECT
9027
9157
  COALESCE(SUM(sc.totalCostUsd), 0) as totalCostUsd,
9028
9158
  COALESCE(SUM(sc.inputTokens), 0) as totalInputTokens,
9029
9159
  COALESCE(SUM(sc.outputTokens), 0) as totalOutputTokens,
@@ -9031,8 +9161,13 @@ function getSessionCostSummary(opts) {
9031
9161
  COALESCE(SUM(sc.cacheWriteTokens), 0) as totalCacheWriteTokens,
9032
9162
  COALESCE(SUM(sc.durationMs), 0) as totalDurationMs,
9033
9163
  COUNT(*) as totalSessions,
9034
- COALESCE(SUM(CASE WHEN t.requestedByUserId IS NOT NULL THEN sc.totalCostUsd ELSE 0 END), 0)
9035
- as attributedCostUsd
9164
+ COALESCE(SUM(CASE WHEN t.requestedByUserId IS NOT NULL AND NOT ${HUMAN_FREE_SQL}
9165
+ THEN sc.totalCostUsd ELSE 0 END), 0) as attributedCostUsd,
9166
+ COALESCE(SUM(CASE WHEN NOT ${HUMAN_FREE_SQL}
9167
+ THEN sc.totalCostUsd ELSE 0 END), 0) as attributableCostUsd,
9168
+ COALESCE(SUM(CASE WHEN ${HUMAN_FREE_SQL}
9169
+ THEN sc.totalCostUsd ELSE 0 END), 0) as excludedCostUsd,
9170
+ COUNT(DISTINCT CASE WHEN ${HUMAN_FREE_SQL} THEN t.id END) as excludedTaskCount
9036
9171
  ${from} ${where}`).get(...params);
9037
9172
  const totals = totalsRow ? {
9038
9173
  ...totalsRow,
@@ -9046,12 +9181,16 @@ function getSessionCostSummary(opts) {
9046
9181
  totalDurationMs: 0,
9047
9182
  totalSessions: 0,
9048
9183
  avgCostPerSession: 0,
9049
- attributedCostUsd: 0
9184
+ attributedCostUsd: 0,
9185
+ attributableCostUsd: 0,
9186
+ excludedCostUsd: 0,
9187
+ excludedTaskCount: 0
9050
9188
  };
9051
9189
  const groupBy = opts.groupBy ?? "both";
9052
9190
  let daily = [];
9053
9191
  if (groupBy === "day" || groupBy === "both") {
9054
- daily = getDb().prepare(`SELECT
9192
+ daily = getDb().prepare(`WITH RECURSIVE ${HUMAN_FREE_TASKS_CTE}
9193
+ SELECT
9055
9194
  DATE(sc.createdAt) as date,
9056
9195
  COALESCE(SUM(sc.totalCostUsd), 0) as costUsd,
9057
9196
  COALESCE(SUM(sc.inputTokens), 0) as inputTokens,
@@ -9063,7 +9202,8 @@ function getSessionCostSummary(opts) {
9063
9202
  }
9064
9203
  let byAgent = [];
9065
9204
  if (groupBy === "agent" || groupBy === "both") {
9066
- byAgent = getDb().prepare(`SELECT
9205
+ byAgent = getDb().prepare(`WITH RECURSIVE ${HUMAN_FREE_TASKS_CTE}
9206
+ SELECT
9067
9207
  sc.agentId as agentId,
9068
9208
  COALESCE(SUM(sc.totalCostUsd), 0) as costUsd,
9069
9209
  COALESCE(SUM(sc.inputTokens), 0) as inputTokens,
@@ -9076,19 +9216,175 @@ function getSessionCostSummary(opts) {
9076
9216
  }
9077
9217
  let byUser = [];
9078
9218
  if (groupBy === "user" || groupBy === "both") {
9079
- byUser = getDb().prepare(`SELECT
9080
- t.requestedByUserId as userId,
9219
+ byUser = getDb().prepare(`WITH RECURSIVE ${HUMAN_FREE_TASKS_CTE}
9220
+ SELECT
9221
+ CASE WHEN ${HUMAN_FREE_SQL} THEN NULL ELSE t.requestedByUserId END as userId,
9081
9222
  COALESCE(SUM(sc.totalCostUsd), 0) as costUsd,
9082
9223
  COALESCE(SUM(sc.inputTokens), 0) as inputTokens,
9083
9224
  COALESCE(SUM(sc.outputTokens), 0) as outputTokens,
9084
9225
  COUNT(DISTINCT sc.taskId) as tasks,
9085
9226
  COALESCE(SUM(sc.durationMs), 0) as durationMs
9086
9227
  ${from} ${where}
9087
- GROUP BY t.requestedByUserId
9228
+ GROUP BY CASE WHEN ${HUMAN_FREE_SQL} THEN NULL ELSE t.requestedByUserId END
9088
9229
  ORDER BY costUsd DESC`).all(...params);
9089
9230
  }
9090
9231
  return { totals, daily, byAgent, byUser };
9091
9232
  }
9233
+ function getAttributionByPerson(opts) {
9234
+ const conditions = ["t.requestedByUserId IS NOT NULL"];
9235
+ const params = [];
9236
+ if (opts.startDate) {
9237
+ conditions.push("t.createdAt >= ?");
9238
+ params.push(opts.startDate);
9239
+ }
9240
+ if (opts.endDate) {
9241
+ const dateOnlyEnd = /^\d{4}-\d{2}-\d{2}$/.test(opts.endDate) ? new Date(`${opts.endDate}T00:00:00.000Z`) : null;
9242
+ if (dateOnlyEnd && !Number.isNaN(dateOnlyEnd.getTime()) && dateOnlyEnd.toISOString().slice(0, 10) === opts.endDate) {
9243
+ dateOnlyEnd.setUTCDate(dateOnlyEnd.getUTCDate() + 1);
9244
+ conditions.push("t.createdAt < ?");
9245
+ params.push(dateOnlyEnd.toISOString());
9246
+ } else {
9247
+ conditions.push("t.createdAt <= ?");
9248
+ params.push(opts.endDate);
9249
+ }
9250
+ }
9251
+ const where = `WHERE ${conditions.join(" AND ")}`;
9252
+ const rootRows = getDb().prepare(`WITH RECURSIVE selected_roots(id, requestedByUserId, status, output) AS (
9253
+ SELECT t.id, t.requestedByUserId, t.status, t.output
9254
+ FROM agent_tasks t
9255
+ ${where} AND t.parentTaskId IS NULL AND NOT ${ROOT_HUMAN_FREE_SQL}
9256
+ ),
9257
+ task_tree(rootId, taskId, output) AS (
9258
+ SELECT id, id, output
9259
+ FROM selected_roots
9260
+
9261
+ UNION ALL
9262
+
9263
+ SELECT tree.rootId, child.id, child.output
9264
+ FROM agent_tasks child
9265
+ JOIN task_tree tree ON child.parentTaskId = tree.taskId
9266
+ )
9267
+ SELECT
9268
+ t.requestedByUserId as userId,
9269
+ COUNT(*) as initiated,
9270
+ SUM(CASE WHEN t.status = 'completed' AND (
9271
+ EXISTS (
9272
+ SELECT 1
9273
+ FROM task_tree tree
9274
+ JOIN task_attachments ta ON ta.task_id = tree.taskId
9275
+ WHERE tree.rootId = t.id
9276
+ AND ta.kind = 'url'
9277
+ AND (
9278
+ ta.url LIKE '%github.com/%/pull/%'
9279
+ OR ta.url LIKE '%/-/merge_requests/%'
9280
+ )
9281
+ )
9282
+ OR EXISTS (
9283
+ SELECT 1 FROM task_attachments ta
9284
+ JOIN task_tree tree ON tree.taskId = ta.task_id
9285
+ WHERE tree.rootId = t.id AND ta.kind = 'page'
9286
+ )
9287
+ OR EXISTS (
9288
+ SELECT 1 FROM task_tree tree
9289
+ WHERE tree.rootId = t.id
9290
+ AND (
9291
+ tree.output LIKE '%github.com/%/pull/%'
9292
+ OR tree.output LIKE '%/-/merge_requests/%'
9293
+ )
9294
+ )
9295
+ ) THEN 1 ELSE 0 END) as shipped
9296
+ FROM selected_roots t
9297
+ GROUP BY t.requestedByUserId`).all(...params);
9298
+ const reachRows = getDb().prepare(`WITH RECURSIVE report_tasks AS (
9299
+ SELECT t.*
9300
+ FROM agent_tasks t
9301
+ ${where}
9302
+ ),
9303
+ task_ancestry(
9304
+ taskId, id, parentTaskId, requestedByUserId, requestedByUserIdInherited,
9305
+ taskType, tags, source, workflowRunId
9306
+ ) AS (
9307
+ SELECT
9308
+ id, id, parentTaskId, requestedByUserId, requestedByUserIdInherited,
9309
+ taskType, tags, source, workflowRunId
9310
+ FROM report_tasks
9311
+
9312
+ UNION ALL
9313
+
9314
+ SELECT
9315
+ child.taskId, parent.id, parent.parentTaskId, parent.requestedByUserId,
9316
+ parent.requestedByUserIdInherited, parent.taskType, parent.tags,
9317
+ parent.source, parent.workflowRunId
9318
+ FROM agent_tasks parent
9319
+ JOIN task_ancestry child ON parent.id = child.parentTaskId
9320
+ WHERE child.requestedByUserId IS NULL
9321
+ OR child.requestedByUserIdInherited = 1
9322
+ ),
9323
+ human_free_report_tasks(id) AS (
9324
+ SELECT DISTINCT ancestor.taskId
9325
+ FROM task_ancestry ancestor
9326
+ LEFT JOIN agent_tasks parent ON parent.id = ancestor.parentTaskId
9327
+ WHERE COALESCE(ancestor.taskType, '') IN ('heartbeat', 'heartbeat-checklist', 'boot-triage')
9328
+ OR COALESCE(ancestor.tags, '[]') LIKE '%"heartbeat"%'
9329
+ OR (COALESCE(ancestor.source, '') = 'schedule' AND ancestor.requestedByUserId IS NULL)
9330
+ OR (
9331
+ ancestor.parentTaskId IS NULL
9332
+ AND COALESCE(ancestor.source, '') = 'workflow'
9333
+ AND ancestor.requestedByUserId IS NULL
9334
+ AND EXISTS (
9335
+ SELECT 1
9336
+ FROM workflow_runs run
9337
+ WHERE run.id = ancestor.workflowRunId
9338
+ AND run.triggerType = 'schedule'
9339
+ AND run.created_by IS NULL
9340
+ )
9341
+ )
9342
+ OR (
9343
+ COALESCE(ancestor.source, '') = 'system'
9344
+ AND parent.id IS NOT NULL
9345
+ AND parent.requestedByUserId IS NULL
9346
+ )
9347
+ )
9348
+ SELECT
9349
+ t.requestedByUserId as userId,
9350
+ COUNT(DISTINCT t.agentId) as agentsReached,
9351
+ COUNT(DISTINCT t.vcsRepo) as reposReached,
9352
+ COUNT(DISTINCT t.source) as surfacesReached
9353
+ FROM report_tasks t
9354
+ WHERE NOT EXISTS (SELECT 1 FROM human_free_report_tasks WHERE id = t.id)
9355
+ GROUP BY t.requestedByUserId`).all(...params);
9356
+ const byUser = new Map;
9357
+ for (const r of rootRows) {
9358
+ byUser.set(r.userId, {
9359
+ userId: r.userId,
9360
+ problemsInitiated: r.initiated,
9361
+ problemsShipped: r.shipped,
9362
+ agentsReached: 0,
9363
+ reposReached: 0,
9364
+ surfacesReached: 0,
9365
+ firstPassYield: null
9366
+ });
9367
+ }
9368
+ for (const r of reachRows) {
9369
+ const existing = byUser.get(r.userId);
9370
+ if (existing) {
9371
+ existing.agentsReached = r.agentsReached;
9372
+ existing.reposReached = r.reposReached;
9373
+ existing.surfacesReached = r.surfacesReached;
9374
+ } else {
9375
+ byUser.set(r.userId, {
9376
+ userId: r.userId,
9377
+ problemsInitiated: 0,
9378
+ problemsShipped: 0,
9379
+ agentsReached: r.agentsReached,
9380
+ reposReached: r.reposReached,
9381
+ surfacesReached: r.surfacesReached,
9382
+ firstPassYield: null
9383
+ });
9384
+ }
9385
+ }
9386
+ return Array.from(byUser.values());
9387
+ }
9092
9388
  function getDashboardCostSummary() {
9093
9389
  const now = new Date;
9094
9390
  const startOfDayUtc = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())).toISOString();
@@ -9766,9 +10062,9 @@ function findTaskByAgentMailThread(agentmailThreadId) {
9766
10062
  function insertActiveSession(session) {
9767
10063
  const id = crypto.randomUUID();
9768
10064
  const now = new Date().toISOString();
9769
- const row = getDb().prepare(`INSERT INTO active_sessions (id, agentId, taskId, triggerType, inboxMessageId, taskDescription, runnerSessionId, startedAt, lastHeartbeatAt)
9770
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
9771
- RETURNING *`).get(id, session.agentId, session.taskId ?? null, session.triggerType, session.inboxMessageId ?? null, session.taskDescription ?? null, session.runnerSessionId ?? null, now, now);
10065
+ const row = getDb().prepare(`INSERT INTO active_sessions (id, agentId, taskId, triggerType, inboxMessageId, taskDescription, runnerSessionId, runtimeInstanceId, startedAt, lastHeartbeatAt)
10066
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
10067
+ RETURNING *`).get(id, session.agentId, session.taskId ?? null, session.triggerType, session.inboxMessageId ?? null, session.taskDescription ?? null, session.runnerSessionId ?? null, session.runtimeInstanceId ?? null, now, now);
9772
10068
  if (!row)
9773
10069
  throw new Error("Failed to insert active session");
9774
10070
  return row;
@@ -10075,6 +10371,7 @@ function rowToWorkflowRun(row) {
10075
10371
  triggerData: row.triggerData ? JSON.parse(row.triggerData) : undefined,
10076
10372
  context: row.context ? JSON.parse(row.context) : undefined,
10077
10373
  error: row.error ?? undefined,
10374
+ createdBy: row.created_by ?? undefined,
10078
10375
  startedAt: normalizeDateRequired(row.startedAt),
10079
10376
  lastUpdatedAt: normalizeDateRequired(row.lastUpdatedAt),
10080
10377
  finishedAt: normalizeDate(row.finishedAt) ?? undefined
@@ -10082,7 +10379,7 @@ function rowToWorkflowRun(row) {
10082
10379
  }
10083
10380
  function createWorkflowRun(data) {
10084
10381
  const now = new Date().toISOString();
10085
- const row = getDb().prepare(`INSERT INTO workflow_runs (id, workflowId, startedAt, triggerData) VALUES (?, ?, ?, ?) RETURNING *`).get(data.id, data.workflowId, now, data.triggerData ? JSON.stringify(data.triggerData) : null);
10382
+ const row = getDb().prepare(`INSERT INTO workflow_runs (id, workflowId, triggerType, startedAt, triggerData, created_by) VALUES (?, ?, ?, ?, ?, ?) RETURNING *`).get(data.id, data.workflowId, data.triggerType ?? "manual", now, data.triggerData ? JSON.stringify(data.triggerData) : null, data.createdBy ?? null);
10086
10383
  if (!row)
10087
10384
  throw new Error("Failed to create workflow run");
10088
10385
  return rowToWorkflowRun(row);
@@ -11969,10 +12266,63 @@ function updateUser(id, data) {
11969
12266
  const row = getDb().prepare(`UPDATE users SET ${sets.join(", ")} WHERE id = ? RETURNING *`).get(...params);
11970
12267
  return row ? rowToUser(row) : null;
11971
12268
  }
11972
- function deleteUser(id) {
11973
- getDb().prepare("UPDATE agent_tasks SET requestedByUserId = NULL WHERE requestedByUserId = ?").run(id);
11974
- const result = getDb().prepare("DELETE FROM users WHERE id = ?").run(id);
11975
- return result.changes > 0;
12269
+ function quoteSqlIdentifier(identifier) {
12270
+ return `"${identifier.replaceAll('"', '""')}"`;
12271
+ }
12272
+ function deleteUser(id, replacementUserId) {
12273
+ if (replacementUserId === id) {
12274
+ throw new Error("Replacement user must differ from deleted user");
12275
+ }
12276
+ const database = getDb();
12277
+ return database.transaction(() => {
12278
+ const userExists = database.prepare("SELECT EXISTS(SELECT 1 FROM users WHERE id = ?) AS present").get(id)?.present;
12279
+ if (!userExists)
12280
+ return false;
12281
+ if (replacementUserId) {
12282
+ const replacementExists = database.prepare("SELECT EXISTS(SELECT 1 FROM users WHERE id = ?) AS present").get(replacementUserId)?.present;
12283
+ if (!replacementExists)
12284
+ throw new Error("Replacement user not found");
12285
+ }
12286
+ const references = database.prepare(`SELECT tables.name AS tableName, foreign_keys."from" AS columnName
12287
+ FROM sqlite_schema AS tables
12288
+ JOIN pragma_foreign_key_list(tables.name) AS foreign_keys
12289
+ JOIN pragma_table_info(tables.name) AS columns
12290
+ ON columns.name = foreign_keys."from"
12291
+ WHERE tables.type = 'table'
12292
+ AND foreign_keys."table" = 'users'
12293
+ AND foreign_keys.on_delete IN ('NO ACTION', 'RESTRICT')
12294
+ AND columns."notnull" = 0
12295
+ UNION ALL
12296
+ SELECT 'scheduled_tasks' AS tableName, columns.name AS columnName
12297
+ FROM pragma_table_info('scheduled_tasks') AS columns
12298
+ WHERE columns.name IN ('created_by', 'updated_by')
12299
+ AND columns."notnull" = 0
12300
+ AND NOT EXISTS (
12301
+ SELECT 1
12302
+ FROM pragma_foreign_key_list('scheduled_tasks') AS foreign_keys
12303
+ WHERE foreign_keys."from" = columns.name
12304
+ AND foreign_keys."table" = 'users'
12305
+ )`).all();
12306
+ const replacement = replacementUserId ?? null;
12307
+ for (const reference of references) {
12308
+ const table = quoteSqlIdentifier(reference.tableName);
12309
+ const column = quoteSqlIdentifier(reference.columnName);
12310
+ database.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).run(replacement, id);
12311
+ }
12312
+ if (replacementUserId) {
12313
+ database.prepare(`UPDATE workflow_runs
12314
+ SET context = json_set(context, '$.swarm.requestedByUserId', ?)
12315
+ WHERE json_valid(context)
12316
+ AND json_extract(context, '$.swarm.requestedByUserId') = ?`).run(replacementUserId, id);
12317
+ } else {
12318
+ database.prepare(`UPDATE workflow_runs
12319
+ SET context = json_remove(context, '$.swarm.requestedByUserId')
12320
+ WHERE json_valid(context)
12321
+ AND json_extract(context, '$.swarm.requestedByUserId') = ?`).run(id);
12322
+ }
12323
+ const result = database.prepare("DELETE FROM users WHERE id = ?").run(id);
12324
+ return result.changes > 0;
12325
+ })();
11976
12326
  }
11977
12327
  function rowToInboxItemState(row) {
11978
12328
  return {
@@ -12811,7 +13161,54 @@ function countScriptRunJournalAgentTaskSteps(runId) {
12811
13161
  const row = getDb().prepare("SELECT COUNT(*) AS count FROM script_run_journal WHERE runId = ? AND stepType = 'agent-task'").get(runId);
12812
13162
  return row?.count ?? 0;
12813
13163
  }
12814
- var db = null, sqliteVecAvailable = false, VERSIONABLE_FIELDS, agentQueries, MAX_EMPTY_POLLS = 2, taskQueries, PENDING_SLACK_MESSAGE_TS_PREFIX = "pending:", findTaskByGitHub, LINEAR_TRACKER_CONTEXT_KEY_PREFIX = "task:trackers:linear:", logQueries, ELIGIBILITY_SCAN_BATCH_SIZE, ELIGIBILITY_SCAN_CAP, sessionLogQueries, sessionCostQueries, UNATTRIBUTED_USER_ID = "unattributed", SCHEDULE_TEMPLATE_PREVIEW_LENGTH = 280, TASK_PREVIEW_LENGTH = 300, RESERVED_CONFIG_PLACEHOLDER = "[reserved key stored in swarm_config; delete this row]", SKILL_FILE_LIMITS, BINARY_SKILL_FILE_PLACEHOLDER = "[binary file - not synced]", SKILL_SLIM_COLUMNS = "id, name, description, type, scope, ownerAgentId, sourceUrl, sourceRepo, sourcePath, sourceBranch, sourceHash, isComplex, allowedTools, model, effort, context, agent, disableModelInvocation, userInvocable, version, isEnabled, systemDefault, createdAt, lastUpdatedAt, lastFetchedAt, '' as content", contextSnapshotQueries, KvTypeCollisionError;
13164
+ var db = null, sqliteVecAvailable = false, cachedSqliteVecExtensionPath = null, VERSIONABLE_FIELDS, BUDGETED_IDENTITY_FIELDS, agentQueries, MAX_EMPTY_POLLS = 2, taskQueries, PENDING_SLACK_MESSAGE_TS_PREFIX = "pending:", findTaskByGitHub, LINEAR_TRACKER_CONTEXT_KEY_PREFIX = "task:trackers:linear:", GENERATED_PULL_REQUEST_PROVIDER_ID = "github", GENERATED_PULL_REQUEST_INTENT = "task-deliverable", GENERATED_PULL_REQUEST_DESCRIPTION = "Pull request shipped by this task", GENERATED_PULL_REQUEST_SOURCE = "task-pull-request-recorder", logQueries, ELIGIBILITY_SCAN_BATCH_SIZE, ELIGIBILITY_SCAN_CAP, sessionLogQueries, sessionCostQueries, UNATTRIBUTED_USER_ID = "unattributed", HUMAN_FREE_TASKS_CTE = `human_free_tasks(id) AS (
13165
+ SELECT task.id
13166
+ FROM agent_tasks task
13167
+ LEFT JOIN agent_tasks parent ON parent.id = task.parentTaskId
13168
+ WHERE COALESCE(task.taskType, '') IN ('heartbeat', 'heartbeat-checklist', 'boot-triage')
13169
+ OR COALESCE(task.tags, '[]') LIKE '%"heartbeat"%'
13170
+ OR (COALESCE(task.source, '') = 'schedule' AND task.requestedByUserId IS NULL)
13171
+ OR (
13172
+ task.parentTaskId IS NULL
13173
+ AND COALESCE(task.source, '') = 'workflow'
13174
+ AND task.requestedByUserId IS NULL
13175
+ AND EXISTS (
13176
+ SELECT 1
13177
+ FROM workflow_runs run
13178
+ WHERE run.id = task.workflowRunId
13179
+ AND run.triggerType = 'schedule'
13180
+ AND run.created_by IS NULL
13181
+ )
13182
+ )
13183
+ OR (
13184
+ COALESCE(task.source, '') = 'system'
13185
+ AND parent.id IS NOT NULL
13186
+ AND parent.requestedByUserId IS NULL
13187
+ )
13188
+
13189
+ UNION
13190
+
13191
+ SELECT child.id
13192
+ FROM agent_tasks child
13193
+ JOIN human_free_tasks parent ON child.parentTaskId = parent.id
13194
+ WHERE child.requestedByUserId IS NULL
13195
+ OR child.requestedByUserIdInherited = 1
13196
+ )`, HUMAN_FREE_SQL = "EXISTS (SELECT 1 FROM human_free_tasks WHERE id = t.id)", ROOT_HUMAN_FREE_SQL = `(
13197
+ COALESCE(t.taskType, '') IN ('heartbeat', 'heartbeat-checklist', 'boot-triage')
13198
+ OR COALESCE(t.tags, '[]') LIKE '%"heartbeat"%'
13199
+ OR (COALESCE(t.source, '') = 'schedule' AND t.requestedByUserId IS NULL)
13200
+ OR (
13201
+ COALESCE(t.source, '') = 'workflow'
13202
+ AND t.requestedByUserId IS NULL
13203
+ AND EXISTS (
13204
+ SELECT 1
13205
+ FROM workflow_runs run
13206
+ WHERE run.id = t.workflowRunId
13207
+ AND run.triggerType = 'schedule'
13208
+ AND run.created_by IS NULL
13209
+ )
13210
+ )
13211
+ )`, SCHEDULE_TEMPLATE_PREVIEW_LENGTH = 280, TASK_PREVIEW_LENGTH = 300, RESERVED_CONFIG_PLACEHOLDER = "[reserved key stored in swarm_config; delete this row]", SKILL_FILE_LIMITS, BINARY_SKILL_FILE_PLACEHOLDER = "[binary file - not synced]", SKILL_SLIM_COLUMNS = "id, name, description, type, scope, ownerAgentId, sourceUrl, sourceRepo, sourcePath, sourceBranch, sourceHash, isComplex, allowedTools, model, effort, context, agent, disableModelInvocation, userInvocable, version, isEnabled, systemDefault, createdAt, lastUpdatedAt, lastFetchedAt, '' as content", contextSnapshotQueries, KvTypeCollisionError;
12815
13212
  var init_db = __esm(() => {
12816
13213
  init_provider_metadata();
12817
13214
  init_package();
@@ -12822,6 +13219,8 @@ var init_db = __esm(() => {
12822
13219
  init_types();
12823
13220
  init_credentials();
12824
13221
  init_env_flag();
13222
+ init_github_pull_request();
13223
+ init_identity_field_budget();
12825
13224
  init_request_auth_context();
12826
13225
  init_secret_scrubber();
12827
13226
  init_asset_key_audit();
@@ -12843,6 +13242,12 @@ var init_db = __esm(() => {
12843
13242
  "setupScript",
12844
13243
  "heartbeatMd"
12845
13244
  ];
13245
+ BUDGETED_IDENTITY_FIELDS = [
13246
+ "soulMd",
13247
+ "identityMd",
13248
+ "claudeMd",
13249
+ "toolsMd"
13250
+ ];
12846
13251
  agentQueries = {
12847
13252
  insert: () => getDb().prepare("INSERT INTO agents (id, name, isLead, status, maxTasks, provider, harness_provider, createdAt, lastUpdatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) RETURNING *"),
12848
13253
  getById: () => getDb().prepare("SELECT * FROM agents WHERE id = ?"),
@@ -12932,4 +13337,4 @@ var init_db = __esm(() => {
12932
13337
  };
12933
13338
  });
12934
13339
 
12935
- export { normalizeAssetKey, defaultAssetKey, parseAssetKey, canWriteAssetKey, init_key, slackContextKey, agentmailContextKey, githubContextKey, gitlabContextKey, linearContextKey, buildJiraContextKey, scheduleContextKey, workflowContextKey, agentContextKey, pageContextKey, init_context_key, checkSlackRoutingCoherence, init_slack_routing, initTelemetry, telemetry, init_telemetry, $OpenAPIRegistry, $OpenApiGeneratorV31, init_dist, init_zod_openapi, AssetKeySchema, AssetEntityTypeSchema, AssetKeyMappingSchema, AssetSummarySchema, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringSourceSchema, SteeringMessageSchema, SteerOutcomeSchema, OnUnsupportedSchema, SteerResultSchema, FollowUpConfigSchema, AgentTaskSchema, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentAvatarSchema, AgentSchema, AgentLatestModelSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChannelTypeSchema, ServiceStatusSchema, ServiceSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostModelBreakdownSchema, SessionCostSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, SwarmEventSchema, ScheduledTaskTargetTypeSchema, ScheduledTaskSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, ActiveSessionSchema, WorkflowEdgeSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, WorkflowSchema, WorkflowVersionSchema, PageContentTypeSchema, PageAuthModeSchema, PageSchema, PageVersionSchema, MetricWidgetSchema, MetricDefinitionSchema, MetricSchema, MetricVersionSchema, WorkflowRunStatusSchema, WorkflowRunSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, ScriptRunSchema, ScriptRunListItemSchema, ScriptRunJournalEntrySchema, WorkflowRunStepSchema, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptRecordSchema, ScriptVersionRecordSchema, ScriptApiAuthModeSchema, ScriptApiRecordSchema, SkillSchema, AgentSkillSchema, SkillWithInstallInfoSchema, SkillFileSchema, McpAuthMethodSchema, McpServerSchema, AgentMcpServerSchema, McpServerWithInstallInfoSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, ContextSnapshotSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, BudgetRefusedTriggerSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, KvEntrySchema, init_types, setRequestAuth, getRequestAuth, getCurrentRequestAuth, init_request_auth_context, auditAssetKeys, init_asset_key_audit, CredentialBindingSchema, placeholderForConfigKey, CredentialBroker, DEFAULT_CREDENTIAL_BINDINGS, init_credential_broker, encryptSecret, decryptSecret, getEncryptionKey, init_crypto, normalizeDate, normalizeDateRequired, init_date_utils, init_templates, init_templates2 as init_templates1, SteeringRequestError, isSteeringEnabled2 as isSteeringEnabled, getTaskSteeringFields, promotePendingSteeringForTask, markSteeringUndeliverable, requestSteering, init_steering, isReservedConfigKey, reservedKeyError, validateConfigValue, init_swarm_config_guard, onTaskStarted, init_task_lifecycle_events, generateDefaultClaudeMd, generateDefaultSoulMd, generateDefaultIdentityMd, generateDefaultToolsMd, init_defaults, isSqliteVecAvailable, initDb, getDb, closeDb, computeContentHash, createContextVersion, getLatestContextVersion, getContextVersion, getContextVersionHistory, agentQueries, updateAgentCredentialState, createAgent, getAgentById, getAllAgents, getLeadAgent, updateAgentStatus, updateAgentMaxTasks, updateAgentProvider, setAgentHarnessProvider, updateAgentCredStatus, listAgentsWithCredStatusByProvider, getAgentHarnessProviders, updateAgentActivity, MAX_EMPTY_POLLS, incrementEmptyPollCount, resetEmptyPollCount, shouldBlockPolling, deleteAgent, getActiveTaskCount, hasCapacity, getRemainingCapacity, updateAgentStatusFromCapacity, isPoolAffinityEnforcementEnabled, buildRoutingAffinityFromAgent, isAgentEligibleForTask, taskQueries, createTask, getPendingTaskForAgent, assignUnassignedTaskPending, startTask, getTaskById, getSlackRenderV2ActivatedAt, ensureSlackRenderV2Activation, isPendingSlackMessage, recordSlackMessage, reserveSlackMessage, bindSlackMessageTimestamp, updateSlackMessageRecord, markSlackTreeRendered, deleteSlackMessageRecord, getSlackTreeMessage, getSlackTreeMessageByThread, getSlackOutcomeMessage, getSlackTreeMessages, getSlackMessageByChannelTs, getSlackTasksInThread, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskTitle, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getSlackTasksMissingTree, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getLatestScriptRunStepTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getLatestLeadTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, overwriteTerminalTaskResultText, cancelTask, supersedeTask, backfillSupersedeTaskResumeTaskId, pauseTask, resumeTask, getPausedTasksForAgent, getOrphanedInProgressTasksForAgent, resetOrphanedInProgressTasksForAgent, getRecentlyCancelledTasksForAgent, deleteTask, updateTaskProgress, insertTaskAttachment, getAssetKeyMappingByProvider, upsertAssetKeyMapping, getAssetKeyMapping, listAssetSummaries, moveAssetKey, deleteTaskAttachment, replaceTaskAttachment, getTaskAttachments, createSteeringMessage, getSteeringMessagesForTask, getSteeringMessageById, getPendingSteeringForTask, getPendingSteeringForAgent, markSteeringDelivered, markSteeringHandled, markSteeringPromoted, cancelPendingSteeringForTask, hasPendingSteering, getAgentWithTasks, getAllAgentsWithTasks, logQueries, createLogEntry, getLogsByAgentId, getLogsByTaskId, getLogsByTaskIdChronological, getLogsByEventType, getAllLogs, findRecentSimilarTasks, createTaskExtended, claimTask, releaseTask, acceptTask, rejectTask, moveTaskToBacklog, moveTaskFromBacklog, releaseStaleReviewingTasks, getOfferedTasksForAgent, claimOfferedTask, getUnassignedTasksCount, getUnassignedTaskIds, getUnassignedTaskIdsForAgent, checkDependencies, getDependentTasks, cascadeFailDependents, updateAgentProfile, updateAgentName, createChannel, getMessageById, getChannelById, getChannelByName, getAllChannels, deleteChannel, postMessage, getChannelMessages, updateReadState, getLastReadAt, getUnreadMessages, getMentionsForAgent, getInboxSummary, claimMentions, releaseMentionProcessing, releaseStaleMentionProcessing, createService, getServiceById, getServiceByAgentAndName, getServicesByAgentId, getAllServices, updateServiceStatus, deleteService, upsertService, deleteServicesByAgentId, sessionLogQueries, createSessionLogs, getSessionLogsByTaskId, getSessionLogsBySession, createSessionCost, getSessionCostsByTaskId, getSessionCostsByAgentId, getAllSessionCosts, getSessionCostsFiltered, UNATTRIBUTED_USER_ID, getSessionCostSummary, getDashboardCostSummary, createInboxMessage, getInboxMessageById, getUnreadInboxMessages, claimInboxMessages, markInboxMessageRead, markInboxMessageResponded, markInboxMessageDelegated, releaseStaleProcessingInbox, getConcurrentContext, getScheduledTasks, getScheduledTaskById, getScheduledTaskByName, createScheduledTask, updateScheduledTask, deleteScheduledTask, getDueScheduledTasks, autoEncryptLegacyPlaintextSecrets, maskSecrets, getSwarmConfigs, getInjectableGlobalConfigs, getSwarmConfigById, getSwarmConfigLookupById, upsertSwarmConfig, deleteSwarmConfig, deleteSwarmConfigByKey, getResolvedConfig, getSwarmRepos, getSwarmRepoById, getSwarmRepoByName, getSwarmRepoByUrl, createSwarmRepo, updateSwarmRepo, deleteSwarmRepo, getAgentMailInboxMapping, getAgentMailInboxMappingsByAgent, getAllAgentMailInboxMappings, createAgentMailInboxMapping, deleteAgentMailInboxMapping, findTaskByAgentMailThread, insertActiveSession, deleteActiveSession, deleteActiveSessionById, getActiveSessions, heartbeatActiveSession, cleanupStaleSessions, cleanupAgentSessions, updateActiveSessionProviderSessionId, getActiveSessionForTask, reassociateSessionLogs, getStalledInProgressTasks, getStalePinnedResumes, failPendingResumeIfUnclaimed, getIdleWorkersWithCapacity, getUnassignedPoolTasks, getStaleUnassignedAffinityTasks, getRecentFailedTasks, getRecentCompletedCount, getRecentFailedCount, createWorkflow, getWorkflow, listWorkflows, updateWorkflow, deleteWorkflow, getWorkflowsByScheduleId, createWorkflowRun, getWorkflowRun, updateWorkflowRun, listWorkflowRuns, countWorkflowRuns, listWorkflowRunsPage, createWorkflowRunStep, getWorkflowRunStep, updateWorkflowRunStep, getWorkflowRunStepsByRunId, getStuckWorkflowRuns, getLastSuccessfulRun, getLastRunStart, getRetryableSteps, getCompletedStepNodeIds, getTaskByWorkflowRunStepId, detachTaskFromWorkflowRunStep, getStepByIdempotencyKey, getStepCountForNode, getLatestStepForNode, createWorkflowVersion, getWorkflowVersions, getWorkflowVersion, createAppVersion, getAppVersions, getAppVersion, createPage, getPage, getPageBySlug, getLatestPageBySlug, listPagesByAgent, listAllPages, countAllPages, countPagesByAgent, updatePage, deletePage, incrementPageViewCount, createPageVersion, getPageVersions, getPageVersion, createMetric, getMetric, getMetricBySlug, listMetricsByAgent, listAllMetrics, countAllMetrics, countMetricsByAgent, updateMetric, deleteMetric, createMetricVersion, getMetricVersions, getMetricVersion, getPromptTemplates, getPromptTemplateById, upsertPromptTemplate, deletePromptTemplate, resetPromptTemplateToDefault, getPromptTemplateHistory, resolvePromptTemplate, checkoutPromptTemplate, getAllChannelActivityCursors, getChannelActivityCursor, upsertChannelActivityCursor, createApprovalRequest, getApprovalRequestById, resolveApprovalRequest, updateApprovalRequestNotifications, listApprovalRequests, getStuckApprovalRuns, getApprovalRequestByStepId, getExpiredPendingApprovals, createWaitState, getWaitStateById, getWaitStateByStepId, getDueWaitStates, getPendingEventWaitNames, getPendingWaitsByEvent, resolveWaitState, getStuckWaitRuns, SKILL_FILE_LIMITS, normalizeSkillFilePath, createSkill, updateSkill, listSkillFileManifest, getSkillFiles, getSkillFile, upsertSkillFile, upsertSkillFiles, deleteSkillFile, deleteSkill, getSkillById, getSkillByName, listSkills, searchSkills, installSkill, getSystemDefaultSkills, installSystemDefaultSkillsForAgent, uninstallSkill, getAgentSkills, toggleAgentSkill, createMcpServer, updateMcpServer, deleteMcpServer, getMcpServerById, getMcpServerByName, listMcpServers, installMcpServer, uninstallMcpServer, getAgentMcpServers, createContextSnapshot, getContextSnapshotsByTaskId, getContextSnapshotsBySessionId, getContextSummaryByTaskId, getAvailableKeyIndices, recordKeyUsage, markKeyRateLimited, recordKeyRateLimitWindows, setApiKeyName, clearKeyRateLimit, getKeyStatuses, getKeyCostSummary, getUserById, getAllUsers, createUser, updateUser, deleteUser, listInboxState, upsertInboxState, listFavorites, listUserFavorites, getFavoriteItemIdSet, setFavorite, setUserFavorite, withFavoriteFlags, listTaskTemplates, getRootTaskChain, listRecentSessions, countSessions, getBudget, getBudgets, upsertBudget, deleteBudget, getAllPricingRows, getPricingRows, getActivePricingRow, insertPricingRow, deletePricingRow, getDailySpendForAgent, getDailySpendGlobal, getDailySpendForUser, recordBudgetRefusalNotification, getBudgetRefusalNotification, getRecentBudgetRefusalNotifications, hasBudgetRefusalNotificationToday, setBudgetRefusalFollowUpTaskId, getLiveAgentCounts, getInstanceActivity, getSwarmMetrics, hasFirstCompletedTask, getKv, sweepExpiredKv, sweepExpiredKvPrefix, upsertKv, deleteKv, KvTypeCollisionError, incrKv, listKv, countKv, createScriptRun, recordInlineScriptRun, getScriptRun, getScriptRunByIdempotencyKey, listScriptRuns, countScriptRuns, countActiveScriptRuns, updateScriptRun, getRunningScriptRuns, getScriptRunJournalStep, upsertScriptRunJournalStep, listScriptRunJournalSteps, countScriptRunJournalSteps, countScriptRunJournalAgentTaskSteps, exports_db, init_db };
13340
+ export { normalizeAssetKey, defaultAssetKey, parseAssetKey, canWriteAssetKey, init_key, slackContextKey, agentmailContextKey, githubContextKey, gitlabContextKey, linearContextKey, buildJiraContextKey, scheduleContextKey, workflowContextKey, agentContextKey, pageContextKey, init_context_key, checkSlackRoutingCoherence, init_slack_routing, initTelemetry, telemetry, init_telemetry, $OpenAPIRegistry, $OpenApiGeneratorV31, init_dist, init_zod_openapi, AssetKeySchema, AssetEntityTypeSchema, AssetKeyMappingSchema, AssetSummarySchema, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringSourceSchema, SteeringMessageSchema, SteerOutcomeSchema, OnUnsupportedSchema, SteerResultSchema, FollowUpConfigSchema, AgentTaskSchema, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, UserCommsPrefsSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentAvatarSchema, AgentSchema, AgentLatestModelSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChannelTypeSchema, ServiceStatusSchema, ServiceSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostModelBreakdownSchema, SessionCostSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, SwarmEventSchema, ScheduledTaskTargetTypeSchema, ScheduledTaskSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, ActiveSessionSchema, RuntimeInstanceSchema, WorkflowEdgeSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, WorkflowSchema, WorkflowVersionSchema, PageContentTypeSchema, PageAuthModeSchema, PageSchema, PageVersionSchema, MetricWidgetSchema, MetricDefinitionSchema, MetricSchema, MetricVersionSchema, WorkflowRunStatusSchema, WorkflowRunSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, ScriptRunSchema, ScriptRunListItemSchema, ScriptRunJournalEntrySchema, WorkflowRunStepSchema, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptRecordSchema, ScriptVersionRecordSchema, ScriptApiAuthModeSchema, ScriptApiRecordSchema, SkillSchema, AgentSkillSchema, SkillWithInstallInfoSchema, SkillFileSchema, McpAuthMethodSchema, McpServerSchema, AgentMcpServerSchema, McpServerWithInstallInfoSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, ContextSnapshotSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, BudgetRefusedTriggerSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, KvEntrySchema, init_types, setRequestAuth, getRequestAuth, getCurrentRequestAuth, init_request_auth_context, auditAssetKeys, init_asset_key_audit, CredentialBindingSchema, placeholderForConfigKey, CredentialBroker, DEFAULT_CREDENTIAL_BINDINGS, init_credential_broker, encryptSecret, decryptSecret, getEncryptionKey, init_crypto, normalizeDate, normalizeDateRequired, init_date_utils, init_templates2 as init_templates, SteeringRequestError, isSteeringEnabled2 as isSteeringEnabled, getTaskSteeringFields, promotePendingSteeringForTask, markSteeringUndeliverable, requestSteering, init_steering, isReservedConfigKey, reservedKeyError, validateConfigValue, init_swarm_config_guard, onTaskStarted, init_task_lifecycle_events, generateDefaultClaudeMd, generateDefaultSoulMd, generateDefaultIdentityMd, generateDefaultToolsMd, init_defaults, isSqliteVecAvailable, resolveSqliteVecExtensionPath, __resetSqliteVecExtensionPathCacheForTests, initDb, getDb, closeDb, computeContentHash, createContextVersion, getLatestContextVersion, getContextVersion, getContextVersionHistory, agentQueries, updateAgentCredentialState, updateAgentCredentialMissing, createAgent, getAgentById, getAllAgents, getLeadAgent, updateAgentStatus, updateAgentMaxTasks, updateAgentProvider, setAgentHarnessProvider, updateAgentCredStatus, listAgentsWithCredStatusByProvider, getAgentHarnessProviders, updateAgentActivity, MAX_EMPTY_POLLS, incrementEmptyPollCount, resetEmptyPollCount, shouldBlockPolling, deleteAgent, getActiveTaskCount, hasCapacity, getRemainingCapacity, updateAgentStatusFromCapacity, isPoolAffinityEnforcementEnabled, buildRoutingAffinityFromAgent, isAgentEligibleForTask, taskQueries, createTask, getPendingTaskForAgent, assignUnassignedTaskPending, startTask, getTaskById, getSlackRenderV2ActivatedAt, ensureSlackRenderV2Activation, isPendingSlackMessage, recordSlackMessage, reserveSlackMessage, bindSlackMessageTimestamp, updateSlackMessageRecord, markSlackTreeRendered, deleteSlackMessageRecord, getSlackTreeMessage, getSlackTreeMessageByThread, getSlackOutcomeMessage, getSlackTreeMessages, getSlackMessageByChannelTs, getSlackTasksInThread, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskTitle, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getSlackTasksMissingTree, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getLatestScriptRunStepTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getLatestLeadTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, overwriteTerminalTaskResultText, cancelTask, supersedeTask, backfillSupersedeTaskResumeTaskId, pauseTask, resumeTask, getPausedTasksForAgent, getOrphanedInProgressTasksForAgent, resetOrphanedInProgressTasksForAgent, getRecentlyCancelledTasksForAgent, deleteTask, updateTaskProgress, insertTaskAttachment, recordTaskPullRequestAttachments, getAssetKeyMappingByProvider, upsertAssetKeyMapping, getAssetKeyMapping, listAssetSummaries, moveAssetKey, deleteTaskAttachment, replaceTaskAttachment, getTaskAttachments, createSteeringMessage, getSteeringMessagesForTask, getSteeringMessageById, getPendingSteeringForTask, getPendingSteeringForAgent, markSteeringDelivered, markSteeringHandled, markSteeringPromoted, cancelPendingSteeringForTask, hasPendingSteering, getAgentWithTasks, getAllAgentsWithTasks, logQueries, createLogEntry, getLogsByAgentId, getLogsByTaskId, getLogsByTaskIdChronological, getLogsByEventType, getAllLogs, findRecentSimilarTasks, createTaskExtended, claimTask, releaseTask, acceptTask, rejectTask, moveTaskToBacklog, moveTaskFromBacklog, releaseStaleReviewingTasks, getOfferedTasksForAgent, claimOfferedTask, getUnassignedTasksCount, getUnassignedTaskIds, getUnassignedTaskIdsForAgent, checkDependencies, getDependentTasks, cascadeFailDependents, updateAgentProfile, updateAgentName, createChannel, getMessageById, getChannelById, getChannelByName, getAllChannels, deleteChannel, postMessage, getChannelMessages, updateReadState, getLastReadAt, getUnreadMessages, getMentionsForAgent, getInboxSummary, claimMentions, releaseMentionProcessing, releaseStaleMentionProcessing, createService, getServiceById, getServiceByAgentAndName, getServicesByAgentId, getAllServices, updateServiceStatus, deleteService, upsertService, deleteServicesByAgentId, sessionLogQueries, createSessionLogs, getSessionLogsByTaskId, getSessionLogsBySession, createSessionCost, getSessionCostsByTaskId, getSessionCostsByAgentId, getAllSessionCosts, getSessionCostsFiltered, UNATTRIBUTED_USER_ID, getSessionCostSummary, getAttributionByPerson, getDashboardCostSummary, createInboxMessage, getInboxMessageById, getUnreadInboxMessages, claimInboxMessages, markInboxMessageRead, markInboxMessageResponded, markInboxMessageDelegated, releaseStaleProcessingInbox, getConcurrentContext, getScheduledTasks, getScheduledTaskById, getScheduledTaskByName, createScheduledTask, updateScheduledTask, deleteScheduledTask, getDueScheduledTasks, autoEncryptLegacyPlaintextSecrets, maskSecrets, getSwarmConfigs, getInjectableGlobalConfigs, getSwarmConfigById, getSwarmConfigLookupById, upsertSwarmConfig, deleteSwarmConfig, deleteSwarmConfigByKey, getResolvedConfig, getSwarmRepos, getSwarmRepoById, getSwarmRepoByName, getSwarmRepoByUrl, createSwarmRepo, updateSwarmRepo, deleteSwarmRepo, getAgentMailInboxMapping, getAgentMailInboxMappingsByAgent, getAllAgentMailInboxMappings, createAgentMailInboxMapping, deleteAgentMailInboxMapping, findTaskByAgentMailThread, insertActiveSession, deleteActiveSession, deleteActiveSessionById, getActiveSessions, heartbeatActiveSession, cleanupStaleSessions, cleanupAgentSessions, updateActiveSessionProviderSessionId, getActiveSessionForTask, reassociateSessionLogs, getStalledInProgressTasks, getStalePinnedResumes, failPendingResumeIfUnclaimed, getIdleWorkersWithCapacity, getUnassignedPoolTasks, getStaleUnassignedAffinityTasks, getRecentFailedTasks, getRecentCompletedCount, getRecentFailedCount, createWorkflow, getWorkflow, listWorkflows, updateWorkflow, deleteWorkflow, getWorkflowsByScheduleId, createWorkflowRun, getWorkflowRun, updateWorkflowRun, listWorkflowRuns, countWorkflowRuns, listWorkflowRunsPage, createWorkflowRunStep, getWorkflowRunStep, updateWorkflowRunStep, getWorkflowRunStepsByRunId, getStuckWorkflowRuns, getLastSuccessfulRun, getLastRunStart, getRetryableSteps, getCompletedStepNodeIds, getTaskByWorkflowRunStepId, detachTaskFromWorkflowRunStep, getStepByIdempotencyKey, getStepCountForNode, getLatestStepForNode, createWorkflowVersion, getWorkflowVersions, getWorkflowVersion, createAppVersion, getAppVersions, getAppVersion, createPage, getPage, getPageBySlug, getLatestPageBySlug, listPagesByAgent, listAllPages, countAllPages, countPagesByAgent, updatePage, deletePage, incrementPageViewCount, createPageVersion, getPageVersions, getPageVersion, createMetric, getMetric, getMetricBySlug, listMetricsByAgent, listAllMetrics, countAllMetrics, countMetricsByAgent, updateMetric, deleteMetric, createMetricVersion, getMetricVersions, getMetricVersion, getPromptTemplates, getPromptTemplateById, upsertPromptTemplate, deletePromptTemplate, resetPromptTemplateToDefault, getPromptTemplateHistory, resolvePromptTemplate, checkoutPromptTemplate, getAllChannelActivityCursors, getChannelActivityCursor, upsertChannelActivityCursor, createApprovalRequest, getApprovalRequestById, resolveApprovalRequest, updateApprovalRequestNotifications, listApprovalRequests, getStuckApprovalRuns, getApprovalRequestByStepId, getExpiredPendingApprovals, createWaitState, getWaitStateById, getWaitStateByStepId, getDueWaitStates, getPendingEventWaitNames, getPendingWaitsByEvent, resolveWaitState, getStuckWaitRuns, SKILL_FILE_LIMITS, normalizeSkillFilePath, createSkill, updateSkill, listSkillFileManifest, getSkillFiles, getSkillFile, upsertSkillFile, upsertSkillFiles, deleteSkillFile, deleteSkill, getSkillById, getSkillByName, listSkills, searchSkills, installSkill, getSystemDefaultSkills, installSystemDefaultSkillsForAgent, uninstallSkill, getAgentSkills, toggleAgentSkill, createMcpServer, updateMcpServer, deleteMcpServer, getMcpServerById, getMcpServerByName, listMcpServers, installMcpServer, uninstallMcpServer, getAgentMcpServers, createContextSnapshot, getContextSnapshotsByTaskId, getContextSnapshotsBySessionId, getContextSummaryByTaskId, getAvailableKeyIndices, recordKeyUsage, markKeyRateLimited, recordKeyRateLimitWindows, setApiKeyName, clearKeyRateLimit, getKeyStatuses, getKeyCostSummary, getUserById, getAllUsers, createUser, updateUser, deleteUser, listInboxState, upsertInboxState, listFavorites, listUserFavorites, getFavoriteItemIdSet, setFavorite, setUserFavorite, withFavoriteFlags, listTaskTemplates, getRootTaskChain, listRecentSessions, countSessions, getBudget, getBudgets, upsertBudget, deleteBudget, getAllPricingRows, getPricingRows, getActivePricingRow, insertPricingRow, deletePricingRow, getDailySpendForAgent, getDailySpendGlobal, getDailySpendForUser, recordBudgetRefusalNotification, getBudgetRefusalNotification, getRecentBudgetRefusalNotifications, hasBudgetRefusalNotificationToday, setBudgetRefusalFollowUpTaskId, getLiveAgentCounts, getInstanceActivity, getSwarmMetrics, hasFirstCompletedTask, getKv, sweepExpiredKv, sweepExpiredKvPrefix, upsertKv, deleteKv, KvTypeCollisionError, incrKv, listKv, countKv, createScriptRun, recordInlineScriptRun, getScriptRun, getScriptRunByIdempotencyKey, listScriptRuns, countScriptRuns, countActiveScriptRuns, updateScriptRun, getRunningScriptRuns, getScriptRunJournalStep, upsertScriptRunJournalStep, listScriptRunJournalSteps, countScriptRunJournalSteps, countScriptRunJournalAgentTaskSteps, exports_db, init_db };