@desplega.ai/agent-swarm 1.124.0 → 1.125.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 (101) hide show
  1. package/dist/{actions-z3d0fk7z.js → actions-3aky6er5.js} +6 -5
  2. package/dist/{app-q2rc9tdr.js → app-xbt4n4mt.js} +4 -3
  3. package/dist/{assistant-3stjq7fz.js → assistant-ncftbs9t.js} +12 -10
  4. package/dist/{boot-reembed-v6r1df32.js → boot-reembed-00cxm1mj.js} +5 -4
  5. package/dist/{boot-reembed-5867whnb.js → boot-reembed-5xxzva12.js} +4 -3
  6. package/dist/{boot-scrub-logs-8b8jegk3.js → boot-scrub-logs-9cmcq6ez.js} +3 -2
  7. package/dist/{cli-0925phzv.js → cli-0w3mk6r2.js} +1 -1
  8. package/dist/{cli-zxb72ctk.js → cli-3x5aphbt.js} +2 -2
  9. package/dist/{cli-exfs8aym.js → cli-3y8xyp0b.js} +7 -1
  10. package/dist/{cli-2yr6edr7.js → cli-4xft7caa.js} +4 -4
  11. package/dist/{cli-kk58tg33.js → cli-5a4nmfrn.js} +12 -10
  12. package/dist/{cli-5jn6wnd9.js → cli-88r31vx9.js} +2 -2
  13. package/dist/{cli-sqv6c9b8.js → cli-8bkwn1wv.js} +11 -9
  14. package/dist/{cli-p0zgv8pj.js → cli-8vzddbs7.js} +2 -1
  15. package/dist/{cli-qf7acvyr.js → cli-94796kxr.js} +2 -2
  16. package/dist/{cli-wn3m6q54.js → cli-dbmh9yqn.js} +7 -5
  17. package/dist/{cli-p0ec4vv6.js → cli-ff8b5cbe.js} +1 -1
  18. package/dist/{cli-y43n987v.js → cli-gbx122ge.js} +1 -1
  19. package/dist/{cli-ykthjw29.js → cli-jcavqvh7.js} +20 -24
  20. package/dist/cli-k1py8264.js +1129 -0
  21. package/dist/{cli-qwsagsmg.js → cli-k5c6jfzn.js} +1 -1
  22. package/dist/{cli-gkvf8d83.js → cli-n02497b2.js} +5 -3
  23. package/dist/{cli-vm20sh8d.js → cli-nqq9tthd.js} +9 -7
  24. package/dist/{cli-jp4mdj9d.js → cli-pqtrhrss.js} +2 -2
  25. package/dist/{cli-gzjsamwc.js → cli-q92pr3rt.js} +1 -1
  26. package/dist/{cli-mmk5vagg.js → cli-qzy21svh.js} +2 -2
  27. package/dist/{cli-dq2ssyf0.js → cli-refygp3c.js} +5 -5
  28. package/dist/{cli-perb20ma.js → cli-tar44ekp.js} +1 -1
  29. package/dist/{cli-h89g0qrd.js → cli-v292k2fv.js} +1 -1
  30. package/dist/{cli-mcez7z4p.js → cli-vvbwy286.js} +1 -1
  31. package/dist/{cli-x268say8.js → cli-wbcsjpyv.js} +366 -68
  32. package/dist/cli-wdrrgv4m.js +22 -0
  33. package/dist/{cli-3z4q09tn.js → cli-yr11vvst.js} +32 -1127
  34. package/dist/{cli-92bqgbgy.js → cli-zhp3t49e.js} +4 -2
  35. package/dist/cli.js +23 -10
  36. package/dist/{codex-adapter-vcseqpwf.js → codex-adapter-mqczt8xv.js} +1 -1
  37. package/dist/codex-hook-emq42pfq.js +106 -0
  38. package/dist/{codex-session-runner-jec9e9t1.js → codex-session-runner-mrwz1h50.js} +1 -1
  39. package/dist/{commands-sda76yn8.js → commands-7dbx98fp.js} +5 -3
  40. package/dist/{db-vn9e4rqj.js → db-r5705rk8.js} +7 -2
  41. package/dist/{handlers-xfja18ac.js → handlers-8kj038es.js} +12 -10
  42. package/dist/{hook-2medrp47.js → hook-2590fnyk.js} +1 -1
  43. package/dist/{http-937pyjfc.js → http-8yej35d0.js} +77 -55
  44. package/dist/{index-vah60vxp.js → index-hy73j39b.js} +8 -7
  45. package/dist/{index-knqczmnm.js → index-kgay2v5w.js} +11 -10
  46. package/dist/{index-gw4en7jg.js → index-v3n4hb3w.js} +10 -9
  47. package/dist/{index-2bqd2q9v.js → index-x1n3tybc.js} +12 -11
  48. package/dist/{keepalive-20rd6hxh.js → keepalive-q8yg6d6r.js} +6 -5
  49. package/dist/{lead-7w2k3a49.js → lead-yxtt169p.js} +23 -21
  50. package/dist/{maintenance-p3x918yw.js → maintenance-70cskw5t.js} +5 -4
  51. package/dist/{oauth-refresh-sweep-shm0nzm4.js → oauth-refresh-sweep-90h9rzx8.js} +5 -4
  52. package/dist/{onboard-py9dnf54.js → onboard-20reqz6j.js} +2 -2
  53. package/dist/{otel-impl-7yjkfg68.js → otel-impl-vja8f9mm.js} +1 -1
  54. package/dist/{pricing-refresh-3snb6370.js → pricing-refresh-34mbexgm.js} +5 -4
  55. package/dist/{rbac-roles-gqxdp8st.js → rbac-roles-s1qnewkt.js} +5 -4
  56. package/dist/{rbac-roles-5e72bbpk.js → rbac-roles-sa59eyp4.js} +4 -3
  57. package/dist/{seed-pricing-bg42d7h2.js → seed-pricing-p5fnj0qd.js} +4 -3
  58. package/dist/{setup-nzk3kbbq.js → setup-p9yq3mb2.js} +2 -2
  59. package/dist/{worker-0p1jdzkm.js → worker-21zrq8cd.js} +23 -21
  60. package/openapi.json +1 -1
  61. package/package.json +2 -1
  62. package/src/be/db.ts +30 -0
  63. package/src/cli.tsx +12 -0
  64. package/src/commands/runner.ts +11 -23
  65. package/src/hooks/codex-hook.ts +157 -0
  66. package/src/http/kv.ts +37 -8
  67. package/src/http/mcp-bridge.ts +3 -2
  68. package/src/kv-overflow.ts +20 -0
  69. package/src/prompts/steering-delivery.ts +32 -0
  70. package/src/providers/codex-adapter.ts +20 -4
  71. package/src/providers/types.ts +8 -0
  72. package/src/script-workflows/harness.ts +5 -1
  73. package/src/script-workflows/workflow-ctx.ts +6 -7
  74. package/src/scripts-runtime/eval-harness.ts +11 -2
  75. package/src/scripts-runtime/extract-args-schema.ts +5 -1
  76. package/src/scripts-runtime/response-limit.ts +50 -0
  77. package/src/scripts-runtime/swarm-sdk.ts +3 -4
  78. package/src/tests/claude-adapter-binary.test.ts +64 -32
  79. package/src/tests/codex-steering-hook.test.ts +224 -0
  80. package/src/tests/kv-http.test.ts +35 -1
  81. package/src/tests/kv-storage.test.ts +45 -0
  82. package/src/tests/kv-tool.test.ts +51 -0
  83. package/src/tests/run-bun-tests.test.ts +171 -0
  84. package/src/tests/scripts-mcp-e2e.test.ts +105 -1
  85. package/src/tests/scripts-runtime.test.ts +33 -0
  86. package/src/tests/sdk-allowlist.test.ts +27 -1
  87. package/src/tests/slack-read-boundaries.test.ts +229 -0
  88. package/src/tests/steering-core.test.ts +19 -19
  89. package/src/tests/steering-transport.test.ts +21 -3
  90. package/src/tests/store-progress-attachments-handler.test.ts +45 -10
  91. package/src/tests/swarm-tool-result-gate.test.ts +300 -21
  92. package/src/tests/tool-output-agent-id.test.ts +9 -3
  93. package/src/tests/tool-registrar-no-input.test.ts +6 -0
  94. package/src/tools/kv/kv-get.ts +10 -0
  95. package/src/tools/kv/kv-list.ts +7 -0
  96. package/src/tools/kv/kv-read-auth.ts +13 -0
  97. package/src/tools/kv/kv-write-auth.ts +4 -0
  98. package/src/tools/steer-task.ts +1 -1
  99. package/src/tools/store-progress.ts +24 -7
  100. package/src/tools/utils.ts +403 -43
  101. package/src/types.ts +7 -1
