Swarm scripts

From desplega-ai/agent-swarm · View interactive version

Swarm scripts is an AI agent skill from the GitHub repository desplega-ai/agent-swarm. Bulk, repeat, fan-out, or data-heavy work: write and run swarm scripts (inline `script-run`, named `script-upsert`, durable `launch-script-run`). Covers the script-vs-tool rubric, the authoring contract (`args` first, `ctx` second), the seed catalog, connections and secrets, files and bash over the

How to use this skill

Skill file

Swarm Scripts

A swarm script is TypeScript that runs out of process with a typed Swarm SDK. Only its return value enters your context. Use one when direct tool calls would repeat, flood your context, or need deterministic processing over many records.

When to script

| Situation | Approach |

|---|---|

| 1 to 9 SDK calls, result fits in context | Direct tool calls. |

| 10 or more similar calls, bulk or fan-out | Script. Inline script-run for a one-off, a named script for reuse. |

| Fetch, parse, and transform heavy data | Script. |

| One large web fetch | Script with ctx.stdlib.fetch. Return only the part you need. |

| A schedule, workflow, or API script that reads or writes drive files | Script with ctx.fs and ctx.sh. |

| Multi-agent fan-out, parallel work, deterministic pipeline | Workflow. See workflow-iterate. |

| Work that repeats on a clock | Schedule. See scheduling. |

Named script only when the logic will run two or more times, by you, another agent, a schedule, or a workflow. A one-off goes inline, so the catalog does not fill with scratch saves.

Reference point: a workflow triage that took about 26 tool calls returns as one result of about 4k tokens in about 13 seconds.

Pick the run mode before you author. A short inline script-run is for small lookups only. A job that scans a whole population or may run past the inline cap of about 30 s starts as a durable launch-script-run from the start. A single ctx.step.swarmScript step has the same cap, so collect in bounded steps: each step takes a cursor, collects one slice in well under 30 s, and returns its rows plus the next cursor. Label each step with its slice (collect-${page}) so the journal checkpoints it, then compute from the collected slices in a final step. Restarting a long inline run throws away the work it already did.

Loading the tools

The script tools are deferred. Load them with your harness tool search before the first call: script-search, script-run, script-upsert, script-query-types, script-delete, and for durable runs launch-script-run, get-script-run, list-script-runs.

Run script-query-types before non-trivial work. It returns the live swarm-sdk.d.ts and stdlib declarations, including generated per-app types.

Seed catalog

The swarm ships named scripts at global scope. Each one replaces a multi-step tool chain. script-search with a plain-language description finds them. Call one with script-run and name plus args.

| Script | Args | Use |

|---|---|---|

| task-context-gathering | { taskId, queries: [...] } | the task plus a deduplicated multi-query memory recall |

| smart-recall | { queries: [...] } | multi-query memory recall without the task |

| memory-dedup-check | { text, threshold? } | near-duplicates before you store a memory |

| delegate | { agentName, task, routingReason, routingNote, parentTaskId? } | a subtask for an agent by name, returns { taskId } |

| wait-for-task | { taskId } | waits up to about 25 s for a terminal state, returns { done, status, output }; call again while done is false |

| get-child-outputs | { parentTaskId } | every child with status and output |

| complete-task | { taskId, output } | finish a task from inside a script |

| report-progress | { taskId, note } | a progress note from inside a script |

| swarm-overview | {} | agents and task counts |

| schedule-health, task-failure-audit, boot-triage | see heartbeat-runbook | the lead's heartbeat data gathering |

Authoring contract

The entry point takes args first and ctx second. A one-parameter function (ctx) receives args at runtime, so every ctx.* access throws. This is the most common cause of a failed run.

import type { ScriptContext } from "swarm-sdk";
import * as z from "zod";

export const argsSchema = z.object({ taskId: z.string(), limit: z.number().optional() });

export default async function (args: z.infer<typeof argsSchema>, ctx: ScriptContext) {
  const res = await ctx.swarm.task_get({ taskId: args.taskId });
  const task = ((res as { data?: unknown }).data ?? res) as { title?: string };
  return { title: task?.title };
}

Upserting a large source

A large source pasted inline into a script-upsert tool call overflows the call. Write the source to a local file, then send it from bash through the same route, POST $MCP_BASE_URL/api/scripts/upsert. The body is JSON (name, source, optional description, intent, scope), so wrap the file instead of sending it raw:

