@desplega.ai/agent-swarm 1.113.0 → 1.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.md +2 -2
  2. package/dist/{actions-q4n7cz6e.js → actions-17ya5wde.js} +8 -9
  3. package/dist/{app-es4nzc71.js → app-4f718yk0.js} +6 -6
  4. package/dist/{assistant-0x8ey0vs.js → assistant-ah7csnjz.js} +19 -18
  5. package/dist/{boot-reembed-69agkhv6.js → boot-reembed-4jpxhb25.js} +6 -6
  6. package/dist/{boot-reembed-p0ny05t8.js → boot-reembed-qata34xa.js} +5 -5
  7. package/dist/{boot-scrub-logs-yybrkmvr.js → boot-scrub-logs-tv48nn3z.js} +4 -4
  8. package/dist/{claude-adapter-mma9a1yr.js → claude-adapter-3csn5bks.js} +3 -3
  9. package/dist/{claude-managed-adapter-pv2nbqy4.js → claude-managed-adapter-kysmkz89.js} +2 -2
  10. package/dist/cli-0pygq9r1.js +429 -0
  11. package/dist/{cli-hsetkkd3.js → cli-12vb0xg6.js} +33 -9
  12. package/dist/{cli-ncfgsqbd.js → cli-15y7qhzp.js} +262 -33
  13. package/dist/{cli-7ga43spr.js → cli-1yjrbg1f.js} +1 -1
  14. package/dist/{cli-36ymmpmp.js → cli-3samkyap.js} +2 -2
  15. package/dist/cli-52fg7s7x.js +269 -0
  16. package/dist/{cli-hjhvekf4.js → cli-65ekje01.js} +11 -8
  17. package/dist/{cli-h3k622d0.js → cli-6aq8xhvm.js} +90 -3
  18. package/dist/{cli-f3qa069v.js → cli-7xje5amz.js} +1 -1
  19. package/dist/cli-86fdnerz.js +405 -0
  20. package/dist/{cli-9cy6nc5m.js → cli-8fjwym53.js} +1 -1
  21. package/dist/{cli-c3frqf65.js → cli-b23axgz4.js} +3 -3
  22. package/dist/{cli-a0t7vapf.js → cli-bc89my0z.js} +1 -1
  23. package/dist/{cli-bnzbn8j8.js → cli-beea4a3y.js} +73 -24
  24. package/dist/{cli-q21d49ac.js → cli-bw80ck94.js} +1 -1
  25. package/dist/{cli-pwc5e83c.js → cli-cchksf5q.js} +12 -7
  26. package/dist/{cli-30bbaveh.js → cli-cmw9rzy5.js} +2 -2
  27. package/dist/{cli-y6mrptcn.js → cli-cnwssmsr.js} +1 -1
  28. package/dist/{cli-r5g6ngtn.js → cli-dcca6j8m.js} +46 -5
  29. package/dist/{cli-tkmm5nf9.js → cli-e61fs2hp.js} +59 -2
  30. package/dist/{cli-6wscj9z0.js → cli-e7306swv.js} +14 -14
  31. package/dist/{cli-dcfyyh3t.js → cli-ftyf58xj.js} +2 -2
  32. package/dist/{cli-4xyj9jtq.js → cli-hrhye2rm.js} +1062 -478
  33. package/dist/cli-jkhwmmgg.js +136 -0
  34. package/dist/{cli-y4ycrnjc.js → cli-k3y4z3h5.js} +1 -1
  35. package/dist/{cli-6xd0bvf8.js → cli-ma04faw5.js} +1 -1
  36. package/dist/{cli-2fc97xm5.js → cli-mnbgv3w7.js} +4 -4
  37. package/dist/{cli-trmapn9k.js → cli-pet3aev6.js} +95 -10
  38. package/dist/{cli-z46pnksz.js → cli-q1rx7g0d.js} +175 -28
  39. package/dist/{cli-qwgtacd6.js → cli-r9f6ngrf.js} +1244 -336
  40. package/dist/{cli-gtkqc144.js → cli-shvaxw27.js} +13 -7
  41. package/dist/{cli-ywez6yps.js → cli-sq7f72d6.js} +1 -1
  42. package/dist/cli-t0vqevnm.js +393 -0
  43. package/dist/{cli-tbw13sx8.js → cli-tece6zgm.js} +1 -1
  44. package/dist/{cli-bgvskydy.js → cli-tffvrh6j.js} +1 -1
  45. package/dist/cli-wh91zby6.js +187222 -0
  46. package/dist/{cli-anrj584m.js → cli-xz9aq0rf.js} +1 -1
  47. package/dist/{cli-mq580e06.js → cli-zsrdty74.js} +18 -18
  48. package/dist/cli.js +32 -15
  49. package/dist/{codex-adapter-5cmy858w.js → codex-adapter-de3w0nch.js} +10 -10
  50. package/dist/{codex-session-runner-46q8mrba.js → codex-session-runner-bnw8cysk.js} +10 -10
  51. package/dist/{commands-z5dbwta3.js → commands-hch4e2k1.js} +4 -4
  52. package/dist/{db-bbgahh4z.js → db-p3h2j06x.js} +14 -4
  53. package/dist/{handlers-6b44317z.js → handlers-9er4zx9q.js} +17 -31
  54. package/dist/{hook-sbp5fmps.js → hook-4axs756z.js} +7 -7
  55. package/dist/{http-2xz43gz3.js → http-809fvtz2.js} +1934 -886
  56. package/dist/{index-wz1ea15p.js → index-2dgfj9av.js} +3 -3
  57. package/dist/{index-nhat35em.js → index-47em3d2n.js} +14 -11
  58. package/dist/{index-5ghxn8s6.js → index-9fqaktjr.js} +12 -9
  59. package/dist/{index-0gzmqj4k.js → index-9ht8gr56.js} +13 -10
  60. package/dist/{index-vfedgdw6.js → index-rm85cfdx.js} +368 -40
  61. package/dist/{index-ykvs43z4.js → index-t2snazez.js} +4 -4
  62. package/dist/{keepalive-62gfj91d.js → keepalive-3cps6e3e.js} +7 -6
  63. package/dist/{lead-ag0akn0v.js → lead-fkk95wgq.js} +36 -32
  64. package/dist/{maintenance-xxrrzk5x.js → maintenance-fweqh0yj.js} +6 -6
  65. package/dist/{mistral-conversations-26yrnbf1.js → mistral-conversations-7gqnz2wt.js} +7 -7
  66. package/dist/oauth-refresh-sweep-sycqtbph.js +114 -0
  67. package/dist/{onboard-64zyfcbs.js → onboard-cy0rkgvx.js} +2 -2
  68. package/dist/{opencode-adapter-mqsxr170.js → opencode-adapter-p6bxnbm4.js} +2 -2
  69. package/dist/{otel-zjd9zaxs.js → otel-g299k41b.js} +2 -2
  70. package/dist/{otel-impl-b86qseaa.js → otel-impl-wbns8hf7.js} +1 -1
  71. package/dist/{pi-mono-adapter-kxjxpfgy.js → pi-mono-adapter-05sck1ds.js} +17 -109
  72. package/dist/{pricing-refresh-cgtkffpa.js → pricing-refresh-0hvazmkf.js} +6 -6
  73. package/dist/rbac-roles-kfesjy9y.js +28 -0
  74. package/dist/rbac-roles-mwcwhbxc.js +283 -0
  75. package/dist/{seed-pricing-1r1y1xkq.js → seed-pricing-h2kdq4cq.js} +5 -5
  76. package/dist/{setup-mkcgkjf7.js → setup-8506q97w.js} +2 -2
  77. package/dist/{worker-351sze63.js → worker-4r5c6zyb.js} +36 -32
  78. package/openapi.json +1327 -20
  79. package/package.json +3 -3
  80. package/src/agentmail/handlers.ts +16 -6
  81. package/src/agentmail/templates.ts +25 -5
  82. package/src/be/audit-user.ts +28 -4
  83. package/src/be/db-queries/oauth.ts +42 -0
  84. package/src/be/db.ts +314 -28
  85. package/src/be/identity.ts +79 -0
  86. package/src/be/mcp-proxy.ts +132 -0
  87. package/src/be/migrations/109_rbac_roles.sql +79 -0
  88. package/src/be/migrations/111_oauth_credential_bindings.sql +6 -0
  89. package/src/be/migrations/112_script_connections_graphql.sql +96 -0
  90. package/src/be/migrations/113_task_routing_affinity.sql +9 -0
  91. package/src/be/migrations/114_backfill_gpt_5_6_pricing.sql +15 -0
  92. package/src/be/modelsdev-cache.json +135 -0
  93. package/src/be/oauth-credential-bindings.ts +35 -0
  94. package/src/be/oauth-refresh-sweep.ts +159 -0
  95. package/src/be/rbac-audit.ts +52 -13
  96. package/src/be/rbac-roles.ts +424 -0
  97. package/src/be/script-connections.ts +459 -40
  98. package/src/be/script-credential-broker.ts +29 -3
  99. package/src/be/scripts/typecheck.ts +51 -7
  100. package/src/be/seed-scripts/catalog/catalog-report.inline.ts +325 -24
  101. package/src/be/seed-scripts/catalog/catalog-report.ts +325 -24
  102. package/src/be/users.ts +24 -0
  103. package/src/cli.tsx +17 -0
  104. package/src/github/handlers.ts +10 -9
  105. package/src/github/templates.ts +45 -9
  106. package/src/gitlab/handlers.ts +20 -8
  107. package/src/gitlab/templates.ts +18 -6
  108. package/src/heartbeat/heartbeat.ts +143 -21
  109. package/src/http/all-routes.ts +3 -0
  110. package/src/http/approval-requests.ts +12 -0
  111. package/src/http/config.ts +44 -10
  112. package/src/http/core.ts +30 -3
  113. package/src/http/favorites.ts +1 -5
  114. package/src/http/index.ts +25 -1
  115. package/src/http/mcp-oauth.ts +2 -0
  116. package/src/http/mcp-servers.ts +44 -3
  117. package/src/http/oauth-generic.ts +105 -0
  118. package/src/http/poll.ts +20 -3
  119. package/src/http/script-connection-proxy.ts +116 -0
  120. package/src/http/script-connections.ts +1657 -0
  121. package/src/http/scripts.ts +27 -7
  122. package/src/http/skills.ts +11 -0
  123. package/src/http/tasks.ts +27 -13
  124. package/src/http/x.ts +6 -2
  125. package/src/integrations/kapso/inbound.ts +23 -6
  126. package/src/jira/sync.ts +111 -17
  127. package/src/jira/templates.ts +10 -2
  128. package/src/mcp-client/http-client.ts +194 -0
  129. package/src/oauth/app-validation.ts +16 -0
  130. package/src/oauth/ensure-token.ts +69 -14
  131. package/src/oauth/mcp-wrapper.ts +15 -0
  132. package/src/oauth/wrapper.ts +48 -20
  133. package/src/prompts/session-templates.ts +3 -3
  134. package/src/providers/codex-models.ts +100 -30
  135. package/src/providers/modelsdev-reasoning.json +51 -0
  136. package/src/providers/pi-mono-mcp-client.ts +2 -133
  137. package/src/providers/reasoning-effort.ts +11 -5
  138. package/src/rbac/admission.ts +68 -0
  139. package/src/rbac/index.ts +2 -0
  140. package/src/rbac/legacy-policy.ts +12 -0
  141. package/src/rbac/permissions.ts +48 -0
  142. package/src/scheduler/scheduler.ts +9 -1
  143. package/src/scripts-runtime/api-client.ts +151 -19
  144. package/src/scripts-runtime/api-types.ts +38 -6
  145. package/src/scripts-runtime/credential-broker/default-bindings.ts +1 -0
  146. package/src/scripts-runtime/credential-broker/types.ts +8 -0
  147. package/src/scripts-runtime/ctx.ts +11 -1
  148. package/src/scripts-runtime/eval-harness.ts +5 -1
  149. package/src/scripts-runtime/executors/types.ts +2 -1
  150. package/src/scripts-runtime/loader.ts +3 -1
  151. package/src/scripts-runtime/mcp-client.ts +87 -0
  152. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  153. package/src/scripts-runtime/types/stdlib.d.ts +6 -0
  154. package/src/scripts-runtime/types/swarm-sdk.d.ts +19 -0
  155. package/src/server-user.ts +114 -59
  156. package/src/server.ts +12 -0
  157. package/src/slack/assistant.ts +14 -6
  158. package/src/slack/enrich.ts +17 -0
  159. package/src/slack/handlers.ts +8 -22
  160. package/src/slack/responses.ts +91 -1
  161. package/src/slack/thread-buffer.ts +6 -3
  162. package/src/slack/watcher.ts +9 -6
  163. package/src/tasks/worker-follow-up.ts +100 -3
  164. package/src/tests/agentmail-handlers.test.ts +32 -3
  165. package/src/tests/approval-requests.test.ts +61 -0
  166. package/src/tests/audit-user.test.ts +47 -1
  167. package/src/tests/codex-adapter.test.ts +46 -23
  168. package/src/tests/credential-broker.test.ts +5 -2
  169. package/src/tests/delete-page-tool.test.ts +197 -0
  170. package/src/tests/github-handlers.test.ts +28 -2
  171. package/src/tests/gitlab-handlers.test.ts +125 -0
  172. package/src/tests/heartbeat.test.ts +48 -3
  173. package/src/tests/identity.test.ts +117 -0
  174. package/src/tests/jira-sync.test.ts +99 -1
  175. package/src/tests/kapso-inbound.test.ts +7 -0
  176. package/src/tests/mcp-tools-user.test.ts +60 -6
  177. package/src/tests/model-control.test.ts +8 -2
  178. package/src/tests/oauth-credential-bindings.test.ts +490 -0
  179. package/src/tests/oauth-refresh-sweep.test.ts +160 -0
  180. package/src/tests/pool-affinity.test.ts +401 -0
  181. package/src/tests/prompt-template-remaining.test.ts +2 -2
  182. package/src/tests/rbac-admission-e2e.test.ts +386 -0
  183. package/src/tests/rbac-admission.test.ts +492 -0
  184. package/src/tests/rbac-e2e-helpers.ts +3 -0
  185. package/src/tests/rbac-engine.test.ts +50 -0
  186. package/src/tests/rbac-mcp-admission-e2e.test.ts +362 -0
  187. package/src/tests/rbac-roles.test.ts +328 -0
  188. package/src/tests/reasoning-effort.test.ts +15 -2
  189. package/src/tests/schedule-target-type.test.ts +50 -0
  190. package/src/tests/scheduled-tasks.test.ts +40 -0
  191. package/src/tests/script-apis-mcp.test.ts +37 -13
  192. package/src/tests/script-connections-http.test.ts +1158 -0
  193. package/src/tests/script-connections-mcp.test.ts +894 -0
  194. package/src/tests/script-connections.test.ts +754 -6
  195. package/src/tests/scripts-external-api.test.ts +49 -1
  196. package/src/tests/scripts-runtime-secret-egress.test.ts +1 -0
  197. package/src/tests/scripts-runtime.test.ts +291 -0
  198. package/src/tests/seed-scripts.test.ts +36 -0
  199. package/src/tests/slack-identity-resolution.test.ts +37 -3
  200. package/src/tests/slack-inline-output.test.ts +65 -0
  201. package/src/tests/slack-thread-buffer.test.ts +28 -0
  202. package/src/tests/tool-annotations.test.ts +1 -0
  203. package/src/tests/user-token-rest-auth.test.ts +140 -1
  204. package/src/tests/workflow-swarm-script.test.ts +44 -0
  205. package/src/tests/workflow-triggers-v2.test.ts +300 -1
  206. package/src/tools/credential-bindings/tool.ts +277 -18
  207. package/src/tools/delete-page.ts +145 -0
  208. package/src/tools/mcp-servers/mcp-server-delete.ts +7 -4
  209. package/src/tools/request-human-input.ts +2 -0
  210. package/src/tools/resolve-user.ts +77 -27
  211. package/src/tools/script-apis.ts +62 -3
  212. package/src/tools/script-connections/tool.ts +275 -31
  213. package/src/tools/send-task.ts +15 -1
  214. package/src/tools/task-action.ts +34 -2
  215. package/src/tools/templates.ts +53 -1
  216. package/src/tools/tool-config.ts +2 -1
  217. package/src/tools/utils.ts +2 -0
  218. package/src/tools/workflows/create-workflow.ts +8 -1
  219. package/src/tools/workflows/update-workflow.ts +11 -2
  220. package/src/types.ts +90 -11
  221. package/src/utils/scoped-resource.ts +25 -0
  222. package/src/workflows/executors/human-in-the-loop.ts +1 -0
  223. package/src/workflows/executors/swarm-script.ts +7 -1
  224. package/src/workflows/triggers.ts +146 -18
  225. package/templates/skills/swarm-scripts/content.md +33 -8
  226. package/dist/cli-bgef578c.js +0 -771
  227. package/dist/cli-c9mtm09b.js +0 -43
  228. package/dist/cli-ceewqajw.js +0 -1698
  229. package/dist/{anthropic-messages-8nc6r2dw.js → anthropic-messages-kq3pjhbp.js} +6 -6
  230. package/dist/{azure-openai-responses-6yfzw3qw.js → azure-openai-responses-gm1ejtmn.js} +7 -7
  231. package/dist/{cli-vbraamxr.js → cli-6b4wwmm8.js} +9 -9
  232. package/dist/{cli-2r7s8jhp.js → cli-sznberje.js} +3 -3
  233. package/dist/{google-generative-ai-vfq6ymz9.js → google-generative-ai-hyrra2jm.js} +3 -3
  234. package/dist/{google-vertex-mj5y5rfj.js → google-vertex-8bs2pzgn.js} +3 -3
  235. package/dist/{openai-codex-responses-8h6kvfv8.js → openai-codex-responses-3nkvje79.js} +4 -4
  236. package/dist/{openai-completions-x6kjnqjd.js → openai-completions-0asftkwg.js} +11 -11
  237. package/dist/{openai-responses-7jwyz3ds.js → openai-responses-pmatek45.js} +10 -10