@@ -1,3 +1,15 @@
1
+ import {
2
+ configureDbResolver,
3
+ getAllTemplateDefinitions,
4
+ init_env_flag,
5
+ init_registry,
6
+ init_resolver,
7
+ init_session_templates,
8
+ init_steering_enabled,
9
+ isEnvFlagEnabled,
10
+ isSteeringEnabled,
11
+ registerTemplate
12
+ } from "./cli-k1py8264.js";
1
13
  import {
2
14
  deriveProviderFromKeyType,
3
15
  init_credentials
@@ -5,7 +17,7 @@ import {
5
17
  import {
6
18
  init_package,
7
19
  package_default
8
- } from "./cli-p0zgv8pj.js";
20
+ } from "./cli-8vzddbs7.js";
9
21
  import {
10
22
  init_secret_scrubber,
11
23
  scrubSecrets
@@ -121,219 +133,6 @@ var init_key = __esm(() => {
121
133
  };
122
134
  });
123
135
 
124
- // src/utils/template.ts
125
- function interpolate(template, ctx) {
126
- const unresolved = [];
127
- const result = template.replace(/\{\{([^}]+)\}\}/g, (_match, path) => {
128
- const keys = path.trim().split(".");
129
- let value = ctx;
130
- for (const key of keys) {
131
- if (value == null || typeof value !== "object") {
132
- unresolved.push(path.trim());
133
- return "";
134
- }
135
- value = value[key];
136
- }
137
- if (value == null) {
138
- unresolved.push(path.trim());
139
- return "";
140
- }
141
- return typeof value === "object" ? safeStringify(value) : String(value);
142
- });
143
- return { result, unresolved };
144
- }
145
- function safeStringify(value) {
146
- try {
147
- return JSON.stringify(value);
148
- } catch {
149
- return "[Circular]";
150
- }
151
- }
152
- function resolvePath(path, ctx) {
153
- const keys = path.trim().split(".");
154
- let value = ctx;
155
- for (const key of keys) {
156
- if (value == null || typeof value !== "object")
157
- return { found: false };
158
- value = value[key];
159
- }
160
- if (value === undefined)
161
- return { found: false };
162
- return { found: true, value };
163
- }
164
- function deepInterpolate(value, ctx, options = {}) {
165
- const allUnresolved = [];
166
- function walk(v) {
167
- if (typeof v === "string") {
168
- const exactMatch = options.preserveRawTokens ? EXACT_TOKEN_RE.exec(v) : null;
169
- if (exactMatch?.[1]) {
170
- const path = exactMatch[1].trim();
171
- const resolved = resolvePath(path, ctx);
172
- if (!resolved.found) {
173
- allUnresolved.push(path);
174
- return "";
175
- }
176
- return resolved.value;
177
- }
178
- const { result, unresolved } = interpolate(v, ctx);
179
- allUnresolved.push(...unresolved);
180
- return result;
181
- }
182
- if (Array.isArray(v))
183
- return v.map(walk);
184
- if (v != null && typeof v === "object") {
185
- const out = {};
186
- for (const [k, val] of Object.entries(v)) {
187
- out[k] = walk(val);
188
- }
189
- return out;
190
- }
191
- return v;
192
- }
193
- return { value: walk(value), unresolved: allUnresolved };
194
- }
195
- var EXACT_TOKEN_RE;
196
- var init_template = __esm(() => {
197
- EXACT_TOKEN_RE = /^\{\{([^}]+)\}\}$/;
198
- });
199
-
200
- // src/prompts/registry.ts
201
- function registerTemplate(def) {
202
- templateDefinitions.set(def.eventType, def);
203
- }
204
- function getTemplateDefinition(eventType) {
205
- return templateDefinitions.get(eventType);
206
- }
207
- function getAllTemplateDefinitions() {
208
- return Array.from(templateDefinitions.values());
209
- }
210
- var templateDefinitions;
211
- var init_registry = __esm(() => {
212
- templateDefinitions = new Map;
213
- });
214
-
215
- // src/prompts/resolver.ts
216
- function configureDbResolver(fn) {
217
- dbResolverFn = fn;
218
- }
219
- function configureHttpResolver(apiUrl, apiKey) {
220
- httpResolverConfig = { apiUrl, apiKey };
221
- }
222
- async function resolveTemplateViaHttp(eventType, variables, options) {
223
- const config = httpResolverConfig;
224
- const url = `${config.apiUrl}/api/prompt-templates/render`;
225
- try {
226
- const resp = await fetch(url, {
227
- method: "POST",
228
- headers: {
229
- Authorization: `Bearer ${config.apiKey}`,
230
- "Content-Type": "application/json"
231
- },
232
- body: JSON.stringify({
233
- eventType,
234
- variables,
235
- agentId: options.agentId,
236
- repoId: options.repoId
237
- })
238
- });
239
- if (!resp.ok) {
240
- console.warn(`[prompt-resolver] HTTP render failed (${resp.status}), falling back to code defaults`);
241
- return resolveTemplateFromCode(eventType, variables);
242
- }
243
- return await resp.json();
244
- } catch (err) {
245
- console.warn(`[prompt-resolver] HTTP render error, falling back to code defaults:`, err instanceof Error ? err.message : err);
246
- return resolveTemplateFromCode(eventType, variables);
247
- }
248
- }
249
- function resolveTemplateFromCode(eventType, variables) {
250
- const definition = getTemplateDefinition(eventType);
251
- const header = definition?.header ?? "";
252
- const body = definition?.defaultBody ?? "";
253
- const composed = header ? `${header}
254
-
255
- ${body}` : body;
256
- const { result: text, unresolved } = interpolate(composed, variables);
257
- return { text, skipped: false, unresolved };
258
- }
259
- function resolveTemplate(eventType, variables, options = {}) {
260
- if (httpResolverConfig) {
261
- return resolveTemplateFromCode(eventType, variables);
262
- }
263
- return resolveTemplateViaDb(eventType, variables, options);
264
- }
265
- async function resolveTemplateAsync(eventType, variables, options = {}) {
266
- if (httpResolverConfig) {
267
- return resolveTemplateViaHttp(eventType, variables, options);
268
- }
269
- return resolveTemplateViaDb(eventType, variables, options);
270
- }
271
- function resolveTemplateViaDb(eventType, variables, options) {
272
- const definition = getTemplateDefinition(eventType);
273
- const header = definition?.header ?? "";
274
- const defaultBody = definition?.defaultBody ?? "";
275
- const dbResult = dbResolverFn?.(eventType, options.agentId, options.repoId) ?? null;
276
- if (dbResult && "skip" in dbResult) {
277
- return { text: "", skipped: true, unresolved: [] };
278
- }
279
- let body;
280
- let templateId;
281
- let scope;
282
- if (dbResult && "template" in dbResult) {
283
- body = dbResult.template.body;
284
- templateId = dbResult.template.id;
285
- scope = dbResult.template.scope;
286
- } else {
287
- body = defaultBody;
288
- }
289
- body = expandTemplateRefs(body, variables, options, new Set, 0);
290
- const composed = header ? `${header}
291
-
292
- ${body}` : body;
293
- const { result: text, unresolved } = interpolate(composed, variables);
294
- return {
295
- text,
296
- templateId,
297
- scope,
298
- skipped: false,
299
- unresolved
300
- };
301
- }
302
- function expandTemplateRefs(text, variables, options, visited, depth) {
303
- if (depth > MAX_TEMPLATE_REF_DEPTH) {
304
- return text;
305
- }
306
- return text.replace(TEMPLATE_REF_REGEX, (fullMatch, referencedId) => {
307
- if (visited.has(referencedId)) {
308
- console.warn(`[prompt-resolver] Cycle detected for template reference "${referencedId}", leaving token as-is`);
309
- return fullMatch;
310
- }
311
- if (depth + 1 > MAX_TEMPLATE_REF_DEPTH) {
312
- console.warn(`[prompt-resolver] Max template reference depth (${MAX_TEMPLATE_REF_DEPTH}) exceeded for "${referencedId}", leaving token as-is`);
313
- return fullMatch;
314
- }
315
- const refDef = getTemplateDefinition(referencedId);
316
- const refDefaultBody = refDef?.defaultBody ?? "";
317
- const refDbResult = dbResolverFn?.(referencedId, options.agentId, options.repoId) ?? null;
318
- if (refDbResult && "skip" in refDbResult) {
319
- return fullMatch;
320
- }
321
- const refBody = refDbResult && "template" in refDbResult ? refDbResult.template.body : refDefaultBody;
322
- if (!refBody) {
323
- return fullMatch;
324
- }
325
- const newVisited = new Set(visited);
326
- newVisited.add(referencedId);
327
- return expandTemplateRefs(refBody, variables, options, newVisited, depth + 1);
328
- });
329
- }
330
- var dbResolverFn = null, httpResolverConfig = null, MAX_TEMPLATE_REF_DEPTH = 3, TEMPLATE_REF_REGEX;
331
- var init_resolver = __esm(() => {
332
- init_template();
333
- init_registry();
334
- TEMPLATE_REF_REGEX = /\{\{@template\[([^\]]+)\]\}\}/g;
335
- });
336
-
337
136
  // src/tasks/context-key.ts