jq -n --arg name my-script --rawfile source ./my-script.ts '{name: $name, source: $source}' \
  | curl -sS -X POST "$MCP_BASE_URL/api/scripts/upsert" \
      -H "Authorization: Bearer $API_KEY" -H "X-Agent-ID: $AGENT_ID" \
      -H "Content-Type: application/json" --data-binary @-

The route runs the same typecheck and scope rules as the tool.

What `ctx` holds

Files and shell

await ctx.fs.writeFile("/afs/reports/today.md", "# Today\n");      // your agent-fs drive
await ctx.sh("echo '- shipped' >> reports/today.md");              // cwd is /afs
const { stdout, exitCode } = await ctx.sh("grep -rn TODO /afs/notes | sort | head -20");

Durable workflow scripts

launch-script-run runs a script as a durable, journaled run with a different ctx: ctx.run (id, agentId, args) and ctx.step.rawLlm(label, config), ctx.step.agentTask(label, config), ctx.step.swarmScript(label, config), plus ctx.swarm.*, ctx.stdlib, ctx.logger. Durable runs have no ctx.api, no ctx.mcp, no ctx.fs, no ctx.sh, and no ctx.swarm.config. A configured ctx.step.agentTask agentId records human_pinned unless routingReason is supplied. Call a connection or the drive from an inner script through ctx.step.swarmScript. See the script-workflows skill.

Durable objects

A durable object is a named instance of a global script class. Each instance keeps its own JSON state between calls. Only one call runs on an instance at a time, so you do not need your own KV locks.

import { DurableObject } from "swarm-sdk";

export default class Counter extends DurableObject<{ n: number }> {
  initialState() { return { n: 0 }; }
  async add(args: { by: number }) { this.state.n += args.by; return this.state.n; }
}

Save it with script_upsert in scope: "global". The API refuses a DurableObject class in agent scope and in an inline script_run. Call one instance by id:

script_run({ name: "counter", object: { id: "team-a", method: "add" }, args: { by: 2 } })
// → result: 2, object: { id: "team-a", stateVersion: 1, destroyed: false }

| Cloudflare Durable Objects | Swarm durable objects |

|---|---|

| this.ctx.storage key-value API | One JSON this.state snapshot per instance |

| fetch() and RPC from a Worker | script_run with object: { id, method } |

| env bindings | ctx (the same ctx as other scripts), passed to each method |

| Alarms | Not available yet |

| Methods take any arguments | Methods take (args, ctx) |

Inline script pattern

import type { ScriptContext } from "swarm-sdk";

export default async function main(args: { status?: string; limit?: number } | undefined, ctx: ScriptContext) {
  const res: any = await ctx.swarm.task_list({ status: args?.status, limit: args?.limit ?? 50 });
  const tasks: any[] = res?.data?.tasks ?? res?.tasks ?? [];
  ctx.logger.log(`Fetched ${tasks.length} tasks`);
  return {
    total: tasks.length,
    tasks: tasks.map((task: any) => ({ id: task.id, status: task.status, title: task.task?.slice(0, 120) })),
  };
}

Named script pattern

script-upsert with a searchable name, a concrete description, and an intent that says when to choose it. Good named scripts: aggregate failures by agent, schedule, or error family; fetch and normalize a third-party API response; fan out over tasks, memories, repos, or schedules; turn noisy JSON or HTML into a compact summary.

Secrets

A config row reaches your shell env only when its exportToEnv flag is on. If $KEY is empty in your shell but get-config or list-config shows the row marked not in agent env, the row stays server-side on purpose: do not copy the value into a file, an env var, or a command. Use it from a script instead, through one of the paths below. Harness, git, and agent-fs credentials stay exported. Keys only the API server reads (Slack app token and signing secret, GitHub App private key, webhook and OAuth client secrets) can never be exported. If a recipe genuinely needs the variable in a shell, ask the lead to turn exportToEnv on for that row (set-config with exportToEnv: true); it applies to your next task.