@@ -4,8 +4,9 @@ import {
4
4
  } from "./cli-z2zcxes1.js";
5
5
  import {
6
6
  init_zod
7
- } from "./cli-q21d49ac.js";
7
+ } from "./cli-bw80ck94.js";
8
8
  import {
9
+ ZodIssueCode,
9
10
  _enum,
10
11
  _null,
11
12
  array,
@@ -21,11 +22,11 @@ import {
21
22
  union,
22
23
  unknown,
23
24
  uuid
24
- } from "./cli-anrj584m.js";
25
+ } from "./cli-xz9aq0rf.js";
25
26
  import {
26
27
  init_package,
27
28
  package_default
28
- } from "./cli-c3frqf65.js";
29
+ } from "./cli-b23axgz4.js";
29
30
  import {
30
31
  init_secret_scrubber,
31
32
  scrubSecrets
@@ -469,12 +470,12 @@ function resolveTaskModelSelection(opts) {
469
470
  function isTerminalTaskStatus(status) {
470
471
  return TERMINAL_TASK_STATUSES.includes(status);
471
472
  }
472
- var ModelTierSchema, MODEL_TIERS, ReasoningEffortSchema, LEGACY_MODEL_TO_TIER, DEFAULT_MODEL_TIER_MAP, AgentTaskStatusSchema, TERMINAL_TASK_STATUSES, InboxMessageStatusSchema, InboxMessageSchema, AgentTaskSourceSchema, ProviderNameSchema, FollowUpConfigSchema, AgentTaskSchema, TaskAttachmentKindSchema, attachmentCommonFields, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, IdentityEventTypeSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentSchema, AgentCredStatusLiveTestSchema, AgentLatestModelSchema, AgentBedrockStatusSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChangeSourceSchema, VersionableFieldSchema, ContextVersionSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, AgentLogEventTypeSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostSourceSchema, 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, 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;
473
+ var ModelTierSchema, MODEL_TIERS, ReasoningEffortSchema, LEGACY_MODEL_TO_TIER, DEFAULT_MODEL_TIER_MAP, AgentTaskStatusSchema, TERMINAL_TASK_STATUSES, InboxMessageStatusSchema, InboxMessageSchema, AgentTaskSourceSchema, ProviderNameSchema, FollowUpConfigSchema, RoutingAffinitySchema, AgentTaskSchema, TaskAttachmentKindSchema, attachmentCommonFields, AttachmentInputSchema, TaskAttachmentSchema, UserSchema, IdentityEventTypeSchema, InboxItemTypeSchema, InboxItemStatusSchema, InboxItemStateSchema, FavoriteItemTypeSchema, UserFavoriteSchema, TaskTemplateKindSchema, TaskTemplateSchema, AgentStatusSchema, AgentSchema, AgentCredStatusLiveTestSchema, AgentLatestModelSchema, AgentBedrockStatusSchema, AgentCredStatusSchema, AgentWithTasksSchema, ChangeSourceSchema, VersionableFieldSchema, ContextVersionSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, AgentLogEventTypeSchema, ResumeReasonSchema, AgentLogSchema, SessionLogSchema, SessionCostSourceSchema, 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;
473
474
  var init_types = __esm(() => {
474
475
  init_zod();
475
476
  ModelTierSchema = _enum(["smol", "regular", "smart", "ultra"]);
476
477
  MODEL_TIERS = ModelTierSchema.options;
477
- ReasoningEffortSchema = _enum(["off", "low", "medium", "high", "xhigh"]);
478
+ ReasoningEffortSchema = _enum(["off", "low", "medium", "high", "xhigh", "max"]);
478
479
  LEGACY_MODEL_TO_TIER = {
479
480
  haiku: "smol",
480
481
  sonnet: "regular",
@@ -495,10 +496,10 @@ var init_types = __esm(() => {
495
496
  ultra: "claude-fable-5"
496
497
  },
497
498
  codex: {
498
- smol: "gpt-5.4-mini",
499
- regular: "gpt-5.4",
500
- smart: "gpt-5.5",
501
- ultra: "gpt-5.5"
499
+ smol: "gpt-5.6-luna",
500
+ regular: "gpt-5.6-terra",
501
+ smart: "gpt-5.6-sol",
502
+ ultra: "gpt-5.6-sol"
502
503
  },
503
504
  pi: {
504
505
  smol: "openrouter/deepseek/deepseek-v4-flash",
@@ -582,6 +583,12 @@ var init_types = __esm(() => {
582
583
  onCompleted: string().max(4000).optional(),
583
584
  onFailed: string().max(4000).optional()
584
585
  });
586
+ RoutingAffinitySchema = object({
587
+ sourceAgentId: uuid().optional(),
588
+ role: string().max(100).optional(),
589
+ harnessProvider: ProviderNameSchema.optional(),
590
+ capabilities: array(string()).default([])
591
+ });
585
592
  AgentTaskSchema = object({
586
593
  id: uuid(),
587
594
  agentId: uuid().nullable(),
@@ -649,7 +656,8 @@ var init_types = __esm(() => {
649
656
  providerMeta: record(string(), unknown()).optional(),
650
657
  harnessVariant: string().optional(),
651
658
  harnessVariantMeta: record(string(), unknown()).optional(),
652
- totalCostUsd: number().min(0).optional()
659
+ totalCostUsd: number().min(0).optional(),
660
+ routingAffinity: RoutingAffinitySchema.optional()
653
661
  });
654
662
  TaskAttachmentKindSchema = _enum(["agent-fs", "url", "shared-fs", "page"]);
655
663
  attachmentCommonFields = {
@@ -921,6 +929,7 @@ var init_types = __esm(() => {
921
929
  "task_accepted",
922
930
  "task_rejected",
923
931
  "task_claimed",
932
+ "task_claim_rejected_affinity",
924
933
  "task_released",
925
934
  "channel_message",
926
935
  "service_registered",
@@ -1224,17 +1233,43 @@ var init_types = __esm(() => {
1224
1233
  onNodeFailure: _enum(["fail", "continue"]).optional().describe("Update the definition-level onNodeFailure behavior"),
1225
1234
  triggerSchema: record(string(), unknown()).optional().nullable().describe("Optional JSON-Schema describing the expected trigger payload shape. " + "Pass an object to set/replace; pass null to clear; omit to leave unchanged. " + "Validator subset: type, required, properties, enum, const, items. " + "Other JSON-Schema keywords are silently ignored.")
1226
1235
  });
1236
+ WebhookVerificationSchema = discriminatedUnion("format", [
1237
+ object({
1238
+ format: literal("hmac-sha256"),
1239
+ header: string().default("X-Hub-Signature-256").describe("Header containing HMAC-SHA256 over the raw request body. Accepts sha256=<hex> or bare hex.")
1240
+ }),
1241
+ object({
1242
+ format: literal("timestamped-hmac-sha256"),
1243
+ header: string().min(1).describe("Header containing comma-separated timestamp/signature pairs such as t=<timestamp>,v1=<hex>."),
1244
+ timestampKey: string().default("t").describe("Timestamp field key in the signature header"),
1245
+ signatureKey: string().default("v1").describe("Signature field key in the signature header; multiple entries are allowed"),
1246
+ toleranceSeconds: number().int().positive().default(300).describe("Maximum allowed clock skew, in seconds, for replay protection")
1247
+ }),
1248
+ object({
1249
+ format: literal("token-equality"),
1250
+ header: string().min(1).describe("Header containing the shared token to compare")
1251
+ })
1252
+ ]);
1227
1253
  TriggerConfigSchema = discriminatedUnion("type", [
1228
1254
  object({
1229
1255
  type: literal("webhook"),
1230
1256
  hmacSecret: string().optional(),
1231
- hmacHeader: string().default("X-Hub-Signature-256")
1257
+ hmacHeader: string().default("X-Hub-Signature-256").describe("Legacy HMAC header for webhook verification. Prefer verification.header for new workflows."),
1258
+ verification: WebhookVerificationSchema.optional().describe("Optional webhook verification format. Omit to keep legacy HMAC-SHA256 behavior with fallback header scanning.")
1232
1259
  }),
1233
1260
  object({
1234
1261
  type: literal("schedule"),
1235
1262
  scheduleId: string().uuid()
1236
1263
  })
1237
- ]);
1264
+ ]).superRefine((trigger, ctx) => {
1265
+ if (trigger.type === "webhook" && trigger.verification && !trigger.hmacSecret) {
1266
+ ctx.addIssue({
1267
+ code: ZodIssueCode.custom,
1268
+ message: "hmacSecret is required when verification is configured",
1269
+ path: ["hmacSecret"]
1270
+ });
1271
+ }
1272
+ });
1238
1273
  CooldownConfigSchema = object({
1239
1274
  hours: number().min(0).optional(),
1240
1275
  minutes: number().min(0).optional(),
@@ -2532,9 +2567,9 @@ The 5 script tools (\`script-search\`, \`script-run\`, \`script-upsert\`, \`scri
2532
2567
  - \`agentId\` IS propagated to scripts via the \`X-Agent-ID\` header.
2533
2568
  - \`taskId\` is NOT propagated to scripts — there is no ambient task context. Pass \`taskId\` explicitly via \`args\` if the script needs to call \`ctx.swarm.task_storeProgress\`.
2534
2569
  - Use \`script-query-types\` to inspect the live \`swarm-sdk.d.ts\` before authoring a complex script.
2535
- - Typed API connections: a lead-registered \`script_connections\` entry exposes a typed \`ctx.api.<slug>.<method>(...)\` client in scripts.
2536
- - \`ctx.api\` clients auto-inject the configured credential at egress, so scripts calling an allow-listed external API should prefer \`ctx.api\` over hand-written \`[REDACTED:<KEY>]\` Authorization headers.
2537
- - Registration is lead-only; workers should document the connection spec and hand it to the lead to register.
2570
+ - Script connections: lead-registered \`script_connections\` entries expose typed clients in scripts — \`ctx.api.<slug>.<operationId>(...)\` (OpenAPI), \`ctx.api.<slug>.graphql(query, vars)\` (GraphQL), and \`ctx.mcp.<slug>.<toolName>(args)\` (MCP, proxied server-side). Introspect with \`Object.keys(ctx.api ?? {})\` / \`Object.keys(ctx.mcp ?? {})\`.
2571
+ - Connection credentials (config secrets or OAuth tokens with auto-refresh) are injected at egress, so scripts calling an external API should prefer a connection over hand-written \`fetch\` + \`[REDACTED:<KEY>]\` headers — and never paste raw secrets.
2572
+ - Registration is lead-only (\`script-connections\` + \`credential-bindings\` tools); workers should hand the lead the spec to register: slug, baseUrl or spec URL, allowedHosts, and auth (config key vs OAuth provider).
2538
2573
  `,
2539
2574
  variables: [],
2540
2575
  category: "system"
@@ -3008,7 +3043,10 @@ A Kapso webhook fired on the swarm's provisioned WhatsApp number. Load the \`kap
3008
3043
  { name: "conversation_id", description: "Kapso conversation id, or 'unknown'" },
3009
3044
  { name: "inbound_wamid", description: "Inbound message WAMID, or 'unknown'" },
3010
3045
  { name: "sender_phone", description: "Sender phone (E.164 no +), or 'unknown'" },
3011
- { name: "contact_name", description: "Contact display name, or 'unknown'" },
3046
+ {
3047
+ name: "contact_name",
3048
+ description: "Sender identity — resolved canonical name (e.g. 'Luis (kapso:15551234567)') or the UNKNOWN sentinel — never the raw WhatsApp profile name"
3049
+ },
3012
3050
  { name: "phone_number_id", description: "Provisioned phone-number id, or 'unknown'" },
3013
3051
  {
3014
3052
  name: "test_note",
@@ -3168,6 +3206,41 @@ This work will NOT fall back to the unassigned pool — you are the only re-dele
3168
3206
  ],
3169
3207
  category: "task_lifecycle"
3170
3208
  });
3209
+ registerTemplate({
3210
+ eventType: "task.pool.starved.decision",
3211
+ header: "",
3212
+ defaultBody: `Reroute decision: a pooled task has no eligible worker.
3213
+
3214
+ Original task ID: {{original_task_id}}
3215
+ Task: "{{task_desc}}"
3216
+ Required role: {{required_role}}
3217
+ Required capabilities: {{required_capabilities}}{{artifacts_block}}
3218
+
3219
+ ## Your job
3220
+
3221
+ This task has been sitting unassigned because no currently-registered agent matches its required role/capabilities. Pick an agent to take this work over and RE-DELEGATE it — do NOT execute it yourself.
3222
+
3223
+ Dispatch via \`send-task\` with an explicit \`agentId\` (REQUIRED — omitting it re-pools the work under the same affinity tag and it will starve again) and \`parentTaskId: {{original_task_id}}\`.
3224
+
3225
+ This work will NOT fall back to the unassigned pool — you are the only re-delegation path.`,
3226
+ variables: [
3227
+ { name: "original_task_id", description: "ID of the starved pool task" },
3228
+ { name: "task_desc", description: "Original task description (truncated to 200 chars)" },
3229
+ {
3230
+ name: "required_role",
3231
+ description: "Role declared on the task's routingAffinity, or a placeholder"
3232
+ },
3233
+ {
3234
+ name: "required_capabilities",
3235
+ description: "Comma-joined capabilities declared on the task's routingAffinity, or a placeholder"
3236
+ },
3237
+ {
3238
+ name: "artifacts_block",
3239
+ description: "Formatted attachment list from the original task, or empty string"
3240
+ }
3241
+ ],
3242
+ category: "task_lifecycle"
3243
+ });
3171
3244
  });
3172
3245
 
3173
3246
  // src/be/seed-prompt-templates.ts
@@ -3600,6 +3673,8 @@ __export(exports_db, {
3600
3673
  listAllMetrics: () => listAllMetrics,
3601
3674
  listAgentsWithCredStatusByProvider: () => listAgentsWithCredStatusByProvider,
3602
3675
  isSqliteVecAvailable: () => isSqliteVecAvailable,
3676
+ isPoolAffinityEnforcementEnabled: () => isPoolAffinityEnforcementEnabled,
3677
+ isAgentEligibleForTask: () => isAgentEligibleForTask,
3603
3678
  installSystemDefaultSkillsForAgent: () => installSystemDefaultSkillsForAgent,
3604
3679
  installSkill: () => installSkill,
3605
3680
  installMcpServer: () => installMcpServer,
@@ -3629,6 +3704,7 @@ __export(exports_db, {
3629
3704
  getUnreadMessages: () => getUnreadMessages,
3630
3705
  getUnreadInboxMessages: () => getUnreadInboxMessages,
3631
3706
  getUnassignedTasksCount: () => getUnassignedTasksCount,
3707
+ getUnassignedTaskIdsForAgent: () => getUnassignedTaskIdsForAgent,
3632
3708
  getUnassignedTaskIds: () => getUnassignedTaskIds,
3633
3709
  getUnassignedPoolTasks: () => getUnassignedPoolTasks,
3634
3710
  getTasksCount: () => getTasksCount,
@@ -3653,6 +3729,7 @@ __export(exports_db, {
3653
3729
  getStepCountForNode: () => getStepCountForNode,
3654
3730
  getStepByIdempotencyKey: () => getStepByIdempotencyKey,
3655
3731
  getStalledInProgressTasks: () => getStalledInProgressTasks,
3732
+ getStaleUnassignedAffinityTasks: () => getStaleUnassignedAffinityTasks,
3656
3733
  getStalePinnedResumes: () => getStalePinnedResumes,
3657
3734
  getSkillFiles: () => getSkillFiles,
3658
3735
  getSkillFile: () => getSkillFile,
@@ -3873,6 +3950,7 @@ __export(exports_db, {
3873
3950
  checkDependencies: () => checkDependencies,
3874
3951
  cascadeFailDependents: () => cascadeFailDependents,
3875
3952
  cancelTask: () => cancelTask,
3953
+ buildRoutingAffinityFromAgent: () => buildRoutingAffinityFromAgent,
3876
3954
  backfillSupersedeTaskResumeTaskId: () => backfillSupersedeTaskResumeTaskId,
3877
3955
  autoEncryptLegacyPlaintextSecrets: () => autoEncryptLegacyPlaintextSecrets,
3878
3956
  assignUnassignedTaskPending: () => assignUnassignedTaskPending,
@@ -4326,6 +4404,40 @@ function updateAgentStatusFromCapacity(agentId) {
4326
4404
  updateAgentStatus(agentId, newStatus);
4327
4405
  }
4328
4406
  }
4407
+ function isPoolAffinityEnforcementEnabled() {
4408
+ return process.env.POOL_AFFINITY_ENFORCEMENT !== "0";
4409
+ }
4410
+ function buildRoutingAffinityFromAgent(agentId) {
4411
+ const agent = getAgentById(agentId);
4412
+ if (!agent)
4413
+ return null;
4414
+ return {
4415
+ sourceAgentId: agent.id,
4416
+ role: agent.role,
4417
+ harnessProvider: agent.harnessProvider ?? agent.provider ?? undefined,
4418
+ capabilities: agent.capabilities ?? []
4419
+ };
4420
+ }
4421
+ function isAgentEligibleForTask(agent, task) {
4422
+ if (!isPoolAffinityEnforcementEnabled())
4423
+ return true;
4424
+ const affinity = task.routingAffinity;
4425
+ if (!affinity)
4426
+ return true;
4427
+ if (affinity.sourceAgentId && affinity.sourceAgentId === agent.id)
4428
+ return true;
4429
+ if (!agent.role || !affinity.role)
4430
+ return false;
4431
+ if (agent.role !== affinity.role)
4432
+ return false;
4433
+ const requiredCapabilities = affinity.capabilities ?? [];
4434
+ if (requiredCapabilities.length > 0) {
4435
+ const agentCapabilities = new Set(agent.capabilities ?? []);
4436
+ if (!requiredCapabilities.every((cap) => agentCapabilities.has(cap)))
4437
+ return false;
4438
+ }
4439
+ return true;
4440
+ }
4329
4441
  function rowToAgentTask(row) {
4330
4442
  let followUpConfig;
4331
4443
  if (row.followUpConfig) {
@@ -4341,6 +4453,19 @@ function rowToAgentTask(row) {
4341
4453
  followUpConfig = undefined;
4342
4454
  }
4343
4455
  }
4456
+ let routingAffinity;
4457
+ if (row.routingAffinity) {
4458
+ try {
4459
+ const parsed = RoutingAffinitySchema.safeParse(JSON.parse(row.routingAffinity));
4460
+ if (parsed.success) {
4461
+ routingAffinity = parsed.data;
4462
+ } else {
4463
+ console.warn(`[db] Ignoring invalid agent_tasks.routingAffinity for task ${row.id}:`, parsed.error.message);
4464
+ }
4465
+ } catch (error) {
4466
+ console.warn(`[db] Ignoring malformed agent_tasks.routingAffinity for task ${row.id}:`, error instanceof Error ? error.message : String(error));
4467
+ }
4468
+ }
4344
4469
  return {
4345
4470
  id: row.id,
4346
4471
  agentId: row.agentId,
@@ -4408,7 +4533,8 @@ function rowToAgentTask(row) {
4408
4533
  providerMeta: parseProviderMeta(row.provider, row.providerMeta),
4409
4534
  harnessVariant: row.harnessVariant ?? undefined,
4410
4535
  harnessVariantMeta: row.harnessVariantMeta ? JSON.parse(row.harnessVariantMeta) : undefined,
4411
- totalCostUsd: row.totalCostUsd ?? undefined
4536
+ totalCostUsd: row.totalCostUsd ?? undefined,
4537
+ routingAffinity
4412
4538
  };
4413
4539
  }
4414
4540
  function rowToAgentTaskSummary(row) {
@@ -4470,6 +4596,24 @@ function getPendingTaskForAgent(agentId) {
4470
4596
  return null;
4471
4597
  }
4472
4598
  function assignUnassignedTaskPending(taskId, agentId) {
4599
+ if (isPoolAffinityEnforcementEnabled()) {
4600
+ const task = getTaskById(taskId);
4601
+ const agent = getAgentById(agentId);
4602
+ if (task && agent && !isAgentEligibleForTask(agent, task)) {
4603
+ try {
4604
+ createLogEntry({
4605
+ eventType: "task_claim_rejected_affinity",
4606
+ agentId,
4607
+ taskId,
4608
+ metadata: {
4609
+ agentRole: agent.role ?? null,
4610
+ requiredRole: task.routingAffinity?.role ?? null
4611
+ }
4612
+ });
4613
+ } catch {}
4614
+ return null;
4615
+ }
4616
+ }
4473
4617
  const now = new Date().toISOString();
4474
4618
  const row = getDb().prepare(`UPDATE agent_tasks SET agentId = ?, status = 'pending', lastUpdatedAt = ?
4475
4619
  WHERE id = ? AND status = 'unassigned' RETURNING *`).get(agentId, now, taskId);
@@ -4665,6 +4809,10 @@ function getAllTasks(filters, opts) {
4665
4809
  conditions.push("createdAt >= ?");
4666
4810
  params.push(filters.createdAfter);
4667
4811
  }
4812
+ if (filters?.createdBefore) {
4813
+ conditions.push("createdAt < ?");
4814
+ params.push(filters.createdBefore);
4815
+ }
4668
4816
  if (filters?.requestedByUserId) {
4669
4817
  conditions.push("requestedByUserId = ?");
4670
4818
  params.push(filters.requestedByUserId);
@@ -4675,10 +4823,11 @@ function getAllTasks(filters, opts) {
4675
4823
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4676
4824
  const limit = filters?.limit ?? 25;
4677
4825
  const offset = filters?.offset ?? 0;
4826
+ const orderBy = filters?.orderBy === "createdAt" ? "createdAt DESC, rowid DESC" : "lastUpdatedAt DESC, priority DESC";
4678
4827
  const query = `SELECT agent_tasks.*,
4679
4828
  (SELECT SUM(totalCostUsd) FROM session_costs WHERE session_costs.taskId = agent_tasks.id) AS totalCostUsd
4680
4829
  FROM agent_tasks ${whereClause}
4681
- ORDER BY lastUpdatedAt DESC, priority DESC LIMIT ${limit} OFFSET ${offset}`;
4830
+ ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}`;
4682
4831
  const rows = getDb().prepare(query).all(...params);
4683
4832
  const isReady = (task) => {
4684
4833
  if (!task.dependsOn || task.dependsOn.length === 0)
@@ -4755,6 +4904,14 @@ function getTasksCount(filters) {
4755
4904
  conditions.push("createdAt >= ?");
4756
4905
  params.push(filters.createdAfter);
4757
4906
  }
4907
+ if (filters?.createdBefore) {
4908
+ conditions.push("createdAt < ?");
4909
+ params.push(filters.createdBefore);
4910
+ }
4911
+ if (filters?.requestedByUserId) {
4912
+ conditions.push("requestedByUserId = ?");
4913
+ params.push(filters.requestedByUserId);
4914
+ }
4758
4915
  if (!filters?.includeHeartbeat) {
4759
4916
  conditions.push(`(IFNULL(taskType, '') NOT IN ('heartbeat', 'heartbeat-checklist', 'boot-triage') AND tags NOT LIKE '%"heartbeat"%')`);
4760
4917
  }
@@ -5548,6 +5705,9 @@ function createTaskExtended(task, options) {
5548
5705
  if (parent.followUpConfig && !options.followUpConfig) {
5549
5706
  options.followUpConfig = parent.followUpConfig;
5550
5707
  }
5708
+ if (parent.routingAffinity && !options.routingAffinity) {
5709
+ options.routingAffinity = parent.routingAffinity;
5710
+ }
5551
5711
  }
5552
5712
  }
5553
5713
  const existingTrackerWork = findExistingLinearTrackerContextWork(options?.contextKey);
@@ -5572,8 +5732,8 @@ function createTaskExtended(task, options) {
5572
5732
  vcsInstallationId, vcsNodeId,
5573
5733
  agentmailInboxId, agentmailMessageId, agentmailThreadId,
5574
5734
  mentionMessageId, mentionChannelId, dir, parentTaskId, model, modelTier, effort, scheduleId,
5575
- workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, contextKey, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by
5576
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(id, 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?.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, package_default.version, now, now, auditUserId, auditUserId);
5735
+ workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, contextKey, routingAffinity, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by
5736
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(id, 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?.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);
5577
5737
  if (!row)
5578
5738
  throw new Error("Failed to create task");
5579
5739
  try {
@@ -5608,6 +5768,24 @@ function createTaskExtended(task, options) {
5608
5768
  return rowToAgentTask(row);
5609
5769
  }
5610
5770
  function claimTask(taskId, agentId) {
5771
+ if (isPoolAffinityEnforcementEnabled()) {
5772
+ const task = getTaskById(taskId);
5773
+ const agent = getAgentById(agentId);
5774
+ if (task && agent && !isAgentEligibleForTask(agent, task)) {
5775
+ try {
5776
+ createLogEntry({
5777
+ eventType: "task_claim_rejected_affinity",
5778
+ agentId,
5779
+ taskId,
5780
+ metadata: {
5781
+ agentRole: agent.role ?? null,
5782
+ requiredRole: task.routingAffinity?.role ?? null
5783
+ }
5784
+ });
5785
+ } catch {}
5786
+ return null;
5787
+ }
5788
+ }
5611
5789
  const now = new Date().toISOString();
5612
5790
  const row = getDb().prepare(`UPDATE agent_tasks SET agentId = ?, status = 'in_progress', lastUpdatedAt = ?
5613
5791
  WHERE id = ? AND status = 'unassigned' RETURNING *`).get(agentId, now, taskId);
@@ -5779,6 +5957,31 @@ function getUnassignedTaskIds(limit = 10) {
5779
5957
  const rows = getDb().prepare("SELECT id FROM agent_tasks WHERE status = 'unassigned' ORDER BY priority DESC, createdAt ASC, rowid ASC LIMIT ?").all(limit);
5780
5958
  return rows.map((r) => r.id);
5781
5959
  }
5960
+ function getUnassignedTaskIdsForAgent(agentId, limit = 10) {
5961
+ const agent = getAgentById(agentId);
5962
+ if (!agent)
5963
+ return [];
5964
+ const batchSize = Math.max(limit * 5, ELIGIBILITY_SCAN_BATCH_SIZE);
5965
+ const eligible = [];
5966
+ let offset = 0;
5967
+ while (eligible.length < limit && offset < ELIGIBILITY_SCAN_CAP) {
5968
+ const rows = getDb().prepare("SELECT * FROM agent_tasks WHERE status = 'unassigned' ORDER BY priority DESC, createdAt ASC, rowid ASC LIMIT ? OFFSET ?").all(batchSize, offset);
5969
+ if (rows.length === 0)
5970
+ break;
5971
+ for (const row of rows) {
5972
+ const task = rowToAgentTask(row);
5973
+ if (isAgentEligibleForTask(agent, task)) {
5974
+ eligible.push(task.id);
5975
+ if (eligible.length >= limit)
5976
+ break;
5977
+ }
5978
+ }
5979
+ offset += rows.length;
5980
+ if (rows.length < batchSize)
5981
+ break;
5982
+ }
5983
+ return eligible;
5984
+ }
5782
5985
  function checkDependencies(taskId) {
5783
5986
  const task = getTaskById(taskId);
5784
5987
  if (!task || !task.dependsOn || task.dependsOn.length === 0) {
@@ -7175,8 +7378,11 @@ function getStalledInProgressTasks(thresholdMinutes = 30) {
7175
7378
  function getStalePinnedResumes(graceMin) {
7176
7379
  const cutoff = new Date(Date.now() - graceMin * 60 * 1000).toISOString();
7177
7380
  return getDb().prepare(`SELECT * FROM agent_tasks
7178
- WHERE taskType = 'resume' AND status = 'pending'
7179
- AND (tags LIKE '%"crash-recovery-pin"%' OR tags LIKE '%"graceful-shutdown-pin"%')
7381
+ WHERE status = 'pending'
7382
+ AND (
7383
+ (taskType = 'resume' AND (tags LIKE '%"crash-recovery-pin"%' OR tags LIKE '%"graceful-shutdown-pin"%'))
7384
+ OR tags LIKE '%"reboot-retry-pin"%'
7385
+ )
7180
7386
  AND createdAt < ?
7181
7387
  ORDER BY createdAt ASC`).all(cutoff).map(rowToAgentTask);
7182
7388
  }
@@ -7207,11 +7413,16 @@ function getIdleWorkersWithCapacity() {
7207
7413
  return activeCount < (agent.maxTasks ?? 1);
7208
7414
  });
7209
7415
  }
7210
- function getUnassignedPoolTasks(limit = 10) {
7416
+ function getUnassignedPoolTasks(limit = 10, offset = 0) {
7211
7417
  return getDb().prepare(`SELECT * FROM agent_tasks
7212
7418
  WHERE status = 'unassigned'
7213
- ORDER BY priority DESC, createdAt ASC
7214
- LIMIT ?`).all(limit).map(rowToAgentTask);
7419
+ ORDER BY priority DESC, createdAt ASC, rowid ASC
7420
+ LIMIT ? OFFSET ?`).all(limit, offset).map(rowToAgentTask);
7421
+ }
7422
+ function getStaleUnassignedAffinityTasks(cutoffIso) {
7423
+ return getDb().prepare(`SELECT * FROM agent_tasks
7424
+ WHERE status = 'unassigned' AND routingAffinity IS NOT NULL AND createdAt < ?
7425
+ ORDER BY createdAt ASC`).all(cutoffIso).map(rowToAgentTask);
7215
7426
  }
7216
7427
  function getRecentFailedTasks(hours = 6) {
7217
7428
  const since = new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();
@@ -7738,7 +7949,11 @@ function updatePage(id, data) {
7738
7949
  return row ? rowToPage(row) : null;
7739
7950
  }
7740
7951
  function deletePage(id) {
7741
- const result = getDb().run("DELETE FROM pages WHERE id = ?", [id]);
7952
+ const result = getDb().transaction(() => {
7953
+ getDb().run("DELETE FROM user_favorites WHERE itemType = 'page' AND itemId = ?", [id]);
7954
+ getDb().run("DELETE FROM kv_entries WHERE namespace = ?", [`task:page:${id}`]);
7955
+ return getDb().run("DELETE FROM pages WHERE id = ?", [id]);
7956
+ })();
7742
7957
  return result.changes > 0;
7743
7958
  }
7744
7959
  function incrementPageViewCount(id) {
@@ -8080,6 +8295,7 @@ function rowToApprovalRequest(row) {
8080
8295
  timeoutSeconds: row.timeoutSeconds,
8081
8296
  expiresAt: normalizeDate(row.expiresAt),
8082
8297
  notificationChannels: row.notificationChannels ? JSON.parse(row.notificationChannels) : null,
8298
+ createdBy: row.created_by ?? undefined,
8083
8299
  createdAt: normalizeDateRequired(row.createdAt),
8084
8300
  updatedAt: normalizeDateRequired(row.updatedAt)
8085
8301
  };
@@ -8087,9 +8303,9 @@ function rowToApprovalRequest(row) {
8087
8303
  function createApprovalRequest(data) {
8088
8304
  const now = new Date().toISOString();
8089
8305
  const expiresAt = data.timeoutSeconds ? new Date(Date.now() + data.timeoutSeconds * 1000).toISOString() : null;
8090
- const row = getDb().prepare(`INSERT INTO approval_requests (id, title, questions, workflowRunId, workflowRunStepId, sourceTaskId, approvers, timeoutSeconds, expiresAt, notificationChannels, createdAt, updatedAt)
8091
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
8092
- RETURNING *`).get(data.id, data.title, JSON.stringify(data.questions), data.workflowRunId ?? null, data.workflowRunStepId ?? null, data.sourceTaskId ?? null, JSON.stringify(data.approvers), data.timeoutSeconds ?? null, expiresAt, data.notificationChannels ? JSON.stringify(data.notificationChannels) : null, now, now);
8306
+ const row = getDb().prepare(`INSERT INTO approval_requests (id, title, questions, workflowRunId, workflowRunStepId, sourceTaskId, approvers, timeoutSeconds, expiresAt, notificationChannels, created_by, createdAt, updatedAt)
8307
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
8308
+ RETURNING *`).get(data.id, data.title, JSON.stringify(data.questions), data.workflowRunId ?? null, data.workflowRunStepId ?? null, data.sourceTaskId ?? null, JSON.stringify(data.approvers), data.timeoutSeconds ?? null, expiresAt, data.notificationChannels ? JSON.stringify(data.notificationChannels) : null, data.createdBy ?? null, now, now);
8093
8309
  return rowToApprovalRequest(row);
8094
8310
  }
8095
8311
  function getApprovalRequestById(id) {
@@ -8790,8 +9006,19 @@ function updateMcpServer(id, updates) {
8790
9006
  return row ? rowToMcpServer(row) : null;
8791
9007
  }
8792
9008
  function deleteMcpServer(id) {
8793
- const result = getDb().prepare("DELETE FROM mcp_servers WHERE id = ?").run(id);
8794
- return result.changes > 0;
9009
+ const db2 = getDb();
9010
+ const existing = db2.prepare("SELECT id FROM mcp_servers WHERE id = ?").get(id);
9011
+ if (!existing)
9012
+ return { deleted: false, deletedScriptConnectionCount: 0 };
9013
+ const tx = db2.transaction(() => {
9014
+ const deletedConnections = db2.prepare("DELETE FROM script_connections WHERE mcp_server_id = ?").run(id);
9015
+ const deletedServer = db2.prepare("DELETE FROM mcp_servers WHERE id = ?").run(id);
9016
+ return {
9017
+ deleted: deletedServer.changes > 0,
9018
+ deletedScriptConnectionCount: deletedConnections.changes
9019
+ };
9020
+ });
9021
+ return tx();
8795
9022
  }
8796
9023
  function getMcpServerById(id) {
8797
9024
  const row = getDb().prepare("SELECT * FROM mcp_servers WHERE id = ?").get(id);
@@ -9969,7 +10196,7 @@ function countScriptRunJournalAgentTaskSteps(runId) {
9969
10196
  const row = getDb().prepare("SELECT COUNT(*) AS count FROM script_run_journal WHERE runId = ? AND stepType = 'agent-task'").get(runId);
9970
10197
  return row?.count ?? 0;
9971
10198
  }
9972
- var db = null, sqliteVecAvailable = false, VERSIONABLE_FIELDS, agentQueries, MAX_EMPTY_POLLS = 2, taskQueries, findTaskByGitHub, LINEAR_TRACKER_CONTEXT_KEY_PREFIX = "task:trackers:linear:", logQueries, sessionLogQueries, sessionCostQueries, 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;
10199
+ var db = null, sqliteVecAvailable = false, VERSIONABLE_FIELDS, agentQueries, MAX_EMPTY_POLLS = 2, taskQueries, findTaskByGitHub, LINEAR_TRACKER_CONTEXT_KEY_PREFIX = "task:trackers:linear:", logQueries, ELIGIBILITY_SCAN_BATCH_SIZE, ELIGIBILITY_SCAN_CAP, sessionLogQueries, sessionCostQueries, 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;
9973
10200
  var init_db = __esm(() => {
9974
10201
  init_provider_metadata();
9975
10202
  init_package();
@@ -10029,6 +10256,8 @@ var init_db = __esm(() => {
10029
10256
  getByEventType: () => getDb().prepare("SELECT * FROM agent_log WHERE eventType = ? ORDER BY createdAt DESC"),
10030
10257
  getAll: () => getDb().prepare("SELECT * FROM agent_log ORDER BY createdAt DESC")
10031
10258
  };
10259
+ ELIGIBILITY_SCAN_BATCH_SIZE = Number(process.env.ELIGIBILITY_SCAN_BATCH_SIZE) || 25;
10260
+ ELIGIBILITY_SCAN_CAP = Number(process.env.ELIGIBILITY_SCAN_CAP) || 500;
10032
10261
  sessionLogQueries = {
10033
10262
  insert: () => getDb().prepare(`INSERT INTO session_logs (id, taskId, sessionId, iteration, cli, content, lineNumber, createdAt)
10034
10263
  VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) RETURNING *`),
@@ -10077,4 +10306,4 @@ var init_db = __esm(() => {
10077
10306
  };
10078
10307
  });
10079
10308
 
10080
- export { interpolate, deepInterpolate, init_template, registerTemplate, getTemplateDefinition, getAllTemplateDefinitions, init_registry, configureHttpResolver, resolveTemplate, resolveTemplateAsync, init_resolver, initTelemetry, telemetry, init_telemetry, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, FollowUpConfigSchema, AgentTaskSchema, AttachmentInputSchema, TaskAttachmentSchema, InboxItemTypeSchema, InboxItemStatusSchema, FavoriteItemTypeSchema, TaskTemplateKindSchema, AgentSchema, AgentLatestModelSchema, AgentCredStatusSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, ResumeReasonSchema, AgentLogSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, ScheduledTaskTargetTypeSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, PageContentTypeSchema, PageAuthModeSchema, MetricDefinitionSchema, MetricVersionSchema, WorkflowRunStatusSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptApiAuthModeSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, KvEntrySchema, init_types, setRequestAuth, getRequestAuth, getCurrentRequestAuth, init_request_auth_context, encryptSecret, decryptSecret, getEncryptionKey, init_crypto, normalizeDateRequired, init_date_utils, init_session_templates, init_templates, init_templates2 as init_templates1, 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, taskQueries, createTask, getPendingTaskForAgent, assignUnassignedTaskPending, startTask, getTaskById, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, cancelTask, supersedeTask, backfillSupersedeTaskResumeTaskId, pauseTask, resumeTask, getPausedTasksForAgent, getOrphanedInProgressTasksForAgent, resetOrphanedInProgressTasksForAgent, getRecentlyCancelledTasksForAgent, deleteTask, updateTaskProgress, insertTaskAttachment, deleteTaskAttachment, replaceTaskAttachment, getTaskAttachments, getAgentWithTasks, getAllAgentsWithTasks, logQueries, createLogEntry, getLogsByAgentId, getLogsByTaskId, getLogsByTaskIdChronological, getLogsByEventType, getAllLogs, findRecentSimilarTasks, createTaskExtended, claimTask, releaseTask, acceptTask, rejectTask, moveTaskToBacklog, moveTaskFromBacklog, releaseStaleReviewingTasks, getOfferedTasksForAgent, claimOfferedTask, getUnassignedTasksCount, getUnassignedTaskIds, 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, 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, getRecentFailedTasks, getRecentCompletedCount, getRecentFailedCount, createWorkflow, getWorkflow, listWorkflows, updateWorkflow, deleteWorkflow, getWorkflowsByScheduleId, createWorkflowRun, getWorkflowRun, updateWorkflowRun, listWorkflowRuns, createWorkflowRunStep, getWorkflowRunStep, updateWorkflowRunStep, getWorkflowRunStepsByRunId, getStuckWorkflowRuns, getLastSuccessfulRun, getLastRunStart, getRetryableSteps, getCompletedStepNodeIds, getTaskByWorkflowRunStepId, getStepByIdempotencyKey, getStepCountForNode, getLatestStepForNode, createWorkflowVersion, getWorkflowVersions, getWorkflowVersion, 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, listUserFavorites, getFavoriteItemIdSet, 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, upsertKv, deleteKv, KvTypeCollisionError, incrKv, listKv, countKv, createScriptRun, recordInlineScriptRun, getScriptRun, getScriptRunByIdempotencyKey, listScriptRuns, countScriptRuns, countActiveScriptRuns, updateScriptRun, getRunningScriptRuns, getScriptRunJournalStep, upsertScriptRunJournalStep, listScriptRunJournalSteps, countScriptRunJournalSteps, countScriptRunJournalAgentTaskSteps, exports_db, init_db };
10309
+ export { interpolate, deepInterpolate, init_template, registerTemplate, getTemplateDefinition, getAllTemplateDefinitions, init_registry, configureHttpResolver, resolveTemplate, resolveTemplateAsync, init_resolver, initTelemetry, telemetry, init_telemetry, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, FollowUpConfigSchema, AgentTaskSchema, AttachmentInputSchema, TaskAttachmentSchema, InboxItemTypeSchema, InboxItemStatusSchema, FavoriteItemTypeSchema, TaskTemplateKindSchema, AgentSchema, AgentLatestModelSchema, AgentCredStatusSchema, ChannelTypeSchema, ChannelSchema, ChannelMessageSchema, ServiceStatusSchema, ServiceSchema, ResumeReasonSchema, AgentLogSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, ScheduledTaskTargetTypeSchema, SwarmConfigScopeSchema, SwarmConfigSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, AgentMemorySchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, PageContentTypeSchema, PageAuthModeSchema, MetricDefinitionSchema, MetricVersionSchema, WorkflowRunStatusSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, PromptTemplateScopeSchema, PromptTemplateStateSchema, PromptTemplateSchema, PromptTemplateHistorySchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptApiAuthModeSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, KvEntrySchema, init_types, setRequestAuth, getRequestAuth, getCurrentRequestAuth, init_request_auth_context, encryptSecret, decryptSecret, getEncryptionKey, init_crypto, normalizeDate, normalizeDateRequired, init_date_utils, init_session_templates, init_templates, init_templates2 as init_templates1, 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, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, cancelTask, supersedeTask, backfillSupersedeTaskResumeTaskId, pauseTask, resumeTask, getPausedTasksForAgent, getOrphanedInProgressTasksForAgent, resetOrphanedInProgressTasksForAgent, getRecentlyCancelledTasksForAgent, deleteTask, updateTaskProgress, insertTaskAttachment, deleteTaskAttachment, replaceTaskAttachment, getTaskAttachments, 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, 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, createWorkflowRunStep, getWorkflowRunStep, updateWorkflowRunStep, getWorkflowRunStepsByRunId, getStuckWorkflowRuns, getLastSuccessfulRun, getLastRunStart, getRetryableSteps, getCompletedStepNodeIds, getTaskByWorkflowRunStepId, getStepByIdempotencyKey, getStepCountForNode, getLatestStepForNode, createWorkflowVersion, getWorkflowVersions, getWorkflowVersion, 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, listUserFavorites, getFavoriteItemIdSet, 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, upsertKv, deleteKv, KvTypeCollisionError, incrKv, listKv, countKv, createScriptRun, recordInlineScriptRun, getScriptRun, getScriptRunByIdempotencyKey, listScriptRuns, countScriptRuns, countActiveScriptRuns, updateScriptRun, getRunningScriptRuns, getScriptRunJournalStep, upsertScriptRunJournalStep, listScriptRunJournalSteps, countScriptRunJournalSteps, countScriptRunJournalAgentTaskSteps, exports_db, init_db };
@@ -14,7 +14,7 @@ import {
14
14
  string,
15
15
  union,
16
16
  unknown
17
- } from "./cli-anrj584m.js";
17
+ } from "./cli-xz9aq0rf.js";
18
18
 
19
19
  // node_modules/@mistralai/mistralai/esm/lib/primitives.js
20
20
  function remap(inp, mappings) {
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  buildModelsDevSeedRows
3
- } from "./cli-tbw13sx8.js";
3
+ } from "./cli-tece6zgm.js";
4
4
  import {
5
5
  createLogEntry,
6
6
  getActivePricingRow,
7
7
  getDb,
8
8
  init_db,
9
9
  insertPricingRow
10
- } from "./cli-ncfgsqbd.js";
10
+ } from "./cli-15y7qhzp.js";
11
11
  import {
12
12
  init_secret_scrubber,
13
13
  scrubSecrets