338
137
  function assertSafePart(value, label) {
339
138
  if (value === null || value === undefined) {
@@ -592,28 +391,6 @@ var init_slack_routing = __esm(() => {
592
391
  init_context_key();
593
392
  });
594
393
 
595
- // src/utils/env-flag.ts
596
- function parseEnvFlag(raw, defaultValue) {
597
- if (raw === undefined || raw === null)
598
- return defaultValue;
599
- const normalized = raw.trim().toLowerCase();
600
- if (normalized === "")
601
- return defaultValue;
602
- if (TRUTHY.has(normalized))
603
- return true;
604
- if (FALSY.has(normalized))
605
- return false;
606
- return defaultValue;
607
- }
608
- function isEnvFlagEnabled(key, defaultValue, env = process.env) {
609
- return parseEnvFlag(env[key], defaultValue);
610
- }
611
- var TRUTHY, FALSY;
612
- var init_env_flag = __esm(() => {
613
- TRUTHY = new Set(["true", "1"]);
614
- FALSY = new Set(["false", "0"]);
615
- });
616
-
617
394
  // src/telemetry.ts
618
395
  import { randomUUID } from "node:crypto";
619
396
  function isEnabled() {
@@ -1063,7 +840,7 @@ var init_types = __esm(() => {
1063
840
  devin: ["queue"],
1064
841
  opencode: ["queue"],
1065
842
  claude: ["queue"],
1066
- codex: []
843
+ codex: ["queue"]
1067
844
  };
1068
845
  FollowUpConfigSchema = object({
1069
846
  disabled: boolean().optional(),
@@ -3069,887 +2846,6 @@ var init_oauth_encryption_backfill = __esm(() => {
3069
2846
  init_crypto();
3070
2847
  });
3071
2848
 
3072
- // src/prompts/session-templates.ts
3073
- var init_session_templates = __esm(() => {
3074
- init_registry();
3075
- registerTemplate({
3076
- eventType: "system.agent.role",
3077
- header: "",
3078
- defaultBody: `
3079
- You are part of an agent swarm, your role is: {{role}} and your unique identified is {{agentId}}.
3080
-
3081
- The agent swarm operates in a collaborative manner to achieve complex tasks by dividing responsibilities among specialized agents.
3082
- `,
3083
- variables: [
3084
- { name: "role", description: "The agent's role (e.g. lead, worker)" },
3085
- { name: "agentId", description: "The agent's unique identifier" }
3086
- ],
3087
- category: "system"
3088
- });
3089
- registerTemplate({
3090
- eventType: "system.agent.register",
3091
- header: "",
3092
- defaultBody: `
3093
- If you are not yet registered in the swarm, use the \`join-swarm\` tool to register yourself.
3094
- `,
3095
- variables: [],
3096
- category: "system"
3097
- });
3098
- registerTemplate({
3099
- eventType: "system.agent.lead",
3100
- header: "",
3101
- defaultBody: `
3102
- As the lead agent, you coordinate all worker agents in the swarm.
3103
-
3104
- **CRITICAL: You are a coordinator, NOT a worker.** Delegate ALL implementation, research, analysis, and content creation to workers. The only things you handle directly: swarm management, simple factual answers, and inter-agent coordination. Exception: when the user explicitly says "do this yourself."
3105
-
3106
- #### Tools
3107
-
3108
- **Monitoring:**
3109
- - \`get-swarm\`: See all agents and their status (idle, busy, offline)
3110
- - \`get-tasks\`: List tasks with filters (status, unassigned, tags)
3111
- - \`get-task-details\`: Deep dive into a specific task's progress and output
3112
-
3113
- **Delegation:**
3114
- - \`send-task\`: Assign a task to a specific worker or to the general pool. Slack/AgentMail metadata auto-inherits from parent task.
3115
- - \`store-progress\`: Track coordination notes or update task status
3116
-
3117
- **User Registration:** When a task arrives from an unknown user (no \`requestedByUserId\`), use the \`manage-user\` tool to register them before proceeding. Resolve their identity from the task metadata attached to the task.
3118
-
3119
- **Identity:**
3120
- - \`update-profile\`: Update your own or other agents' profile fields (name, role, capabilities, soulMd, identityMd, heartbeatMd, claudeMd, toolsMd, setupScript)
3121
- - \`manage-user\`: Register or update human users (resolve from GitHub/GitLab identity or other source metadata)
3122
-
3123
- #### Task Routing
3124
-
3125
- When composing task descriptions: include the repo URL (if applicable), specific goal, and any constraints. Workers know how to use git, wts, slash commands, and store-progress — don't spell out those steps.
3126
-
3127
- **Decision guide:**
3128
- - Research/exploration/analysis → tell worker to use \`/desplega:research\`
3129
- - Complex feature/major refactor → send Planning task first, then Implementation with \`parentTaskId\`
3130
- - Bug fix/small change → direct implementation (no plan needed)
3131
- - Non-code task/question → general task description
3132
-
3133
- #### Session Continuity (parentTaskId)
3134
-
3135
- For follow-up tasks that should continue from previous work, pass \`parentTaskId\` with the previous task's ID:
3136
- - Worker resumes the parent's Claude session (full conversation context preserved)
3137
- - Child task is auto-routed to the same worker (session data is local)
3138
-
3139
- If you explicitly assign to a different worker, session resume gracefully falls back to a fresh session.
3140
-
3141
- #### Follow-Up Tasks
3142
-
3143
- When a worker completes or fails a task, you receive an automatic follow-up task. Handle it by:
3144
- 1. Review the output/failure reason
3145
- 2. Complete this task. Do NOT re-delegate or create new worker tasks from a follow-up — the worker's result IS the answer. Only escalate to the stakeholder if the worker explicitly failed and the failure needs human attention.
3146
-
3147
- #### Heartbeat Checklist
3148
-
3149
- The system reads your \`/workspace/HEARTBEAT.md\` every 30 minutes. If it has content, it creates a \`heartbeat-checklist\` task containing auto-generated system status + your standing orders.
3150
-
3151
- **Configuration:** Edit \`/workspace/HEARTBEAT.md\` directly or use \`update-profile\` with the \`heartbeatMd\` field. Empty file = disabled (zero cost).
3152
-
3153
- **Keep it alive:** HEARTBEAT.md is a live operational runbook, not a static config file. Update it when you detect patterns (recurring failures, worker issues, rate limits). Remove items when they're resolved. The system status includes failure reasons and patterns — use them to decide what standing orders to add.
3154
-
3155
- **Example standing orders:**
3156
- \`\`\`markdown
3157
- - Review active tasks for any that seem stuck or need follow-up
3158
- - If idle workers exist and unassigned tasks are available, investigate why
3159
- \`\`\`
3160
-
3161
- **Key mechanics:**
3162
- - System status is automatic — don't gather it yourself
3163
- - Don't create checklist tasks yourself — the system handles scheduling
3164
- - Boot triage: after server restart, you get a higher-priority checklist within 30 seconds
3165
-
3166
- **When you receive a checklist task:** Review system status + standing orders, take action if needed, otherwise complete with "All clear."
3167
- `,
3168
- variables: [],
3169
- category: "system"
3170
- });
3171
- registerTemplate({
3172
- eventType: "system.agent.slack",
3173
- header: "",
3174
- defaultBody: `
3175
- #### Slack Tools
3176
-
3177
- - \`slack-reply\`: Reply to user in the Slack thread (use taskId for context)
3178
- - \`slack-read\`: Read thread/channel history (use taskId or channelId)
3179
- - \`slack-list-channels\`: Discover available Slack channels
3180
-
3181
- **Slack User Registration:** When a task arrives from an unknown user (no \`requestedByUserId\`) with Slack metadata, use the \`manage-user\` tool to register them before proceeding. Resolve their identity from the Slack metadata (user ID, display name) attached to the task.
3182
-
3183
- **Slack context inheritance:** For follow-up tasks using \`parentTaskId\`, Slack metadata (channelId, threadTs, userId) auto-inherits.
3184
-
3185
- **Slack follow-up tasks:** When a worker completes or fails a task that has Slack metadata, use \`slack-reply\` with the task's ID to post the result back to the originating thread before completing the follow-up task.
3186
-
3187
- **Slack standing orders:** If you maintain heartbeat standing orders, check Slack for unaddressed requests older than 1 hour when appropriate.
3188
- `,
3189
- variables: [],
3190
- category: "system"
3191
- });
3192
- registerTemplate({
3193
- eventType: "system.agent.worker",
3194
- header: "",
3195
- defaultBody: `
3196
- As a worker agent of the swarm, you are responsible for executing tasks assigned by the lead agent.
3197
-
3198
- - Each worker focuses on specific tasks or objectives, contributing to the overall goals of the swarm.
3199
- - Workers MUST report their progress back to the lead and collaborate with other workers as needed.
3200
-
3201
- #### Useful tools for workers
3202
-
3203
- - \`store-progress\`: Save your work progress on tasks (critical!)
3204
- - \`task-action\`: Manage tasks - claim from pool, release, accept/reject offered tasks
3205
-
3206
- #### Completing Tasks
3207
-
3208
- When you finish a task:
3209
- - **Success**: Use \`store-progress\` with status: "completed" and output: "<summary of what you did>"
3210
- - **Failure**: Use \`store-progress\` with status: "failed" and failureReason: "<what went wrong>"
3211
-
3212
- Always include meaningful output - the lead agent reviews your work.
3213
-
3214
- #### Credential Hygiene
3215
-
3216
- When you retrieve secrets via \`get-config\` (with \`includeSecrets: true\`), **never pass secret values directly on a command line or embed them in tool output**. Command arguments are logged.
3217
-
3218
- **Safe pattern:** Write the secret to a temporary \`.env\` file, then source it:
3219
- \`\`\`bash
3220
- # Write to temp file (not logged)
3221
- echo "MY_TOKEN=<value>" > /tmp/.task-env && source /tmp/.task-env
3222
- # Use the variable (value stays out of logs)
3223
- curl -H "Authorization: Bearer $MY_TOKEN" https://api.example.com
3224
- rm /tmp/.task-env
3225
- \`\`\`
3226
-
3227
- **Unsafe pattern (NEVER do this):**
3228
- \`\`\`bash
3229
- # The literal secret appears in the logged command
3230
- curl -H "Authorization: Bearer lin_oauth_abc123..." https://api.example.com
3231
- \`\`\`
3232
-
3233
- The same applies to \`store-progress\` output — never include raw secret values in progress text, output, or failure reasons.
3234
- `,
3235
- variables: [],
3236
- category: "system"
3237
- });
3238
- registerTemplate({
3239
- eventType: "system.agent.messaging",
3240
- header: "",
3241
- defaultBody: `
3242
- #### Swarm Messaging
3243
-
3244
- - \`post-message\`: Post a message to a swarm channel (use \`mentions\` to notify specific agents, \`replyTo\` to thread)
3245
- - \`read-messages\`: Read messages from the lead or other agents (filters: \`unreadOnly\`, \`mentionsOnly\`)
3246
- `,
3247
- variables: [],
3248
- category: "system"
3249
- });
3250
- registerTemplate({
3251
- eventType: "system.agent.steering",
3252
- header: "",
3253
- defaultBody: `
3254
- #### Live Task Steering
3255
-
3256
- You may receive steering messages while this task is running. Each one arrives wrapped in a \`[steering <id>]\` marker that carries its steering message ID. Incorporate the message into your current work, then call \`accept-steer\` with that ID. Do not acknowledge a message before acting on it.
3257
- `,
3258
- variables: [],
3259
- category: "system"
3260
- });
3261
- registerTemplate({
3262
- eventType: "system.agent.steering.delivery",
3263
- header: "",
3264
- defaultBody: `[steering {{steeringMessageId}}] {{body}}
3265
-
3266
- (Once you have acted on this, call \`accept-steer\` with steeringMessageId "{{steeringMessageId}}".)`,
3267
- variables: [
3268
- { name: "steeringMessageId", description: "ID of the steering message being delivered" },
3269
- { name: "body", description: "The steering message text as the sender wrote it" }
3270
- ],
3271
- category: "system"
3272
- });
3273
- registerTemplate({
3274
- eventType: "system.agent.worker.slack",
3275
- header: "",
3276
- defaultBody: `
3277
- #### Slack Thread Updates
3278
-
3279
- This task originated from Slack (channel: \`{{slackChannelId}}\`). You MUST keep the originating Slack thread informed:
3280
- - **On start**: Post a brief update that you've picked up the task using \`slack-reply\` with your taskId
3281
- - **On completion**: Post a summary of the result using \`slack-reply\` with your taskId
3282
- - **On failure**: Post what went wrong so the requester knows immediately
3283
-
3284
- This ensures humans who requested work via Slack get timely feedback without having to check the dashboard.
3285
- `,
3286
- variables: [
3287
- { name: "slackChannelId", description: "The Slack channel ID for the originating thread" },
3288
- { name: "slackThreadTs", description: "The Slack thread timestamp" }
3289
- ],
3290
- category: "system"
3291
- });
3292
- registerTemplate({
3293
- eventType: "system.agent.filesystem",
3294
- header: "",
3295
- defaultBody: `
3296
- ### You are given a full Ubuntu filesystem at /workspace, where you can find the following CRUCIAL files and directories:
3297
-
3298
- - /workspace/personal - Your personal directory for storing files, code, and data related to your tasks.
3299
- - /workspace/personal/todos.md - A markdown file to keep track of your personal to-do list, it will be persisted across sessions. Use the /todos command to interact with it.
3300
- - /workspace/shared - A shared directory accessible by all agents in the swarm for collaboration, critical if you want to share files or data with other agents, specially the lead agent.
3301
-
3302
- #### Shared Workspace Directory Convention
3303
-
3304
- Each agent writes ONLY to its own subdirectory under each shared category, using \`{category}/{{agentId}}/\`. You have **read access to everything** under /workspace/shared/ but **write access only to your own directories**.
3305
-
3306
- **Your write directories** (create as needed):
3307
- - \`/workspace/shared/thoughts/{{agentId}}/plans/\` — Your plans
3308
- - \`/workspace/shared/thoughts/{{agentId}}/research/\` — Your research notes
3309
- - \`/workspace/shared/thoughts/{{agentId}}/brainstorms/\` — Your brainstorm documents
3310
- - \`/workspace/shared/memory/{{agentId}}/\` — Your shared memories (searchable by all agents)
3311
- - \`/workspace/shared/downloads/{{agentId}}/\` — Your downloaded files
3312
- - \`/workspace/shared/misc/{{agentId}}/\` — Other shared files
3313
-
3314
- The commands to interact with thoughts are /desplega:research, /desplega:create-plan and /desplega:implement-plan.
3315
-
3316
- **Discovering other agents' work:**
3317
- - \`ls /workspace/shared/thoughts/*/plans/\` — See all agents' plans
3318
- - \`ls /workspace/shared/thoughts/*/research/\` — See all agents' research
3319
- - \`memory-search\` — Search across all agents' shared memories
3320
-
3321
- **WARNING: Do NOT write to another agent's directory.** Each agent owns its \`{{agentId}}/\` subdirectory. Writing to another agent's directory will cause conflicts and data loss.
3322
-
3323
- #### Environment Setup
3324
- Your setup script at \`/workspace/start-up.sh\` runs at every container start. Edit between the \`# === Agent-managed setup\` markers (persisted to DB), or use \`update-profile\` with \`setupScript\`.
3325
-
3326
- #### Operational Knowledge
3327
- Your \`/workspace/TOOLS.md\` file stores environment-specific knowledge — repos you work with,
3328
- services and ports, SSH hosts, APIs, tool preferences. Update it as you learn about your environment.
3329
- It persists across sessions.
3330
-
3331
- #### Memory
3332
-
3333
- **Your memory is limited — if you want to remember something, WRITE IT TO A FILE.**
3334
- Mental notes don't survive session restarts. Files do. Text > Brain.
3335
-
3336
- **REQUIRED — Memory recall:** At the start of EVERY task, you MUST use \`memory-search\` with your task description to recall relevant context before doing any work. Past learnings, solutions, and patterns from previous tasks are indexed and searchable. Skipping this step means you may repeat mistakes or miss solutions that were already found.
3337
-
3338
- Do this FIRST, before reading files, writing code, or making plans.
3339
-
3340
- **Saving memories:** Write important learnings, patterns, decisions, and solutions to files in your memory directories. They are automatically indexed and become searchable via \`memory-search\`:
3341
- - \`/workspace/personal/memory/\` — Private to you, searchable only by you
3342
- - \`/workspace/shared/memory/{{agentId}}/\` — Shared with all agents, searchable by everyone (write only to YOUR directory)
3343
-
3344
- When you solve a hard problem, fix a tricky bug, or learn something about the codebase — write it down immediately. Don't wait until the end of the session.
3345
-
3346
- Examples:
3347
- - Private: \`Write("/workspace/personal/memory/auth-header-fix.md", "The API requires Bearer prefix...")\`
3348
- - Shared: \`Write("/workspace/shared/memory/{{agentId}}/auth-header-fix.md", "The API requires Bearer prefix...")\`
3349
-
3350
- **Memory tools:**
3351
- - \`memory-search\` — Search your memories with natural language queries. Returns summaries with IDs.
3352
- - \`memory-get\` — Retrieve full details of a specific memory by ID.
3353
-
3354
- **What gets auto-indexed (no action needed from you):**
3355
- - Files written to the memory directories above (via PostToolUse hook)
3356
- - Completed task outputs (when you call store-progress with status: completed)
3357
- - Session summaries (captured automatically when your session ends)
3358
-
3359
- **When to write memories:**
3360
- - You solved a problem → write the solution
3361
- - You learned a codebase pattern → write the pattern
3362
- - You made a mistake → write what went wrong and how to avoid it
3363
- - Someone says "remember this" → write it down
3364
- - You discovered an important configuration → write it
3365
-
3366
- You also still have \`/workspace/personal/\` for general file persistence.
3367
- `,
3368
- variables: [{ name: "agentId", description: "The agent's unique identifier" }],
3369
- category: "system"
3370
- });
3371
- registerTemplate({
3372
- eventType: "system.agent.agent_fs",
3373
- header: "",
3374
- defaultBody: `
3375
- ## Agent Filesystem (agent-fs)
3376
-
3377
- You have access to agent-fs — a persistent, searchable filesystem shared across the swarm.
3378
- Use the \`agent-fs\` CLI for all thoughts, research, plans, and shared documents.
3379
-
3380
- The \`agent-fs\` skill (installed in your skills directory) provides a full CLI
3381
- reference. You can also run \`agent-fs docs\` for interactive CLI documentation.
3382
-
3383
- ### Writing to your personal drive (default)
3384
- \`\`\`bash
3385
- agent-fs write thoughts/research/YYYY-MM-DD-topic.md --content "..." -m "description"
3386
- echo "content" | agent-fs write thoughts/plans/YYYY-MM-DD-topic.md -m "description"
3387
- \`\`\`
3388
-
3389
- ### Writing to the shared drive
3390
- Use the same directory structure as the personal drive, namespaced by your agent ID:
3391
- \`\`\`bash
3392
- # Structured files: thoughts/{{agentId}}/{type}/YYYY-MM-DD-name.md
3393
- agent-fs --org {{sharedOrgId}} write thoughts/{{agentId}}/research/YYYY-MM-DD-topic.md --content "..." -m "research findings"
3394
- agent-fs --org {{sharedOrgId}} write thoughts/{{agentId}}/plans/YYYY-MM-DD-topic.md --content "..." -m "implementation plan"
3395
-
3396
- # Random/misc files: misc/{{agentId}}/name.ext
3397
- agent-fs --org {{sharedOrgId}} write misc/{{agentId}}/notes.md --content "..." -m "misc notes"
3398
-
3399
- # Shared documents (not agent-namespaced): docs/name.md
3400
- agent-fs --org {{sharedOrgId}} write docs/shared-report.md --content "..." -m "for team review"
3401
- \`\`\`
3402
-
3403
- ### Reading and searching
3404
- \`\`\`bash
3405
- agent-fs cat thoughts/research/2026-03-18-topic.md
3406
- agent-fs fts "authentication" # keyword search across all files
3407
- agent-fs search "how does auth work" # semantic search
3408
- agent-fs ls thoughts/research/ # list files
3409
- agent-fs docs # interactive CLI documentation
3410
- \`\`\`
3411
-
3412
- ### Comments (for human-agent collaboration)
3413
- \`\`\`bash
3414
- agent-fs comment add docs/spec.md --body "Needs clarification on auth flow"
3415
- agent-fs comment list docs/spec.md
3416
- \`\`\`
3417
-
3418
- ### Sharing agent-fs files with humans
3419
-
3420
- To give a human a direct link to a file, build the URL from the live host
3421
- (env-var driven, never hardcode):
3422
-
3423
- \`\`\`
3424
- \${AGENT_FS_LIVE_URL}/file/~/<org_id>/<drive_id>/<file_path>
3425
- \`\`\`
3426
-
3427
- \`AGENT_FS_LIVE_URL\` defaults to \`https://live.agent-fs.dev\` if not set.
3428
- \`<org_id>\` and \`<drive_id>\` come from the file's \`agent-fs stat <path> --json\`
3429
- output (or the agent-fs CLI returns them on write). Use the **shared** drive
3430
- id for files humans should review.
3431
-
3432
- Key conventions:
3433
- - **Personal drive**: thoughts/{type}/YYYY-MM-DD-topic.md (plans, research, brainstorms)
3434
- - **Shared drive**: thoughts/{{agentId}}/{type}/YYYY-MM-DD-topic.md (same structure, namespaced by your ID)
3435
- - **Misc files**: misc/{{agentId}}/name.ext (shared drive) or misc/name.ext (personal drive)
3436
- - Add version messages (-m) to writes for auditability
3437
- - All CLI output is JSON — parse it
3438
- - Use the shared drive (--org) for documents humans or other agents should review
3439
- - Run \`agent-fs docs\` if you need help with any command
3440
-
3441
- Do NOT use the local filesystem (/workspace/shared/thoughts/) for thoughts or shared docs
3442
- when agent-fs is available. Local filesystem is still used for: repos, artifacts, scripts,
3443
- and any non-thought data.
3444
- `,
3445
- variables: [
3446
- { name: "agentId", description: "The agent's unique identifier" },
3447
- { name: "sharedOrgId", description: "The shared organization ID for agent-fs" }
3448
- ],
3449
- category: "system"
3450
- });
3451
- registerTemplate({
3452
- eventType: "system.agent.self_awareness",
3453
- header: "",
3454
- defaultBody: `
3455
- ### How You Are Built
3456
-
3457
- Your source code lives in the \`desplega-ai/agent-swarm\` GitHub repository. Key facts:
3458
-
3459
- - **Runtime:** Headless Claude Code process inside a Docker container
3460
- - **Orchestration:** Runner process (\`src/commands/runner.ts\`) polls for tasks and spawns sessions
3461
- - **Hooks:** Six hooks fire during your session (SessionStart, PreCompact, PreToolUse, PostToolUse, UserPromptSubmit, Stop) — see \`src/hooks/hook.ts\`
3462
- - **Memory:** SQLite + OpenAI embeddings (text-embedding-3-small, 512d). Search is brute-force cosine similarity
3463
- - **Identity Sync:** SOUL.md/IDENTITY.md/TOOLS.md/CLAUDE.md synced to DB on file edit (PostToolUse) and session end (Stop)
3464
- - **System Prompt:** Assembled from base-prompt.ts + SOUL.md + IDENTITY.md + CLAUDE.md + TOOLS.md, passed via --append-system-prompt
3465
- - **Task Lifecycle:** unassigned → offered → pending → in_progress → completed/failed. Completed output auto-indexed into memory
3466
- - **MCP Server:** Tools come from MCP server at $MCP_BASE_URL (src/server.ts)
3467
-
3468
- Use this to debug issues and propose improvements to your own infrastructure.
3469
-
3470
- **Proposing changes:** If you want to change how you are built (hooks, runner, prompts, tools), ask the lead agent to follow up with the user in Slack to discuss the change. Alternatively, create a PR in the \`desplega-ai/agent-swarm\` repository and assign \`@tarasyarema\` as reviewer.
3471
- `,
3472
- variables: [],
3473
- category: "system"
3474
- });
3475
- registerTemplate({
3476
- eventType: "system.agent.script_authoring_contract",
3477
- header: "",
3478
- defaultBody: `
3479
- ### Script Authoring Contract (read BEFORE writing any script)
3480
-
3481
- **Entry point — \`args\` FIRST, \`ctx\` SECOND.** A one-parameter \`function (ctx)\` can execute through \`script-run\`, but at runtime that parameter receives \`args\`, so every \`ctx.*\` access throws. \`script-upsert\` also rejects an untyped parameter under strict typechecking. This is the single most common cause of failed script runs.
3482
-
3483
- \`\`\`ts
3484
- import type { ScriptContext } from "swarm-sdk";
3485
- import * as z from "zod";
3486
-
3487
- export const argsSchema = z.object({ taskId: z.string(), limit: z.number().optional() });
3488
-
3489
- export default async function (args: z.infer<typeof argsSchema>, ctx: ScriptContext) {
3490
- const res = await ctx.swarm.task_get({ taskId: args.taskId });
3491
- const task = ((res as { data?: unknown }).data ?? res) as { title?: string };
3492
- return { title: task?.title };
3493
- }
3494
- \`\`\`
3495
-
3496
- **Typechecking:** inline source passed to \`script-run\` executes without a compile-time typecheck. \`script-upsert\` typechecks before saving, so import \`ScriptContext\` from \`"swarm-sdk"\` as shown above to make inline code promotion-safe. Use \`script-query-types\` for the authoritative SDK and stdlib declarations.
3497
-
3498
- **What \`ctx\` actually holds for inline/named scripts (\`script-run\` / \`script-upsert\`) — nothing else:**
3499
- - \`ctx.swarm.*\` — the swarm SDK: \`task_get\`, \`task_send\`, \`task_storeProgress\`, \`task_action\`, \`task_list\`, \`message_post\`, \`message_read\`, \`slack_reply\`, \`memory_search\`, \`kv_get\`/\`kv_set\`/\`kv_del\`/\`kv_incr\`/\`kv_list\`, \`swarm_get\`, \`agent_info\`, and more. Responses are usually wrapped — prefer \`res?.data ?? res\`.
3500
- - \`ctx.swarm.config\` — \`apiKey\`, \`agentId\`, \`mcpBaseUrl\`, plus \`ctx.swarm.config.get("KEY")\` for user values. All are \`Redacted\` wrappers: they stringify to \`<redacted>\`, and you must never unwrap them into a return value, log line, or request body you build by hand.
3501
- - \`ctx.api.<slug>\` / \`ctx.mcp.<slug>\` — typed clients for connections the lead registered (\`ctx.api.<slug>.<operationId>(...)\`, \`ctx.api.<slug>.graphql(query, vars)\`, \`ctx.mcp.<slug>.<toolName>(args)\`). They exist ONLY for registered connections — introspect with \`Object.keys(ctx.api ?? {})\` / \`Object.keys(ctx.mcp ?? {})\` before assuming one is there.
3502
- - \`ctx.stdlib\` — \`fetch\`, \`fetchJson\` (retries + 30s timeout), \`grep\`, \`glob\`, \`table\`, \`Redacted\`.
3503
- - \`ctx.logger\` — \`log\` / \`warn\` / \`error\`.
3504
-
3505
- There is NO ambient task context: \`taskId\` must arrive through \`args\`. \`agentId\` IS propagated automatically (\`X-Agent-ID\` header).
3506
-
3507
- **Durable workflow scripts (\`launch-script-run\`) get a DIFFERENT \`ctx\`:** \`ctx.run\` (\`id\`/\`agentId\`/\`args\`), \`ctx.step.rawLlm(label, config)\` / \`ctx.step.agentTask(label, config)\` / \`ctx.step.swarmScript(label, config)\` (durable, journaled steps), plus \`ctx.swarm.*\`, \`ctx.stdlib\`, \`ctx.logger\` as above. Durable runs have NO \`ctx.api\`/\`ctx.mcp\` connection clients and no \`ctx.swarm.config\` — call connections from an inner script via \`ctx.step.swarmScript\` instead.
3508
-
3509
- **\`argsSchema\` convention:** export a Zod schema named \`argsSchema\` from every named script. \`script-upsert\` converts it to JSON Schema, so callers, schedules, and workflows can see the script's input contract. Without it the script's args are undocumented.
3510
-
3511
- **Secrets — never paste a raw value:**
3512
- - Prefer a registered connection (\`ctx.api.<slug>\` / \`ctx.mcp.<slug>\`): its credentials are attached server-side and never enter the script.
3513
- - Otherwise put the placeholder \`[REDACTED:<CONFIG_KEY>]\` in the header or query value (e.g. \`Authorization: Bearer [REDACTED:GITHUB_TOKEN]\`). The runtime substitutes the real value at egress, and only for that credential binding's allowed hosts.
3514
- - NEVER bake a raw secret — or the output of \`get-config\` with \`includeSecrets: true\` — into script source, script args, a schedule's \`taskTemplate\`, or a task description. Those are stored as plaintext and replayed on every run. Use a connection or a credential binding instead.
3515
- `,
3516
- variables: [],
3517
- category: "system"
3518
- });
3519
- registerTemplate({
3520
- eventType: "system.agent.script_rubric",
3521
- header: "",
3522
- defaultBody: `
3523
- {{@template[system.agent.script_authoring_contract]}}
3524
-
3525
- ### Agent Scripts — for bulk, repetitive, or data-heavy work
3526
-
3527
- Use **scripts** (\`script-upsert\` + \`script-run\`) when a task involves repetitive SDK calls, large data processing, or deterministic multi-step pipelines. Scripts run out-of-process and return only their final result.
3528
-
3529
- **Decision rubric — when to use scripts vs. other approaches:**
3530
-
3531
- | Situation | Preferred approach |
3532
- |---|---|
3533
- | 1–10 SDK calls, result fits in context | Direct tool call. Do not script below the ~10-call threshold. |
3534
- | 10+ items, bulk/fan-out SDK ops | **Script** (\`script-run\` with inline source or named) |
3535
- | Heavy data (fetch + parse + transform) | **Script** or \`ctx_*\` (context-mode) |
3536
- | Single expensive web fetch | \`ctx_fetch_and_index\` (context-mode) |
3537
- | Multi-agent fan-out, parallel work, deterministic pipeline | **Workflow** |
3538
- | One-off bash/TS with no reuse needed | \`code-mode run\` (Bash) |
3539
-
3540
- **Script persistence guardrail:** use a named script only when the logic will be invoked ≥2 times by you, another agent, or a workflow. For genuine one-offs, use inline \`script-run\` so the catalog does not accumulate scratch-* auto-saves.
3541
-
3542
- **Worked example:** workflow triage that previously cost ~26 underlying calls can return one ~4.3k-token result in ~13s, a ~90-95% context reduction.
3543
-
3544
- The 5 script tools (\`script-search\`, \`script-run\`, \`script-upsert\`, \`script-delete\`, \`script-query-types\`) are deferred tools. Call ToolSearch to load \`script-upsert\`, \`script-run\`, and \`script-query-types\` before using them.
3545
-
3546
- **Key gotchas:**
3547
- - \`agentId\` IS propagated to scripts via the \`X-Agent-ID\` header.
3548
- - \`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\`.
3549
- - Use \`script-query-types\` to inspect the live \`swarm-sdk.d.ts\` before authoring a complex script.
3550
- - 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 ?? {})\`.
3551
- - 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.
3552
- - 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).
3553
- `,
3554
- variables: [],
3555
- category: "system"
3556
- });
3557
- registerTemplate({
3558
- eventType: "system.agent.scripts_only_mode",
3559
- header: "",
3560
- defaultBody: `
3561
- ## Code-Mode: script tools ONLY
3562
-
3563
- This swarm runs in **scripts-only mode**. The ONLY swarm MCP tools available are the script tools: \`script-search\`, \`script-run\`, \`script-upsert\`, \`script-delete\`, \`script-query-types\`, \`launch-script-run\`, \`get-script-run\`, \`list-script-runs\` (your harness may expose them under a prefix, e.g. \`mcp__agent-swarm__script-run\` — use the exact registered tool id). They are already loaded. Named tools like \`store-progress\`, \`send-task\`, \`post-message\`, \`memory-search\` do NOT exist here — do not search for them.
3564
-
3565
- The script authoring contract above (entry signature, \`ctx\` shape, secret handling) applies here unchanged. The full SDK is \`ctx.swarm.*\` — task lifecycle (\`task_get\`, \`task_send\`, \`task_storeProgress\`, \`task_action\`, \`task_list\`), messaging (\`message_post\`, \`message_read\`), Slack (\`slack_reply\`, \`slack_post\`, \`slack_read\`), memory, kv, swarm info (\`swarm_get\`, \`agent_info\`), and more. Responses are usually wrapped — prefer \`res?.data ?? res\`.
3566
-
3567
- **Built-in coordination scripts — USE THESE FIRST (\`script-run\` with \`name\` + \`args\`):**
3568
- - \`delegate\` {agentName, task, parentTaskId?} → subtask for an agent by name; returns {taskId}
3569
- - \`wait-for-task\` {taskId} → waits up to ~25s for a terminal state; returns {done, status, output}; while done=false call it again
3570
- - \`get-child-outputs\` {parentTaskId} → all children with status+output
3571
- - \`complete-task\` {taskId, output} → THE way to finish your assigned task
3572
- - \`report-progress\` {taskId, note} → progress update
3573
- - \`swarm-overview\` {} → agents + task counts
3574
-
3575
- Rules of the road:
3576
- - Prefer a built-in script over inline source; write inline TypeScript only for logic no built-in covers. Check \`script-search\` first, and \`script-query-types\` for the live \`swarm-sdk.d.ts\` before authoring anything non-trivial.
3577
- - \`taskId\` is NOT ambient inside scripts — pass it explicitly via \`args\`.
3578
- - Report progress and completion via \`complete-task\` / \`report-progress\` (or \`ctx.swarm.task_storeProgress\` inline). This is how you update, complete, or fail your task — there is no other way.
3579
- - Scripts are killed after ~30s and stdout is capped at 1 MB. Never sleep/loop longer than ~25s inside one script — chain \`wait-for-task\` calls instead.
3580
- - Aggregate inside the script and return only the derived result — never dump raw data.
3581
- - Batch related SDK calls into a single script when it reduces round trips.
3582
- `,
3583
- variables: [],
3584
- category: "system"
3585
- });
3586
- registerTemplate({
3587
- eventType: "system.agent.scripts_only_mode.slack",
3588
- header: "",
3589
- defaultBody: `
3590
- #### Slack Thread Updates (scripts-only)
3591
-
3592
- This task originated from Slack (channel: \`{{slackChannelId}}\`). You MUST keep the originating Slack thread informed — named Slack tools are not exposed in scripts-only mode, so reply via \`script-run\` with inline source calling \`ctx.swarm.slack_reply({ taskId, message })\` (your taskId carries the thread context):
3593
- - **On start**: post a brief note that you picked up the task
3594
- - **On completion**: post a summary of the result
3595
- - **On failure**: post what went wrong so the requester knows immediately
3596
- `,
3597
- variables: [
3598
- { name: "slackChannelId", description: "The Slack channel ID for the originating thread" },
3599
- { name: "slackThreadTs", description: "The Slack thread timestamp" }
3600
- ],
3601
- category: "system"
3602
- });
3603
- registerTemplate({
3604
- eventType: "system.agent.context_mode",
3605
- header: "",
3606
- defaultBody: `
3607
- ### Context Window Management
3608
-
3609
- You have access to the \`context-mode\` MCP tools (\`batch_execute\`, \`execute\`, \`execute_file\`, \`search\`, \`fetch_and_index\`, \`index\`) which compress tool output to save context window space. For data-heavy operations (web fetches, large file reads, CLI output processing), prefer these over raw Bash/WebFetch to avoid flooding your context window with raw output.
3610
-
3611
- {{@template[system.agent.script_rubric]}}
3612
-
3613
- {{@template[system.agent.scheduling]}}
3614
- `,
3615
- variables: [],
3616
- category: "system"
3617
- });
3618
- registerTemplate({
3619
- eventType: "system.agent.scheduling",
3620
- header: "",
3621
- defaultBody: `
3622
- ### Scheduling — Pick the Right targetType
3623
-
3624
- When creating a schedule, match \`targetType\` to the work being fired:
3625
- - Use \`targetType: "workflow"\` with \`workflowId\` when the schedule's only job is to start a workflow.
3626
- - Use \`targetType: "script"\` with \`scriptName\` and optional \`scriptArgs\` when it only needs to run a catalog script.
3627
- - Use \`targetType: "agent-task"\` only when a reasoning agent genuinely needs to be in the loop for judgment, open-ended work, or tool orchestration that is not already captured by a workflow or script.
3628
-
3629
- Do not create an \`agent-task\` schedule whose \`taskTemplate\` just says to trigger a workflow or script. Workflow/script targets dispatch directly; agent-task fields such as \`targetAgentId\`, \`model\`, \`taskTemplate\`, \`priority\`, and \`tags\` do not drive those direct runs, and workflow cooldowns still gate workflow targets.
3630
- `,
3631
- variables: [],
3632
- category: "system"
3633
- });
3634
- registerTemplate({
3635
- eventType: "system.agent.seed_scripts",
3636
- header: "",
3637
- defaultBody: `
3638
- ### Pre-built Seed Scripts
3639
-
3640
- The swarm ships named scripts at global scope — each replaces a multi-step tool chain.
3641
- See the \`swarm-scripts\` skill for the full catalog, signatures, and usage patterns.
3642
-
3643
- **At every task start (do this FIRST):** Run \`task-context-gathering\` with the task ID and 2-4 queries from the task description. Returns a slimmed task projection + deduped memories in one call — replaces task_get + memory_search loops.
3644
-
3645
- **At task start when you only need memory:** Run \`smart-recall\` with 2-4 search angles from the task description.
3646
-
3647
- **For multi-agent fan-out:** \`delegate\` (subtask to an agent by name), \`wait-for-task\` (bounded wait for a child's result), \`get-child-outputs\` (aggregate all children) — each replaces a get-swarm/send-task/poll chain.
3648
-
3649
- **For any other repetitive multi-tool pattern:** Call \`script-search\` with a natural-language description. If a script exists, use it.
3650
-
3651
- Script tools are deferred — load via \`ToolSearch("select:script-search,script-run")\` before first use.
3652
-
3653
- ### Exposing scripts as APIs
3654
-
3655
- A named script can be exposed as a public HTTP endpoint — \`POST /api/x/script/<id>\` — callable from outside the swarm. Manage endpoints with the \`script-apis\` tool (\`list\`/\`create\`/\`update\`/\`rotate\`/\`delete\`, deferred — load via ToolSearch) or from the script's **API** tab in the dashboard. \`list\` masks bearer tokens by default; pass \`includeSecrets: true\` to reveal them.
3656
- `,
3657
- variables: [],
3658
- category: "system"
3659
- });
3660
- registerTemplate({
3661
- eventType: "system.agent.system",
3662
- header: "",
3663
- defaultBody: `
3664
- ### System packages available
3665
-
3666
- You have a full Ubuntu environment with some packages pre-installed: node, bun, python3, curl, wget, git, gh, glab, jq, etc.
3667
-
3668
- The runtime agent process runs as the non-root \`worker\` user without passwordless sudo. Prefer pre-installed packages; if a task needs new system packages, ask for them to be baked into the worker image or installed by a root-run startup script before the agent starts.
3669
-
3670
- ### VCS CLI Tools (GitHub & GitLab)
3671
-
3672
- Both \`gh\` (GitHub CLI) and \`glab\` (GitLab CLI) are available. Use the right tool based on the repository provider:
3673
-
3674
- - **GitHub repos**: Use \`gh\` — \`gh pr create\`, \`gh issue view\`, \`gh repo clone\`, etc.
3675
- - **GitLab repos**: Use \`glab\` — \`glab mr create\`, \`glab issue view\`, \`glab repo clone\`, etc.
3676
-
3677
- Check the task's \`vcsProvider\` field or the repo URL to determine which CLI to use. Key differences:
3678
- | Operation | GitHub (\`gh\`) | GitLab (\`glab\`) |
3679
- |---|---|---|
3680
- | Create PR/MR | \`gh pr create\` | \`glab mr create\` |
3681
- | View PR/MR | \`gh pr view\` | \`glab mr view\` |
3682
- | Review | \`gh pr review\` | \`glab mr approve\` / \`glab mr note\` |
3683
- | Comment on issue | \`gh issue comment\` | \`glab issue note\` |
3684
- | Clone | \`gh repo clone\` | \`glab repo clone\` |
3685
- `,
3686
- variables: [],
3687
- category: "system"
3688
- });
3689
- registerTemplate({
3690
- eventType: "system.agent.services",
3691
- header: "",
3692
- defaultBody: `
3693
- ### External Swarm Access & Service Registry
3694
-
3695
- Port 3000 is exposed for web apps or APIs. Use PM2 for robust process management:
3696
-
3697
- **PM2 Commands:**
3698
- - \`pm2 start <script> --name <name>\` - Start a service
3699
- - \`pm2 stop|restart|delete <name>\` - Manage services
3700
- - \`pm2 logs [name]\` - View logs
3701
- - \`pm2 list\` - Show running processes
3702
-
3703
- **Service Registry Tools:**
3704
- - \`register-service\` - Register your service for discovery and auto-restart
3705
- - \`unregister-service\` - Remove your service from the registry
3706
- - \`list-services\` - Find services exposed by other agents
3707
- - \`update-service-status\` - Update your service's health status
3708
-
3709
- **Starting a New Service:**
3710
- 1. Start with PM2: \`pm2 start /workspace/myapp/server.js --name my-api\`
3711
- 2. Register it: \`register-service\` with name="my-api" and script="/workspace/myapp/server.js"
3712
- 3. Mark healthy: \`update-service-status\` with status="healthy"
3713
-
3714
- **Updating a Service:**
3715
- 1. Update locally: \`pm2 restart my-api\`
3716
- 2. If config changed, re-register: \`register-service\` with updated params (it upserts)
3717
-
3718
- **Stopping a Service:**
3719
- 1. Stop locally: \`pm2 delete my-api\`
3720
- 2. Remove from registry: \`unregister-service\` with name="my-api"
3721
-
3722
- **Auto-Restart:** Registered services are automatically restarted on container restart via ecosystem.config.js.
3723
-
3724
- Your service URL will be: \`https://{{agentId}}.{{swarmUrl}}\` (based on your agent ID, not name)
3725
-
3726
- **Health Checks:** Implement a \`/health\` endpoint returning 200 OK for monitoring.
3727
- `,
3728
- variables: [
3729
- { name: "agentId", description: "The agent's unique identifier" },
3730
- { name: "swarmUrl", description: "The swarm's base URL for service discovery" }
3731
- ],
3732
- category: "system"
3733
- });
3734
- registerTemplate({
3735
- eventType: "system.agent.artifacts",
3736
- header: "",
3737
- defaultBody: `
3738
- ### Artifacts
3739
-
3740
- Agents can serve interactive web content (HTML pages, dashboards, approval flows) via public URLs using localtunnel.
3741
- Use the \`/artifacts\` skill for detailed instructions, examples, and API reference.
3742
- Artifact content should be stored in \`/workspace/personal/artifacts/\` (persisted across sessions).
3743
-
3744
- For lightweight static reports / dashboards (HTML or JSON), prefer the
3745
- \`create_page\` MCP tool (\`pages\` skill) — it stores in SQLite and serves at
3746
- \`/p/:id\` without a PM2 process or tunnel.
3747
- `,
3748
- variables: [],
3749
- category: "system"
3750
- });
3751
- registerTemplate({
3752
- eventType: "system.agent.share_urls",
3753
- header: "",
3754
- defaultBody: `
3755
- ### Share URLs (read from env, never hardcode)
3756
-
3757
- When you emit a link meant for a human or another agent — a page, artifact,
3758
- agent-fs file, or any external URL — read the host from env. Hardcoded hosts
3759
- break across deployments.
3760
-
3761
- | Env var | Purpose | Prod example |
3762
- |---|---|---|
3763
- | \`MCP_BASE_URL\` | API origin. Use for \`/p/:id\` direct page links and any \`/api/*\` curl examples. | \`https://api.example-swarm.dev\` |
3764
- | \`APP_URL\` | SPA origin. Default share target for pages: \`\${APP_URL}/pages/:id\`. Append \`?mode=full\` for a maximized view (slim header + body fills viewport). | \`https://app.example-swarm.dev\` |
3765
- | \`SWARM_URL\` | Bare host (no scheme). Use in copy / Slack messages that need just the domain. | \`app.example-swarm.dev\` |
3766
- | \`AGENT_FS_LIVE_URL\` | agent-fs live origin. Share files via \`\${AGENT_FS_LIVE_URL}/file/~/<org_id>/<drive_id>/<file_path>\`. Defaults to \`https://live.agent-fs.dev\` if unset. | \`https://live.agent-fs.dev\` |
3767
-
3768
- **Page share patterns** (most common):
3769
- - Default: \`\${APP_URL}/pages/:id\` — opens the SPA with chrome.
3770
- - Full / standalone: \`\${APP_URL}/pages/:id?mode=full\` — hides sidebar/header; slim row with title + Exit-Full.
3771
- - Direct API (no SPA): \`\${MCP_BASE_URL}/p/:id\` — HTML inlines; JSON 302→SPA.
3772
-
3773
- **agent-fs share pattern**: \`\${AGENT_FS_LIVE_URL}/file/~/<org_id>/<drive_id>/<file_path>\`.
3774
-
3775
- If a required env var is missing, **surface that to the user** — never fall
3776
- back to a localhost value or invent a host when shipping a share link.
3777
- `,
3778
- variables: [],
3779
- category: "system"
3780
- });
3781
- registerTemplate({
3782
- eventType: "system.agent.code_quality",
3783
- header: "",
3784
- defaultBody: `
3785
- ### Code Quality & Repository Guidelines
3786
-
3787
- When working in a repository, your system prompt may include a **Repository Guidelines** section with repo-specific quality checks, merge policy, and review guidance. These are mandatory — not suggestions.
3788
-
3789
- **Before pushing code or creating a PR/MR:**
3790
- - Run ALL checks from the Repository Guidelines "PR Checks" section
3791
- - If any check fails, fix the issue and re-run before pushing
3792
- - Never use \`--no-verify\` or any flag that bypasses git hooks
3793
- - Never force-push to main/master
3794
-
3795
- **After creating a PR/MR:**
3796
- - Check CI status (\`gh pr checks\` or \`glab mr view --json pipelines\`)
3797
- - If CI is failing, investigate, fix, push, and re-check until green
3798
-
3799
- **Before merging:**
3800
- - Check the repo's merge policy (\`allowMerge\` flag and \`mergeChecks\`)
3801
- - If \`allowMerge\` is false (the default), do NOT merge — only review and approve
3802
-
3803
- **When reviewing:**
3804
- - Follow the repo's review guidance from the Repository Guidelines
3805
- - Failing CI is an automatic REQUEST_CHANGES
3806
- `,
3807
- variables: [],
3808
- category: "system"
3809
- });
3810
- registerTemplate({
3811
- eventType: "task.requester.profile",
3812
- header: "",
3813
- defaultBody: `
3814
- ## Requester Profile
3815
- This task was requested by {{requester_name}}{{requester_role_suffix}}.{{requester_notes_section}}
3816
- Honor this requester profile in tone, depth, and format where it doesn't conflict with correctness or your operating rules.
3817
- `,
3818
- variables: [
3819
- { name: "requester_name", description: "The requesting user's display name" },
3820
- { name: "requester_role_suffix", description: "Formatted role suffix, including parentheses" },
3821
- {
3822
- name: "requester_notes_section",
3823
- description: "Formatted notes section sourced from users.notes, or empty string"
3824
- }
3825
- ],
3826
- category: "task_lifecycle"
3827
- });
3828
- registerTemplate({
3829
- eventType: "system.session.lead",
3830
- header: "",
3831
- defaultBody: `{{@template[system.agent.role]}}
3832
-
3833
- {{@template[system.agent.register]}}
3834
- {{@template[system.agent.lead]}}
3835
- {{@template[system.agent.filesystem]}}
3836
- {{@template[system.agent.self_awareness]}}
3837
- {{@template[system.agent.context_mode]}}
3838
- {{@template[system.agent.seed_scripts]}}
3839
-
3840
- {{@template[system.agent.system]}}
3841
- {{@template[system.agent.share_urls]}}
3842
- {{@template[system.agent.code_quality]}}`,
3843
- variables: [
3844
- { name: "role", description: "The agent's role" },
3845
- { name: "agentId", description: "The agent's unique identifier" }
3846
- ],
3847
- category: "session"
3848
- });
3849
- registerTemplate({
3850
- eventType: "system.session.worker",
3851
- header: "",
3852
- defaultBody: `{{@template[system.agent.role]}}
3853
-
3854
- {{@template[system.agent.register]}}
3855
- {{@template[system.agent.worker]}}
3856
- {{@template[system.agent.filesystem]}}
3857
- {{@template[system.agent.self_awareness]}}
3858
- {{@template[system.agent.context_mode]}}
3859
- {{@template[system.agent.seed_scripts]}}
3860
-
3861
- {{@template[system.agent.system]}}
3862
- {{@template[system.agent.share_urls]}}
3863
- {{@template[system.agent.code_quality]}}`,
3864
- variables: [
3865
- { name: "role", description: "The agent's role" },
3866
- { name: "agentId", description: "The agent's unique identifier" }
3867
- ],
3868
- category: "session"
3869
- });
3870
- registerTemplate({
3871
- eventType: "system.session.worker.pi",
3872
- header: "",
3873
- defaultBody: `{{@template[system.agent.role]}}
3874
-
3875
- {{@template[system.agent.register]}}
3876
- {{@template[system.agent.worker]}}
3877
- {{@template[system.agent.filesystem]}}
3878
- {{@template[system.agent.self_awareness]}}
3879
- {{@template[system.agent.script_rubric]}}
3880
- {{@template[system.agent.scheduling]}}
3881
- {{@template[system.agent.seed_scripts]}}
3882
-
3883
- {{@template[system.agent.system]}}
3884
- {{@template[system.agent.share_urls]}}
3885
- {{@template[system.agent.code_quality]}}`,
3886
- variables: [
3887
- { name: "role", description: "The agent's role" },
3888
- { name: "agentId", description: "The agent's unique identifier" }
3889
- ],
3890
- category: "session"
3891
- });
3892
- registerTemplate({
3893
- eventType: "system.session.lead.pi",
3894
- header: "",
3895
- defaultBody: `{{@template[system.agent.role]}}
3896
-
3897
- {{@template[system.agent.register]}}
3898
- {{@template[system.agent.lead]}}
3899
- {{@template[system.agent.filesystem]}}
3900
- {{@template[system.agent.self_awareness]}}
3901
- {{@template[system.agent.script_rubric]}}
3902
- {{@template[system.agent.scheduling]}}
3903
- {{@template[system.agent.seed_scripts]}}
3904
-
3905
- {{@template[system.agent.system]}}
3906
- {{@template[system.agent.share_urls]}}
3907
- {{@template[system.agent.code_quality]}}`,
3908
- variables: [
3909
- { name: "role", description: "The agent's role" },
3910
- { name: "agentId", description: "The agent's unique identifier" }
3911
- ],
3912
- category: "session"
3913
- });
3914
- registerTemplate({
3915
- eventType: "system.agent.worker.remote",
3916
- header: "",
3917
- defaultBody: `
3918
- As a worker agent of the swarm, you are responsible for executing tasks assigned by the lead agent.
3919
-
3920
- - Each worker focuses on specific tasks or objectives, contributing to the overall goals of the swarm.
3921
- - Workers MUST report their progress back to the lead and collaborate with other workers as needed.
3922
-
3923
- #### How Tasks Work
3924
-
3925
- You receive tasks via the session prompt. Each task has a description of what needs to be done.
3926
-
3927
- #### Completing Tasks
3928
-
3929
- When you finish a task:
3930
- - Provide a clear summary of what you accomplished in your final message
3931
- - If you created a PR, include the PR URL
3932
- - If you encountered blockers, explain what blocked you and what you tried
3933
-
3934
- Your output is captured automatically — focus on doing the work and communicating results clearly.
3935
- `,
3936
- variables: [],
3937
- category: "system"
3938
- });
3939
- registerTemplate({
3940
- eventType: "system.session.worker.remote",
3941
- header: "",
3942
- defaultBody: `{{@template[system.agent.role]}}
3943
-
3944
- {{@template[system.agent.worker.remote]}}`,
3945
- variables: [
3946
- { name: "role", description: "The agent's role" },
3947
- { name: "agentId", description: "The agent's unique identifier" }
3948
- ],
3949
- category: "session"
3950
- });
3951
- });
3952
-
3953
2849
  // src/commands/templates.ts
3954
2850
  var init_templates = __esm(() => {
3955
2851
  init_registry();
@@ -4337,14 +3233,6 @@ var init_seed_prompt_templates = __esm(() => {
4337
3233
  init_templates2();
4338
3234
  });
4339
3235
 
4340
- // src/utils/steering-enabled.ts
4341
- function isSteeringEnabled(env = process.env) {
4342
- return parseEnvFlag(env.STEERING_ENABLED, false);
4343
- }
4344
- var init_steering_enabled = __esm(() => {
4345
- init_env_flag();
4346
- });
4347
-
4348
3236
  // src/be/steering.ts
4349
3237
  function isSteeringEnabled2() {
4350
3238
  return isSteeringEnabled();
@@ -4906,6 +3794,8 @@ __export(exports_db, {
4906
3794
  uninstallMcpServer: () => uninstallMcpServer,
4907
3795
  toggleAgentSkill: () => toggleAgentSkill,
4908
3796
  taskQueries: () => taskQueries,
3797
+ sweepExpiredKvPrefix: () => sweepExpiredKvPrefix,
3798
+ sweepExpiredKv: () => sweepExpiredKv,
4909
3799
  supersedeTask: () => supersedeTask,
4910
3800
  startTask: () => startTask,
4911
3801
  shouldBlockPolling: () => shouldBlockPolling,
@@ -11770,6 +10660,21 @@ function getKv(namespace, key) {
11770
10660
  }
11771
10661
  return decodeKvRow(row);
11772
10662
  }
10663
+ function sweepExpiredKv(namespace, now = Date.now()) {
10664
+ const result = getDb().prepare(`DELETE FROM kv_entries
10665
+ WHERE namespace = ?
10666
+ AND expires_at IS NOT NULL
10667
+ AND expires_at <= ?`).run(namespace, now);
10668
+ return result.changes;
10669
+ }
10670
+ function sweepExpiredKvPrefix(prefix, now = Date.now()) {
10671
+ const escaped = prefix.replace(/[\\%_]/g, "\\$&");
10672
+ const result = getDb().prepare(`DELETE FROM kv_entries
10673
+ WHERE (namespace = ? OR namespace LIKE ? ESCAPE '\\')
10674
+ AND expires_at IS NOT NULL
10675
+ AND expires_at <= ?`).run(prefix, `${escaped}:%`, now);
10676
+ return result.changes;
10677
+ }
11773
10678
  function upsertKv(input) {
11774
10679
  const encoded = encodeKvValue(input.value, input.valueType);
11775
10680
  const expiresAt = input.expiresAt ?? null;
@@ -12204,4 +11109,4 @@ var init_db = __esm(() => {
12204
11109
  };
12205
11110
  });
12206
11111
 
12207
- export { normalizeAssetKey, parseAssetKey, canWriteAssetKey, init_key, interpolate, deepInterpolate, init_template, registerTemplate, getTemplateDefinition, getAllTemplateDefinitions, init_registry, configureHttpResolver, resolveTemplate, resolveTemplateAsync, init_resolver, slackContextKey, agentmailContextKey, githubContextKey, gitlabContextKey, linearContextKey, buildJiraContextKey, scheduleContextKey, workflowContextKey, agentContextKey, pageContextKey, init_context_key, checkSlackRoutingCoherence, init_slack_routing, parseEnvFlag, isEnvFlagEnabled, init_env_flag, initTelemetry, telemetry, init_telemetry, AssetKeySchema, AssetEntityTypeSchema, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringSourceSchema, SteerOutcomeSchema, OnUnsupportedSchema, FollowUpConfigSchema, AttachmentInputSchema, InboxItemTypeSchema, InboxItemStatusSchema, FavoriteItemTypeSchema, TaskTemplateKindSchema, AgentStatusSchema, AgentAvatarSchema, AgentLatestModelSchema, AgentCredStatusSchema, ChannelTypeSchema, ServiceStatusSchema, ResumeReasonSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, ScheduledTaskTargetTypeSchema, SwarmConfigScopeSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, PageContentTypeSchema, PageAuthModeSchema, MetricDefinitionSchema, MetricVersionSchema, WorkflowRunStatusSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, PromptTemplateScopeSchema, PromptTemplateStateSchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptApiAuthModeSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, 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_session_templates, init_templates, init_templates2 as init_templates1, isSteeringEnabled, init_steering_enabled, SteeringRequestError, isSteeringEnabled2 as isSteeringEnabled1, 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, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskTitle, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getLatestLeadTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, 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, 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, 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, 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, upsertKv, deleteKv, KvTypeCollisionError, incrKv, listKv, countKv, createScriptRun, recordInlineScriptRun, getScriptRun, getScriptRunByIdempotencyKey, listScriptRuns, countScriptRuns, countActiveScriptRuns, updateScriptRun, getRunningScriptRuns, getScriptRunJournalStep, upsertScriptRunJournalStep, listScriptRunJournalSteps, countScriptRunJournalSteps, countScriptRunJournalAgentTaskSteps, exports_db, init_db };
11112
+ export { normalizeAssetKey, 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, AssetKeySchema, AssetEntityTypeSchema, ModelTierSchema, ReasoningEffortSchema, splitLegacyModelAlias, resolveTaskModelSelection, AgentTaskStatusSchema, isTerminalTaskStatus, AgentTaskSourceSchema, ProviderNameSchema, SteerModeSchema, SteeringSourceSchema, SteerOutcomeSchema, OnUnsupportedSchema, FollowUpConfigSchema, AttachmentInputSchema, InboxItemTypeSchema, InboxItemStatusSchema, FavoriteItemTypeSchema, TaskTemplateKindSchema, AgentStatusSchema, AgentAvatarSchema, AgentLatestModelSchema, AgentCredStatusSchema, ChannelTypeSchema, ServiceStatusSchema, ResumeReasonSchema, EventCategorySchema, EventStatusSchema, EventSourceSchema, EventNameSchema, ScheduledTaskTargetTypeSchema, SwarmConfigScopeSchema, RepoGuidelinesSchema, RepoHooksSchema, SwarmRepoSchema, AgentMemoryScopeSchema, AgentMemorySourceSchema, WorkflowDefinitionSchema, WorkflowNodePatchSchema, WorkflowPatchSchema, TriggerConfigSchema, CooldownConfigSchema, InputValueSchema, PageContentTypeSchema, PageAuthModeSchema, MetricDefinitionSchema, MetricVersionSchema, WorkflowRunStatusSchema, ScriptRunStatusSchema, TERMINAL_SCRIPT_RUN_STATUSES, PromptTemplateScopeSchema, PromptTemplateStateSchema, ScriptScopeSchema, ScriptFsModeSchema, ScriptApiAuthModeSchema, ContextSnapshotEventTypeSchema, ContextFormulaSchema, BudgetScopeSchema, BudgetSchema, PricingProviderSchema, PricingTokenClassSchema, PricingRowSchema, BudgetRefusalCauseSchema, BudgetRefusalNotificationSchema, KvValueTypeSchema, KvNamespaceSchema, KvKeySchema, 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, markTaskSlackReplySent, setSlackMessageTracking, getChildTasks, hasNonTerminalResumeChild, hasNonTerminalRerouteDecisionChild, updateTaskClaudeSessionId, updateTaskTitle, updateTaskVcs, getTasksByAgentId, getAgentCurrentTask, getTasksByStatus, findTaskByVcs, findTaskByGitHub, getAllTasks, getTasksCount, getTaskStats, getCompletedSlackTasks, getRecentlyFinishedWorkerTasks, markTasksNotified, resetTasksNotified, getInProgressSlackTasks, getInProgressTasksByContextKey, findExistingLinearTrackerContextWork, getLatestTaskByContextKey, getAgentWorkingOnThread, getLatestActiveTaskInThread, getLatestLeadTaskInThread, getMostRecentTaskInThread, findCompletedTaskInThread, findRecentCancelledTaskInThread, completeTask, failTask, 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, 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, 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, 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 };