Order of preference:

  1. A registered connection: ctx.api.<slug>.<operationId>({ path, query, header, body }) (OpenAPI), ctx.api.<slug>.graphql(query, variables) (GraphQL), ctx.mcp.<slug>.<toolName>(args) (MCP, proxied server-side, returns the raw MCP envelope: read res.structuredContent ?? res.content?.[0]?.text). Credentials attach at egress. The script never sees them. OAuth tokens refresh on their own.
  2. A credential binding placeholder in a hand-written request: Authorization: Bearer [REDACTED:GITHUB_TOKEN]. The runtime substitutes the value at egress, only for the binding's allowed hosts.
  3. ctx.swarm.config.get("KEY") for a config value you pass to ctx.stdlib.fetch as a header value. Unwrap it with ctx.stdlib.Redacted.value(...) inside the header itself (a wrapped value sends the literal <redacted>), and never log it. Secret values are scrubbed from run output. Not available in launch-script-run (durable runs have no ctx.swarm.config): collect there without secrets, then pass the run's output to a short script-run that makes the authenticated calls.

A raw secret, or the output of get-config with includeSecrets: true, must not appear in script source, script args, a schedule's taskTemplate or scriptArgs, or a task description. Those are stored as plain text and replayed on every run.

Registration is lead-only: script-connections and credential-bindings. A worker that needs a missing connection puts the request in its task output: slug, baseUrl or spec URL, allowedHosts, and the auth (config key or OAuth provider). When a secret has no credential binding yet, step 3 is a stopgap: say so in the task output and ask the lead to register a binding for that config key, so later runs use it. Leads: upsert-openapi with a spec URL keeps operations refreshable; credential-bindings oauth-app-upsert then oauth-authorize-url sets up an OAuth provider (tokenAuthStyle and tokenBodyFormat cover Notion-style token endpoints).

Full reference: the "Script connections" guide on the docs site.

SQL in scripts

Direct SQL beats fetching lists into the script. Use ctx.db.query(sql, params?). It returns the rows as objects keyed by column name, and it throws when the query fails (bad SQL, timeout, 429). It goes through ctx.swarm.db_query, so it has the same permissions, row cap and errors.

const counts = await ctx.db.query<{ status: string; cnt: number }>(
  "SELECT status, count(*) AS cnt FROM agent_tasks GROUP BY status",
);

The swarm database is SQLite or PostgreSQL. ctx.db.dialect tells which one, with no probe query. When a statement has no portable form, give one text for each dialect. ctx.db.query runs the text of the active dialect:

const durations = await ctx.db.query(
  {
    sqlite: `SELECT id, (julianday("finishedAt") - julianday("startedAt")) * 86400 AS seconds FROM script_runs WHERE "scriptName" = ? LIMIT 100`,
    postgres: `SELECT id, extract(epoch FROM "finishedAt" - "startedAt") AS seconds FROM script_runs WHERE "scriptName" = $1 LIMIT 100`,
  },
  [args.scriptName],
);

Give both texts. An object without both strings throws a TypeError. The db-query-guidance skill has the dialect notes.

ctx.swarm.db_query({ sql, params }) is the raw call. It does not throw on a failed query: it returns { success, status, data }. On success, data holds positional rows, { rows: unknown[][], columns: string[], dialect }. Zip them:

function rowsToObjects(res: any): any[] {
  const p = res?.data ?? res;
  const cols: string[] = p?.columns ?? [];
  return (p?.rows ?? []).map((r: any) =>
    Array.isArray(r) ? Object.fromEntries(cols.map((c, i) => [c, r[i]])) : r,
  );
}

Concurrency limit

ctx.swarm.db_query throttles at about three concurrent calls. A wider Promise.all fan-out can return 429 responses with no rows key, so res?.data?.rows ?? [] misreads throttling as a clean zero. ctx.db.query throws on a 429. With the raw call, check the response status and data.error before reading rows. Serialize queries or cap concurrency at three.

Response traps

Common tables: agent_tasks, session_logs, agent_memory, scheduled_tasks, agents. session_logs has no tool_name column. Tool names sit inside the content JSON column. Extract them with instr and substr in SQL, or parse the JSON in the script.

Progress from a script

export default async function main(args: { taskId: string; items: string[] }, ctx: ScriptContext) {
  await ctx.swarm.task_storeProgress({ taskId: args.taskId, progress: `Processing ${args.items.length} items` });
  return { processed: args.items.length };
}

Exposing a script as an API

A named script can serve POST /api/x/script/<id> for callers outside the swarm. Manage endpoints from the script's API tab in the dashboard, or with the script-apis tool (list, create, update, rotate, delete). list masks bearer tokens; includeSecrets: true reveals them. create and rotate return the plaintext token once.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.