Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(swarm): the board is always cleared when the turn ends, and stays small while it runs

Samrat Talukdar3460776da3a3
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index a14ce1b0..987a628c 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -20,8 +20,11 @@ import {
OMNIRUSH_SWARM_MAX_PER_TURN,
OMNIRUSH_SWARM_MAX_RUNNING,
OMNIRUSH_SWARM_SKILL,
+ OMNIRUSH_SWARM_ARCHIVE_DIR,
OMNIRUSH_SWARM_SKILL_NAME,
+ OMNIRUSH_SWARM_TOOL_NAME,
omnirushSwarmSkillMarkdown,
+ omnirushSwarmSubagentNote,
} from "./omnirush-swarm.js";
import { parseFrontmatter } from "./frontmatter.js";
import {
@@ -354,6 +357,9 @@ describe("omnirush runtime config file", () => {
expect(agents.explore).toBeUndefined();
expect((parsed.permission as Record<string, unknown>).task).toBeUndefined();
expect(agents.omnirush?.permission?.task).toBeUndefined();
+ // The board tool is for sub-agents only: hidden from the main agent.
+ expect(agents.omnirush?.permission?.[OMNIRUSH_SWARM_TOOL_NAME]).toBe("deny");
+ expect(agents.general?.permission?.[OMNIRUSH_SWARM_TOOL_NAME]).toBeUndefined();
expect((parsed.plugin as string[]).some((plugin) => /omnirush-swarm\.(?:ts|js)$/.test(plugin))).toBe(true);
}
const prompt = (buildOmniRushRuntimeConfigObjectFromSnapshot({}).agent as Record<string, { prompt: string }>).omnirush!.prompt;
@@ -377,14 +383,26 @@ describe("omnirush runtime config file", () => {
expect(OMNIRUSH_SWARM_SKILL).toContain("`.omnirush/swarm.md`");
expect(OMNIRUSH_SWARM_SKILL).toContain("never a file in the project root");
expect(OMNIRUSH_SWARM_SKILL).toContain("For 1-2 sub-agents, stop here");
- expect(OMNIRUSH_SWARM_SKILL).toContain("`.omnirush/swarms/<YYYYMMDD-HHMMSS>.md`");
expect(OMNIRUSH_SWARM_SKILL).toContain("There is no limit on how many run at once or start per turn");
+ // Sub-agents use the board tool instead of reading the whole board, and
+ // omnirush.ai (not the model) clears the board when the turn ends.
+ expect(OMNIRUSH_SWARM_SKILL).toContain(`use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id`);
+ expect(OMNIRUSH_SWARM_SKILL).toContain("do not read or edit the board file");
+ expect(OMNIRUSH_SWARM_SKILL).toContain("omnirush.ai does that when the turn ends");
const { data, body } = parseFrontmatter(omnirushSwarmSkillMarkdown());
expect(data.name).toBe(OMNIRUSH_SWARM_SKILL_NAME);
expect(String(data.description)).toContain("Required before starting 3 or more sub-agents for one request");
expect(body.trim()).toBe(OMNIRUSH_SWARM_SKILL);
});
+ test("no prompt, skill or sub-agent note points a model at archived boards", () => {
+ const prompt = (buildOmniRushRuntimeConfigObjectFromSnapshot({}).agent as Record<string, { prompt: string }>).omnirush!.prompt;
+ for (const text of [prompt, OMNIRUSH_SWARM_SKILL, omnirushSwarmSkillMarkdown(), omnirushSwarmSubagentNote(1), omnirushSwarmSubagentNote(3)]) {
+ expect(text).not.toContain(OMNIRUSH_SWARM_ARCHIVE_DIR);
+ expect(text).not.toContain("swarms/");
+ }
+ });
+
test("the engine loads the swarm skill from the runtime folder", async () => {
const { root, config } = await setup();
const { path } = await writeOmniRushRuntimeConfigFile(config);
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 404949e0..3187ff11 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -45,7 +45,7 @@ import {
import { CONNECT_MCP_SERVER_NAME_PREFIX } from "./connect-mcp-server-catalog.js";
import { isOmniRushUiMcpRegistryEntry } from "./omnirush-ui-mcp-command.js";
import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
-import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_SKILL_NAME, omnirushSwarmSkillMarkdown } from "./omnirush-swarm.js";
+import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_SKILL_NAME, OMNIRUSH_SWARM_TOOL_NAME, omnirushSwarmSkillMarkdown } from "./omnirush-swarm.js";
import {
builtinOmniRushModelCatalog,
engineModelsFromCatalog,
@@ -205,6 +205,10 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
"agent-creator": "deny",
"plugin-creator": "deny",
},
+ // The swarm plugin's board tool is for sub-agents: the main agent
+ // writes and reads the board itself, and never pays for the tool
+ // definition on its requests.
+ [OMNIRUSH_SWARM_TOOL_NAME]: "deny",
},
},
// The engine hides the task tool from a sub-agent unless the sub-agent's
diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.ts
index bdc9ae1c..9f6be83b 100644
--- a/apps/server/src/omnirush-swarm.ts
+++ b/apps/server/src/omnirush-swarm.ts
@@ -69,9 +69,34 @@ export const OMNIRUSH_SWARM_ARCHIVE_DIR = `${OMNIRUSH_WORKSPACE_DIR}/swarms`;
*/
export const OMNIRUSH_SWARM_GITIGNORE_LINES = ["/.gitignore", "/swarm.md", "/swarms/"] as const;
+/**
+ * The `.omnirush/.ignore` entries: ripgrep, which the engine's grep and glob
+ * tools run with hidden files included, honours `.ignore` files in every
+ * folder, git repository or not (a `.gitignore` only counts inside one), so a
+ * search over the workspace never pulls a board into a model's context.
+ */
+export const OMNIRUSH_SWARM_IGNORE_LINES = ["/.ignore", "/swarm.md", "/swarms/"] as const;
+
+/** Finished boards kept in `.omnirush/swarms/`; older ones are deleted when a board is archived. */
+export const OMNIRUSH_SWARM_ARCHIVES_KEPT = 10;
+
/** Fewest parallel sub-agents that make a swarm (fewer never get a board). */
export const OMNIRUSH_SWARM_MIN_AGENTS = 3;
+/**
+ * Board size limits. Every agent's view of the board is re-sent to the model
+ * on each of its steps, so the board stays a status board: a task table with
+ * one-line cells, a few one-line findings per task and one-line decisions.
+ * Full reports travel in the task results, never on the board.
+ */
+export const OMNIRUSH_SWARM_CELL_MAX_CHARS = 160;
+export const OMNIRUSH_SWARM_LINE_MAX_CHARS = 240;
+export const OMNIRUSH_SWARM_FINDINGS_PER_TASK = 3;
+export const OMNIRUSH_SWARM_GOAL_MAX_CHARS = 600;
+
+/** The engine tool (from the swarm plugin) that sub-agents use to read their rows and update the board. */
+export const OMNIRUSH_SWARM_TOOL_NAME = "swarm_board";
+
/** The on-demand skill that carries the swarm procedure. */
export const OMNIRUSH_SWARM_SKILL_NAME = "omnirush-swarm";
@@ -90,15 +115,13 @@ export const OMNIRUSH_SWARM_SKILL = `# Sub-agent swarm
Use this only for a real swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for several agents. For 1-2 sub-agents, stop here: call the task tool directly and do not create or touch a board.
-The board is \`${OMNIRUSH_SWARM_FILE}\` in the workspace, never a file in the project root. omnirush.ai keeps \`${OMNIRUSH_SWARM_FILE}\` and \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/\` out of git. Ignore any \`swarm.md\` in the project root: it is not this swarm's board.
+The board is \`${OMNIRUSH_SWARM_FILE}\` in the workspace, never a file in the project root. It is a short status board, not a report: every agent re-reads it, so keep it small. omnirush.ai keeps it out of git and clears it when your turn ends. Ignore any \`swarm.md\` in the project root: it is not this swarm's board.
-1. If \`${OMNIRUSH_SWARM_FILE}\` already exists, it is left over from an earlier swarm: move it to \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/<YYYYMMDD-HHMMSS>.md\` and start a fresh board.
-2. Before delegating, create \`${OMNIRUSH_SWARM_FILE}\` with: \`# Goal\` (one paragraph), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked), \`## Findings\` (shared facts, one bullet each, with the task id), \`## Decisions\` (choices every agent must follow).
-3. Give each sub-agent one task id. Its task-tool prompt names the id, the task, and says: read \`${OMNIRUSH_SWARM_FILE}\` first; set your row to running; when done, set it to done with a one-line result and append your findings under your id; edit only your own rows and sections; report back briefly.
-4. Sub-agents may split their own task: they add sub-task rows (T1.1, T1.2) and give the same instructions to their own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. There is no limit on how many run at once or start per turn: start as many as the work needs, and no more.
-5. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.
-6. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\`, check and merge the results, and answer the user.
-7. Then archive the board: move \`${OMNIRUSH_SWARM_FILE}\` to \`${OMNIRUSH_SWARM_ARCHIVE_DIR}/<YYYYMMDD-HHMMSS>.md\` (create the folder if needed), so no later request picks it up. If the user asked to keep the board, name the archived path in your answer.`;
+1. Before delegating, create \`${OMNIRUSH_SWARM_FILE}\` (replace it if one exists) with: \`# Goal\` (at most 3 sentences), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked; every cell one short line), \`## Findings\` (empty) and \`## Decisions\` (choices every agent must follow, one line each).
+2. Give each sub-agent one task id. Its task-tool prompt names the id and the task, and says: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (it shows your row and the Decisions, and sets your status, one-line result and at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings); do not read or edit the board file; report back briefly.
+3. Sub-agents may split their own task: they add sub-task rows (T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` and give the same instructions to their own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. There is no limit on how many run at once or start per turn: start as many as the work needs, and no more.
+4. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.
+5. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\` once, check the results against the task reports, and answer the user. Do not move, copy or archive the board: omnirush.ai does that when the turn ends. Board cells over ${OMNIRUSH_SWARM_CELL_MAX_CHARS} characters, lines over ${OMNIRUSH_SWARM_LINE_MAX_CHARS} and findings past ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} per task are cut.`;
/** The omnirush-swarm skill's SKILL.md. */
export function omnirushSwarmSkillMarkdown(): string {
@@ -114,15 +137,235 @@ export function omnirushSwarmArchiveName(date: Date = new Date()): string {
/**
* System text for a sub-agent session of a running swarm (its main session
* started one and the board exists): every layer follows the board even when
- * a prompt forgot to say so.
+ * a prompt forgot to say so. It never changes during a session, so it never
+ * invalidates the model's prompt cache; the board itself comes from the tool.
*/
export function omnirushSwarmSubagentNote(depth: number): string {
const canDelegate = depth < OMNIRUSH_SUBAGENT_DEPTH;
return [
- `You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}) in a swarm coordinated through \`${OMNIRUSH_SWARM_FILE}\` in the workspace.`,
- `Read \`${OMNIRUSH_SWARM_FILE}\` before you start. Find your task id in your prompt (or the row that matches your task), set its status to running, and when you finish set it to done with a one-line result and append your findings under your task id. Edit only your own rows and sections, and re-read the file right before each edit because other agents write to it too. Do not move or archive the board: the main agent does that.`,
+ `You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}) in a swarm coordinated through the board \`${OMNIRUSH_SWARM_FILE}\`.`,
+ `Do not read, search or edit the board file: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (from your prompt); it answers with your rows and the Decisions. Call it once when you start (status running) and once when you finish (status done, a one-line result, at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings other agents need). Put details in your final report, not on the board. Do not move or archive the board: omnirush.ai does that.`,
canDelegate
- ? "If your task splits into independent parts that each take real effort, you may delegate them with the task tool: add sub-task rows (for example T1.1, T1.2) first and give each sub-agent the same instructions. Otherwise do the work yourself."
+ ? `If your task splits into independent parts that each take real effort, you may delegate them with the task tool: add sub-task rows (for example T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` first and give each sub-agent the same instructions. Otherwise do the work yourself.`
: "You cannot delegate further: do the work yourself.",
].join("\n");
}
+
+export const OMNIRUSH_SWARM_STATUSES = ["todo", "running", "done", "blocked"] as const;
+export type SwarmTaskStatus = (typeof OMNIRUSH_SWARM_STATUSES)[number];
+
+export type SwarmBoardUpdate = {
+ task: string;
+ status?: SwarmTaskStatus;
+ result?: string;
+ findings?: string[];
+ subtasks?: Array<{ id: string; task: string }>;
+};
+
+type Table = { header: number; separator: number; rows: number[]; columns: { id: number; task: number; owner: number; status: number; result: number; count: number } };
+
+/** One line, whitespace collapsed, at most `max` characters (cut with an ellipsis). */
+function oneLine(text: string, max: number): string {
+ const flat = text.replace(/\s+/g, " ").trim();
+ return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat;
+}
+
+const cellsOf = (line: string): string[] => line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
+const rowOf = (cells: string[]): string => `| ${cells.join(" | ")} |`;
+const isSeparator = (line: string) => /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line);
+const heading = (line: string) => /^(#{1,6})\s+(.*)$/.exec(line.trim());
+const sectionName = (line: string) => {
+ const match = heading(line);
+ return match && match[1].length === 2 ? match[2].trim().toLowerCase() : null;
+};
+/** A task id at the start of a table cell or finding: T1, T1.2, **T3**, [T2]. */
+const TASK_ID = /^[\s*_[(`]*(T\d+(?:\.\d+)*)\b/i;
+const normalId = (id: string) => id.trim().toUpperCase();
+
+/** The first task table in the board (a markdown table whose header names an id and a status column). */
+function findTable(lines: string[]): Table | null {
+ for (let i = 0; i + 1 < lines.length; i += 1) {
+ if (!lines[i].trim().startsWith("|") || !isSeparator(lines[i + 1])) continue;
+ const names = cellsOf(lines[i]).map((cell) => cell.toLowerCase().replace(/[^a-z]/g, ""));
+ const find = (...keys: string[]) => names.findIndex((name) => keys.includes(name));
+ const columns = {
+ id: Math.max(find("id", "task id", "taskid"), 0),
+ task: find("task", "description", "title"),
+ owner: find("owner", "agent", "assignee"),
+ status: find("status", "state"),
+ result: find("result", "results", "outcome", "summary"),
+ count: names.length,
+ };
+ if (columns.status < 0) continue;
+ const rows: number[] = [];
+ for (let j = i + 2; j < lines.length && lines[j].trim().startsWith("|"); j += 1) rows.push(j);
+ return { header: i, separator: i + 1, rows, columns };
+ }
+ return null;
+}
+
+/**
+ * The board cut to its limits: one-line table cells, one-line findings and
+ * decisions (at most OMNIRUSH_SWARM_FINDINGS_PER_TASK per task; code blocks,
+ * paragraphs and nested bullets under Findings dropped) and a short goal.
+ * Other sections are left as they are. Returns the text unchanged when it is
+ * already within the limits.
+ */
+export function compactSwarmBoard(text: string): string {
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
+ const out: string[] = [];
+ const table = findTable(lines);
+ const tableRows = new Set(table?.rows ?? []);
+ let section: string | null = null;
+ let fence = false;
+ let goalChars = 0;
+ let findingTask: string | null = null;
+ const perTask = new Map<string, number>();
+ for (let i = 0; i < lines.length; i += 1) {
+ const line = lines[i];
+ const h = heading(line);
+ if (h && !fence) {
+ section = sectionName(line) ?? (h[1].length === 1 ? "goal" : section);
+ findingTask = section === "findings" && h[1].length > 2 ? (TASK_ID.exec(h[2])?.[1] ?? null) : section === "findings" ? findingTask : null;
+ if (h[1].length === 1) goalChars = 0;
+ out.push(line);
+ continue;
+ }
+ if (tableRows.has(i)) {
+ const cells = cellsOf(line);
+ out.push(cells.some((cell) => cell.length > OMNIRUSH_SWARM_CELL_MAX_CHARS)
+ ? rowOf(cells.map((cell) => oneLine(cell, OMNIRUSH_SWARM_CELL_MAX_CHARS)))
+ : line);
+ continue;
+ }
+ if (section === "findings") {
+ if (/^\s*```/.test(line)) { fence = !fence; continue; }
+ if (fence) continue;
+ const bullet = /^[-*+]\s+(.*)$/.exec(line);
+ if (!bullet) {
+ if (!line.trim()) out.push(line);
+ continue;
+ }
+ const task = normalId(TASK_ID.exec(bullet[1])?.[1] ?? findingTask ?? "?");
+ const count = (perTask.get(task) ?? 0) + 1;
+ perTask.set(task, count);
+ if (count > OMNIRUSH_SWARM_FINDINGS_PER_TASK) continue;
+ out.push(`- ${oneLine(bullet[1], OMNIRUSH_SWARM_LINE_MAX_CHARS)}`);
+ continue;
+ }
+ if (section === "decisions") {
+ const bullet = /^[-*+]\s+(.*)$/.exec(line);
+ out.push(bullet ? `- ${oneLine(bullet[1], OMNIRUSH_SWARM_LINE_MAX_CHARS)}` : line.length > OMNIRUSH_SWARM_LINE_MAX_CHARS ? oneLine(line, OMNIRUSH_SWARM_LINE_MAX_CHARS) : line);
+ continue;
+ }
+ if (section === "goal") {
+ if (goalChars >= OMNIRUSH_SWARM_GOAL_MAX_CHARS && line.trim()) continue;
+ const room = OMNIRUSH_SWARM_GOAL_MAX_CHARS - goalChars;
+ goalChars += line.length;
+ out.push(line.length > room ? oneLine(line, Math.max(room, 1)) : line);
+ continue;
+ }
+ out.push(line);
+ }
+ const next = out.join("\n").replace(/\n{3,}/g, "\n\n");
+ return next === text ? text : next;
+}
+
+/** The lines of one `## <name>` section, heading excluded; null when the board has none. */
+function sectionLines(lines: string[], name: string): { start: number; end: number } | null {
+ const start = lines.findIndex((line) => sectionName(line) === name);
+ if (start < 0) return null;
+ let end = start + 1;
+ while (end < lines.length && !(heading(lines[end]) && (heading(lines[end])?.[1].length ?? 3) <= 2)) end += 1;
+ return { start, end };
+}
+
+/**
+ * What one agent needs from the board: the task table's header with its own
+ * rows (its id and its sub-tasks) and the Decisions. Much smaller than the
+ * board, whose other rows and findings belong to other agents.
+ */
+export function swarmBoardView(text: string, taskId: string): string {
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
+ const id = normalId(taskId);
+ const parts: string[] = [];
+ const table = findTable(lines);
+ if (table) {
+ const mine = table.rows.filter((row) => {
+ const rowId = normalId(cellsOf(lines[row])[table.columns.id] ?? "");
+ return rowId === id || rowId.startsWith(`${id}.`);
+ });
+ parts.push(mine.length ? [lines[table.header], lines[table.separator], ...mine.map((row) => lines[row])].join("\n") : `(no row for ${id} yet)`);
+ }
+ const decisions = sectionLines(lines, "decisions");
+ const body = decisions ? lines.slice(decisions.start + 1, decisions.end).filter((line) => line.trim()) : [];
+ parts.push(`Decisions:\n${body.length ? body.join("\n") : "(none)"}`);
+ return parts.join("\n");
+}
+
+/**
+ * Applies one agent's update to the board: its row's status and result (a
+ * row is added when it has none), new sub-task rows, and findings appended
+ * under Findings as `- <id>: <text>`. The result is compacted.
+ */
+export function updateSwarmBoard(text: string, update: SwarmBoardUpdate): string {
+ const id = normalId(update.task);
+ let lines = text.replace(/\r\n/g, "\n").split("\n");
+ let table = findTable(lines);
+ if (!table) {
+ const tasks = ["## Tasks", "| id | task | owner | status | result |", "|---|---|---|---|---|"];
+ const at = sectionLines(lines, "tasks");
+ lines = at ? [...lines.slice(0, at.start), ...tasks, ...lines.slice(at.start + 1)] : [...lines, "", ...tasks];
+ table = findTable(lines);
+ if (!table) return text;
+ }
+ const { columns } = table;
+ const blank = () => Array.from({ length: columns.count }, () => "");
+ const rowIndex = (rowId: string) => table?.rows.find((row) => normalId(cellsOf(lines[row])[columns.id] ?? "") === rowId) ?? -1;
+ const insertRow = (cells: string[]) => {
+ const at = (table?.rows.at(-1) ?? table?.separator ?? lines.length - 1) + 1;
+ lines.splice(at, 0, rowOf(cells));
+ table = findTable(lines);
+ };
+ if (update.status || update.result !== undefined || rowIndex(id) < 0) {
+ let row = rowIndex(id);
+ if (row < 0) {
+ const cells = blank();
+ cells[columns.id] = id;
+ if (columns.status >= 0) cells[columns.status] = "todo";
+ insertRow(cells);
+ row = rowIndex(id);
+ }
+ const cells = cellsOf(lines[row]);
+ while (cells.length < columns.count) cells.push("");
+ if (update.status && columns.status >= 0) cells[columns.status] = update.status;
+ if (update.result !== undefined && columns.result >= 0) cells[columns.result] = oneLine(update.result.replace(/\|/g, "/"), OMNIRUSH_SWARM_CELL_MAX_CHARS);
+ lines[row] = rowOf(cells);
+ }
+ for (const sub of update.subtasks ?? []) {
+ const subId = normalId(sub.id);
+ if (!subId || rowIndex(subId) >= 0) continue;
+ const cells = blank();
+ cells[columns.id] = subId;
+ if (columns.task >= 0) cells[columns.task] = oneLine(sub.task.replace(/\|/g, "/"), OMNIRUSH_SWARM_CELL_MAX_CHARS);
+ if (columns.status >= 0) cells[columns.status] = "todo";
+ insertRow(cells);
+ }
+ const findings = (update.findings ?? []).map((finding) => finding.trim()).filter(Boolean);
+ if (findings.length) {
+ let at = sectionLines(lines, "findings");
+ if (!at) {
+ const decisions = sectionLines(lines, "decisions");
+ const insert = decisions ? decisions.start : lines.length;
+ lines.splice(insert, 0, "## Findings", "");
+ at = sectionLines(lines, "findings");
+ }
+ if (at) {
+ let end = at.end;
+ while (end > at.start + 1 && !lines[end - 1].trim()) end -= 1;
+ lines.splice(end, 0, ...findings.map((finding) => `- ${id}: ${oneLine(finding.replace(TASK_ID, "").replace(/^\s*[:\-–]\s*/, ""), OMNIRUSH_SWARM_LINE_MAX_CHARS)}`));
+ }
+ }
+ return compactSwarmBoard(lines.join("\n"));
+}
+
diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
index f02ff2e2..d91e1646 100644
--- a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
@@ -1,12 +1,20 @@
import { afterEach, describe, expect, test } from "bun:test";
-import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readdir, readFile, rm, utimes, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { OmniRushSwarm } from "./omnirush-swarm.js";
import {
+ compactSwarmBoard,
OMNIRUSH_SUBAGENT_DEPTH,
+ OMNIRUSH_SWARM_ARCHIVES_KEPT,
+ OMNIRUSH_SWARM_CELL_MAX_CHARS,
OMNIRUSH_SWARM_FILE,
+ OMNIRUSH_SWARM_FINDINGS_PER_TASK,
+ OMNIRUSH_SWARM_LINE_MAX_CHARS,
+ OMNIRUSH_SWARM_TOOL_NAME,
+ swarmBoardView,
+ updateSwarmBoard,
OMNIRUSH_SWARM_MAX_PER_TURN,
OMNIRUSH_SWARM_MAX_RUNNING,
OMNIRUSH_SWARM_SKILL_NAME,
@@ -93,7 +101,8 @@ describe("omnirush swarm plugin", () => {
expect(await system("ses_main")).toBe("");
const child = await system("ses_child");
expect(child).toContain("layer 1 of at most 3");
- expect(child).toContain("Read `.omnirush/swarm.md` before you start");
+ expect(child).toContain("Do not read, search or edit the board file");
+ expect(child).toContain(`use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool`);
expect(child).toContain("you may delegate");
expect(await system("ses_grand")).toContain("layer 2 of at most 3");
const great = await system("ses_great");
@@ -120,6 +129,8 @@ describe("omnirush swarm plugin", () => {
await writeBoard(directory);
expect(await systemOf(hooks)("ses_child")).toContain("`.omnirush/swarm.md`");
expect(await readFile(join(directory, ".omnirush", ".gitignore"), "utf8")).toContain("/swarm.md\n/swarms/\n");
+ // ripgrep (the engine's grep and glob) honours .ignore outside git repositories too.
+ expect(await readFile(join(directory, ".omnirush", ".ignore"), "utf8")).toContain("/.ignore\n/swarm.md\n/swarms/\n");
});
test("a user's own .omnirush/.gitignore only gains the board lines", async () => {
@@ -171,6 +182,186 @@ describe("omnirush swarm plugin", () => {
});
});
+const BOARD = [
+ "# Goal",
+ "Review the project.",
+ "",
+ "## Tasks",
+ "| id | task | owner | status | result |",
+ "|---|---|---|---|---|",
+ "| T1 | review math | agent 1 | todo | |",
+ "| T2 | review strings | agent 2 | todo | |",
+ "| T3 | write tests | agent 3 | todo | |",
+ "",
+ "## Findings",
+ "",
+ "## Decisions",
+ "- Do not edit source files.",
+ "",
+].join("\n");
+
+const busyStatus = (hooks: Hooks, sessionID: string) =>
+ hooks.event({ event: { type: "session.status", properties: { sessionID, status: { type: "busy" } } } });
+const boardTool = (hooks: Hooks) => hooks.tool[OMNIRUSH_SWARM_TOOL_NAME];
+
+describe("omnirush swarm board: size limits", () => {
+ test("compaction cuts cells, findings and decisions to one short line and keeps a few findings per task", () => {
+ const long = "x".repeat(1000);
+ const board = BOARD
+ .replace("| T1 | review math | agent 1 | todo | |", `| T1 | review math | agent 1 | done | ${long} |`)
+ .replace("## Findings\n", `## Findings\n- T1: ${long}\n- T1: second\n - nested detail\n- T1: third\n- T1: fourth\n- T1: fifth\n\`\`\`\ncode dump\n\`\`\`\nA paragraph of prose.\n### T2\n- one\n`)
+ .replace("- Do not edit source files.", `- ${long}`);
+ const compact = compactSwarmBoard(board);
+ const row = compact.split("\n").find((line) => line.startsWith("| T1"))!;
+ expect(row.length).toBeLessThan(OMNIRUSH_SWARM_CELL_MAX_CHARS + 60);
+ expect(compact).not.toContain("fourth");
+ expect(compact).not.toContain("fifth");
+ expect(compact).not.toContain("nested detail");
+ expect(compact).not.toContain("code dump");
+ expect(compact).not.toContain("A paragraph");
+ expect(compact).toContain("- T1: third");
+ expect(compact).toContain("### T2\n- one");
+ for (const line of compact.split("\n")) expect(line.length).toBeLessThanOrEqual(OMNIRUSH_SWARM_LINE_MAX_CHARS + 2);
+ expect(compact.length).toBeLessThan(board.length / 2);
+ // A board within the limits is left exactly as it is.
+ expect(compactSwarmBoard(BOARD)).toBe(BOARD);
+ expect(compactSwarmBoard(compact)).toBe(compact);
+ });
+
+ test("an update sets the agent's own row, adds sub-task rows and appends capped one-line findings", () => {
+ let board = updateSwarmBoard(BOARD, { task: "t2", status: "running" });
+ expect(board).toContain("| T2 | review strings | agent 2 | running | |");
+ board = updateSwarmBoard(board, { task: "T2", subtasks: [{ id: "T2.1", task: "check shout" }] });
+ expect(board).toContain("| T2.1 | check shout | | todo | |");
+ board = updateSwarmBoard(board, {
+ task: "T2",
+ status: "done",
+ result: "found 2 issues\nsee report | details",
+ findings: ["T2: banner() double-spaces", "whisper drops punctuation", "x".repeat(900), "four", "five"],
+ });
+ expect(board).toContain("| T2 | review strings | agent 2 | done | found 2 issues see report / details |");
+ expect(board).toContain("## Findings\n- T2: banner() double-spaces\n- T2: whisper drops punctuation\n- T2: xxx");
+ expect(board).not.toContain("four");
+ expect(board.indexOf("## Findings")).toBeLessThan(board.indexOf("## Decisions"));
+ // An id without a row gets one.
+ expect(updateSwarmBoard(BOARD, { task: "T9", status: "running" })).toContain("| T9 | | | running | |");
+ });
+
+ test("an agent's view is its own rows and the Decisions, not the rest of the board", () => {
+ const board = updateSwarmBoard(updateSwarmBoard(BOARD, { task: "T1", subtasks: [{ id: "T1.1", task: "sub" }] }), { task: "T3", findings: ["other agent's finding"] });
+ const view = swarmBoardView(board, "T1");
+ expect(view).toContain("| T1 | review math |");
+ expect(view).toContain("| T1.1 | sub |");
+ expect(view).not.toContain("T2");
+ expect(view).not.toContain("other agent's finding");
+ expect(view).toContain("Decisions:\n- Do not edit source files.");
+ expect(swarmBoardView(board, "T7")).toContain("(no row for T7 yet)");
+ });
+});
+
+describe("omnirush swarm plugin: board tool, notes and cleanup", () => {
+ test("sub-agents update the board through the tool, one write at a time, and see only their rows", async () => {
+ const { hooks, directory } = await setup();
+ await created(hooks, "ses_main");
+ await loadSwarmSkill(hooks, "ses_main");
+ const tool = boardTool(hooks);
+ expect(await tool.execute({ task: "T1", status: "running" })).toContain("No swarm board is running");
+ await writeBoard(directory, BOARD);
+ // Many agents at once: no update is lost.
+ await Promise.all(["T1", "T2", "T3"].flatMap((task) => [
+ tool.execute({ task, status: "done", result: `${task} ok` }),
+ tool.execute({ task, findings: [`fact from ${task}`] }),
+ ]));
+ const board = await readFile(join(directory, OMNIRUSH_SWARM_FILE), "utf8");
+ for (const task of ["T1", "T2", "T3"]) {
+ expect(board).toContain(`| ${task} |`);
+ expect(board).toContain(`| done | ${task} ok |`);
+ expect(board).toContain(`- ${task}: fact from ${task}`);
+ }
+ const answer = await tool.execute({ task: "T2" });
+ expect(answer).toContain("Board unchanged.");
+ expect(answer).toContain("| T2 |");
+ expect(answer).not.toContain("| T1 |");
+ expect(answer.length).toBeLessThan(board.length);
+ });
+
+ test("a sub-agent's system note stays the same while the board changes (prompt cache)", async () => {
+ const { hooks, directory } = await setup();
+ await created(hooks, "ses_main");
+ await created(hooks, "ses_child", "ses_main");
+ await loadSwarmSkill(hooks, "ses_main");
+ await writeBoard(directory, BOARD);
+ const first = await systemOf(hooks)("ses_child");
+ await boardTool(hooks).execute({ task: "T2", status: "running", findings: ["something"] });
+ expect(await systemOf(hooks)("ses_child")).toBe(first);
+ expect(first).not.toContain("| T2 |");
+ });
+
+ test("a board written with the model's own file tools is cut to the limits", async () => {
+ const { hooks, directory } = await setup();
+ await created(hooks, "ses_main");
+ await writeBoard(directory, BOARD.replace("## Findings\n", `## Findings\n- T1: ${"y".repeat(2000)}\n`));
+ await hooks["tool.execute.after"]({ tool: "edit", callID: "e1", args: { filePath: join(directory, OMNIRUSH_SWARM_FILE) } }, { output: "" });
+ const board = await readFile(join(directory, OMNIRUSH_SWARM_FILE), "utf8");
+ expect(board.length).toBeLessThan(BOARD.length + OMNIRUSH_SWARM_LINE_MAX_CHARS + 20);
+ // Other files are never touched.
+ await writeFile(join(directory, "notes.md"), `- T1: ${"y".repeat(2000)}\n`);
+ await hooks["tool.execute.after"]({ tool: "write", callID: "w1", args: { filePath: join(directory, "notes.md") } }, { output: "" });
+ expect((await readFile(join(directory, "notes.md"), "utf8")).length).toBeGreaterThan(2000);
+ });
+
+ test("the board is archived only once the main session and every sub-agent are idle", async () => {
+ const { hooks, directory } = await setup();
+ await created(hooks, "ses_main");
+ await created(hooks, "ses_child", "ses_main");
+ await loadSwarmSkill(hooks, "ses_main");
+ await writeBoard(directory, BOARD);
+ await busyStatus(hooks, "ses_main");
+ await busyStatus(hooks, "ses_child");
+ await idle(hooks, "ses_main");
+ // A sub-agent is still running: the board stays.
+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(true);
+ await idle(hooks, "ses_child");
+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(false);
+ expect(await readdir(join(directory, ".omnirush", "swarms"))).toHaveLength(1);
+ });
+
+ test("a board left by an earlier engine run is archived when a turn ends, even without a swarm", async () => {
+ const { hooks, directory } = await setup();
+ await created(hooks, "ses_main");
+ await writeBoard(directory, BOARD);
+ const old = new Date(Date.now() - 60 * 60_000);
+ await utimes(join(directory, OMNIRUSH_SWARM_FILE), old, old);
+ await busyStatus(hooks, "ses_main");
+ await idle(hooks, "ses_main");
+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(false);
+ // A board written during this run by no swarm the plugin knows is left alone.
+ await writeBoard(directory, BOARD);
+ await idle(hooks, "ses_main");
+ expect(existsSync(join(directory, OMNIRUSH_SWARM_FILE))).toBe(true);
+ });
+
+ test(`only the newest ${OMNIRUSH_SWARM_ARCHIVES_KEPT} archived boards are kept`, async () => {
+ const { hooks, directory } = await setup();
+ const archive = join(directory, ".omnirush", "swarms");
+ await mkdir(archive, { recursive: true });
+ const names = Array.from({ length: OMNIRUSH_SWARM_ARCHIVES_KEPT + 3 }, (_, i) => `20260101-0000${String(i).padStart(2, "0")}.md`);
+ for (const name of names) await writeFile(join(archive, name), "# old\n");
+ await writeFile(join(archive, "keep-me.txt"), "user file\n");
+ await created(hooks, "ses_main");
+ await loadSwarmSkill(hooks, "ses_main");
+ await writeBoard(directory, BOARD);
+ await idle(hooks, "ses_main");
+ const left = await readdir(archive);
+ expect(left).toContain("keep-me.txt");
+ const boards = left.filter((name) => name.endsWith(".md"));
+ expect(boards).toHaveLength(OMNIRUSH_SWARM_ARCHIVES_KEPT);
+ expect(boards).not.toContain(names[0]);
+ expect(boards).not.toContain(names[3]);
+ expect(boards).toContain(names.at(-1)!);
+ });
+});
+
describe("omnirush swarm plugin: sub-agent model and effort", () => {
type Resolve = { body: Record<string, unknown> };
const saved = { url: process.env.OMNIRUSH_SERVER_URL, token: process.env.OMNIRUSH_POLICY_TOKEN };
diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.ts b/apps/server/src/opencode-plugins/omnirush-swarm.ts
index a89ec9e0..80da5f69 100644
--- a/apps/server/src/opencode-plugins/omnirush-swarm.ts
+++ b/apps/server/src/opencode-plugins/omnirush-swarm.ts
@@ -15,11 +15,19 @@
* Swarm board: a main session runs a swarm once its tree loads the
* omnirush-swarm skill or writes the board (`.omnirush/swarm.md`). Only then
* are its sub-agents reminded of the board (while it exists), so 1-2 plain
- * task calls never hear of one. The plugin keeps the board out of git
- * (`.omnirush/.gitignore`), moves a board left by an earlier swarm to
- * `.omnirush/swarms/` when a new one starts, and archives the board there
- * when the swarm's main session goes idle if the main agent did not, so a
- * later request never finds a stale board.
+ * task calls never hear of one. The plugin keeps the board out of git and
+ * out of workspace searches (`.omnirush/.gitignore`, `.omnirush/.ignore`),
+ * moves a board left by an earlier swarm to `.omnirush/swarms/` when a new
+ * one starts, and archives the board there once the swarm's main session is
+ * idle and none of its sub-agents is still running, whatever the model did,
+ * so a later request never finds it. Only the newest
+ * OMNIRUSH_SWARM_ARCHIVES_KEPT archives are kept.
+ *
+ * Board size: sub-agents never read the board file. The `swarm_board` tool
+ * shows an agent its own rows and the Decisions, and writes its status,
+ * one-line result, findings and sub-task rows (serialized, so parallel
+ * agents never overwrite each other). Every write to the board, by the tool or by the
+ * model's own file tools, is cut to the board limits (compactSwarmBoard).
*
* Sub-agent model and effort: every prompt of a sub-agent session (any
* layer) is resolved against the app's sub-agent setting by the OmniRush.ai
@@ -37,15 +45,24 @@
* falling back to one engine read per unknown session. Everything is kept in
* bounded maps; nothing is persisted.
*/
-import { existsSync } from "node:fs";
-import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { existsSync, statSync } from "node:fs";
+import { appendFile, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
+import { z } from "zod";
import {
+ compactSwarmBoard,
OMNIRUSH_SUBAGENT_DEPTH,
+ OMNIRUSH_SWARM_ARCHIVES_KEPT,
+ OMNIRUSH_SWARM_FINDINGS_PER_TASK,
OMNIRUSH_SWARM_GITIGNORE_LINES,
+ OMNIRUSH_SWARM_IGNORE_LINES,
OMNIRUSH_SWARM_SKILL_NAME,
+ OMNIRUSH_SWARM_STATUSES,
+ OMNIRUSH_SWARM_TOOL_NAME,
OMNIRUSH_WORKSPACE_DIR,
omnirushSwarmArchiveName,
+ swarmBoardView,
+ updateSwarmBoard,
SUBAGENT_FALLBACK_EFFORT_HEADER,
SUBAGENT_FALLBACK_MODEL_HEADER,
SUBAGENT_ROOT_SESSION_HEADER,
@@ -193,22 +210,37 @@ function writesBoard(tool: string, args: unknown): boolean {
return false;
}
-/** Keeps the board and its archive out of git; a user's own `.omnirush/.gitignore` only gains the missing lines. */
-async function ignoreBoard(directory: string): Promise<void> {
- const folder = join(directory, OMNIRUSH_WORKSPACE_DIR);
- const file = join(folder, ".gitignore");
- await mkdir(folder, { recursive: true });
+/** Adds the board lines to one ignore file in `.omnirush/`; a user's own file only gains the missing lines. */
+async function ignoreIn(folder: string, name: string, lines: readonly string[], why: string): Promise<void> {
+ const file = join(folder, name);
const current = await readFile(file, "utf8").catch(() => null);
if (current === null) {
- await writeFile(file, `# omnirush.ai: the swarm board and its archive stay out of git\n${OMNIRUSH_SWARM_GITIGNORE_LINES.join("\n")}\n`, "utf8");
+ await writeFile(file, `# omnirush.ai: ${why}\n${lines.join("\n")}\n`, "utf8");
return;
}
- const lines = new Set(current.split(/\r?\n/).map((line) => line.trim()));
+ const present = new Set(current.split(/\r?\n/).map((line) => line.trim()));
// A user's own file is theirs to track: only the board lines are added.
- const missing = OMNIRUSH_SWARM_GITIGNORE_LINES.filter((line) => line !== "/.gitignore" && !lines.has(line));
+ const missing = lines.filter((line) => line !== `/${name}` && !present.has(line));
if (missing.length) await appendFile(file, `${current.endsWith("\n") || !current ? "" : "\n"}${missing.join("\n")}\n`, "utf8");
}
+/** Keeps the board and its archive out of git and out of the engine's grep/glob (ripgrep `.ignore`). */
+async function ignoreBoard(directory: string): Promise<void> {
+ const folder = join(directory, OMNIRUSH_WORKSPACE_DIR);
+ await mkdir(folder, { recursive: true });
+ await ignoreIn(folder, ".gitignore", OMNIRUSH_SWARM_GITIGNORE_LINES, "the swarm board and its archive stay out of git");
+ await ignoreIn(folder, ".ignore", OMNIRUSH_SWARM_IGNORE_LINES, "workspace searches skip the swarm board and its archive");
+}
+
+/** Deletes all but the newest OMNIRUSH_SWARM_ARCHIVES_KEPT archived boards (names sort by time). */
+async function pruneArchive(directory: string): Promise<void> {
+ const folder = join(directory, OMNIRUSH_SWARM_ARCHIVE_DIR);
+ const names = (await readdir(folder).catch(() => [] as string[])).filter((name) => /^\d{8}-\d{6}(?:-\d+)?\.md$/.test(name));
+ const order = (name: string) => name.replace(/\.md$/, "").replace(/-(\d+)$/, (_, n: string) => `-${n.padStart(6, "0")}`).replace(/^(\d{8}-\d{6})$/, "$1-000001");
+ const stale = names.sort((a, b) => order(a).localeCompare(order(b))).slice(0, Math.max(0, names.length - OMNIRUSH_SWARM_ARCHIVES_KEPT));
+ await Promise.all(stale.map((name) => rm(join(folder, name), { force: true })));
+}
+
/** Moves the board to `.omnirush/swarms/<stamp>.md`; no board, no move. */
async function archiveBoard(directory: string): Promise<string | null> {
const board = join(directory, OMNIRUSH_SWARM_FILE);
@@ -217,9 +249,27 @@ async function archiveBoard(directory: string): Promise<string | null> {
let name = omnirushSwarmArchiveName();
for (let n = 2; existsSync(join(directory, name)); n += 1) name = omnirushSwarmArchiveName().replace(/\.md$/, `-${n}.md`);
await rename(board, join(directory, name));
+ await pruneArchive(directory).catch(() => undefined);
return name;
}
+/** When the board was last written, or null when there is none. */
+function boardWrittenAt(directory: string): number | null {
+ try {
+ return statSync(join(directory, OMNIRUSH_SWARM_FILE)).mtimeMs;
+ } catch {
+ return null;
+ }
+}
+
+const swarmBoardArgs = z.object({
+ task: z.string().min(1).describe("Your task id from your prompt, for example T2 or T1.1."),
+ status: z.enum(OMNIRUSH_SWARM_STATUSES).optional().describe("New status of your task."),
+ result: z.string().optional().describe("One-line result, set when the task is done or blocked."),
+ findings: z.array(z.string()).optional().describe(`Up to ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line facts other agents need.`),
+ subtasks: z.array(z.object({ id: z.string().min(1), task: z.string().min(1) })).optional().describe("Sub-task rows to add before delegating them, for example T2.1."),
+});
+
// Only export the factory: the engine treats every export as a plugin.
export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?: string }) => {
/** Session id -> parent id (null for a main session). */
@@ -238,6 +288,14 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
const titled = new Set<string>();
/** Main sessions running a swarm: their tree loaded the swarm skill or wrote the board. */
const swarms = new Set<string>();
+ /** Sessions the engine reports busy (any layer). */
+ const busy = new Set<string>();
+ /** Main sessions that went idle while a sub-agent below them was still running. */
+ const waiting = new Set<string>();
+ /** Board writes by the swarm_board tool, one at a time. */
+ let boardQueue: Promise<unknown> = Promise.resolve();
+ /** When this engine instance started: a board older than this was left by an earlier run. */
+ const startedAt = Date.now();
const learn = (info: unknown) => {
if (!record(info) || typeof info.id !== "string" || !info.id) return;
@@ -362,14 +420,87 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
if (swarms.size > MAX_TRACKED_TREES) swarms.delete(swarms.values().next().value as string);
};
- /** A swarm's main session went idle: its board is archived if the main agent left it. */
- const endSwarm = async (root: string) => {
- if (!swarms.delete(root)) return;
+ /** Whether the main session `root` or any sub-agent below it is still running. */
+ const treeBusy = async (root: string) => {
+ for (const id of busy) {
+ if (id === root || (await locate(id)).root === root) return true;
+ }
+ return false;
+ };
+
+ /**
+ * A session went idle. Once its main session and every sub-agent below it
+ * are idle, the turn is over: a swarm's board is archived if the main agent
+ * left it. A board no swarm of this engine instance wrote (the engine
+ * restarted mid-swarm, or it was written in a way the plugin did not see)
+ * is archived too once no swarm is running, if it was written before this
+ * instance started.
+ */
+ const endSwarm = async (sessionId: string) => {
const directory = input?.directory;
+ const { root } = await locate(sessionId);
+ // Only the main session's idle ends a turn; a sub-agent's idle only
+ // finishes a turn whose main session already went idle before it.
+ if (root !== sessionId && !waiting.has(root)) return;
+ if (await treeBusy(root)) {
+ waiting.add(root);
+ return;
+ }
+ waiting.delete(root);
+ const tree = trees.get(root);
+ if (tree) {
+ for (const callId of tree.running.keys()) calls.delete(callId);
+ tree.running.clear();
+ }
+ const wasSwarm = swarms.delete(root);
if (!directory || swarms.size > 0) return;
+ const writtenAt = boardWrittenAt(directory);
+ if (writtenAt === null || (!wasSwarm && writtenAt >= startedAt)) return;
await archiveBoard(directory).catch(() => null);
};
+ /** Cuts the board to its limits after a model wrote it with its own file tools. */
+ const compactBoardFile = async (directory: string) => {
+ const file = join(directory, OMNIRUSH_SWARM_FILE);
+ boardQueue = boardQueue.then(async () => {
+ const text = await readFile(file, "utf8").catch(() => null);
+ if (text === null) return;
+ const next = compactSwarmBoard(text);
+ if (next !== text) await writeFile(file, next, "utf8");
+ }).catch(() => undefined);
+ await boardQueue;
+ };
+
+ /** The swarm_board tool: one agent's view of the board, and its update. */
+ const boardTool = async (rawArgs: unknown) => {
+ const args = swarmBoardArgs.parse(rawArgs);
+ const directory = input?.directory;
+ if (!directory || !existsSync(join(directory, OMNIRUSH_SWARM_FILE))) {
+ return "No swarm board is running in this workspace: nothing to update. Report your result in your answer.";
+ }
+ const task = args.task.trim().toUpperCase();
+ const file = join(directory, OMNIRUSH_SWARM_FILE);
+ const changes = Boolean(args.status || args.result !== undefined || args.findings?.length || args.subtasks?.length);
+ let view = "";
+ const run = boardQueue.then(async () => {
+ const text = await readFile(file, "utf8");
+ const next = changes
+ ? updateSwarmBoard(text, {
+ task,
+ ...(args.status ? { status: args.status } : {}),
+ ...(args.result !== undefined ? { result: args.result } : {}),
+ ...(args.findings?.length ? { findings: args.findings.slice(0, OMNIRUSH_SWARM_FINDINGS_PER_TASK) } : {}),
+ ...(args.subtasks?.length ? { subtasks: args.subtasks } : {}),
+ })
+ : text;
+ if (next !== text) await writeFile(file, next, "utf8");
+ view = swarmBoardView(next, task);
+ });
+ boardQueue = run.catch(() => undefined);
+ await run;
+ return `${changes ? "Board updated." : "Board unchanged."} Your rows and the Decisions:\n${view}`;
+ };
+
return {
event: async ({ event }: { event: EngineEvent }) => {
const properties = record(event?.properties) ? event.properties : {};
@@ -386,6 +517,8 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
overrides.delete(properties.info.id);
notes.delete(properties.info.id);
swarms.delete(properties.info.id);
+ busy.delete(properties.info.id);
+ waiting.delete(properties.info.id);
}
return;
case "message.part.updated": {
@@ -396,14 +529,14 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
return;
}
case "session.status": {
- // A main session that went idle has no running sub-agents left.
const status = record(properties.status) ? properties.status.type : undefined;
- if (status !== "idle" || typeof properties.sessionID !== "string") return;
+ if (typeof properties.sessionID !== "string" || typeof status !== "string") return;
+ if (status !== "idle") {
+ busy.add(properties.sessionID);
+ return;
+ }
+ busy.delete(properties.sessionID);
await endSwarm(properties.sessionID);
- const tree = trees.get(properties.sessionID);
- if (!tree) return;
- for (const callId of tree.running.keys()) calls.delete(callId);
- tree.running.clear();
return;
}
}
@@ -483,8 +616,12 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
// A finished task names the model its sub-agent ran on, and says so in
// the result when that is the main model instead of the picked one.
- "tool.execute.after": async (call: { tool: string; callID: string }, output?: { output?: unknown; metadata?: unknown }) => {
- if (call?.tool !== "task") return;
+ "tool.execute.after": async (call: { tool: string; callID: string; args?: unknown }, output?: { output?: unknown; metadata?: unknown }) => {
+ if (call?.tool !== "task") {
+ // A board written with the model's own file tools is cut to the board limits.
+ if (input?.directory && call?.tool !== OMNIRUSH_SWARM_TOOL_NAME && writesBoard(call?.tool, call?.args)) await compactBoardFile(input.directory);
+ return;
+ }
finish(call.callID);
const metadata = record(output?.metadata) ? output.metadata : null;
const child = metadata && typeof metadata.sessionId === "string" ? metadata.sessionId : null;
@@ -526,8 +663,19 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:
if ((await parentOf(request.sessionID)) === null) return;
const { root, depth } = await locate(request.sessionID);
// Only the sub-agents of a running swarm, and only while its board exists.
- if (!swarms.has(root) || !existsSync(join(directory, OMNIRUSH_SWARM_FILE))) return;
+ if (!swarms.has(root)) return;
+ if (!existsSync(join(directory, OMNIRUSH_SWARM_FILE))) return;
+ // The note is the same on every step (a changing system prompt would
+ // defeat the model's prompt cache); the agent's rows come from the tool.
output.system.push(omnirushSwarmSubagentNote(Math.min(Math.max(depth, 1), OMNIRUSH_SUBAGENT_DEPTH)));
},
+
+ tool: {
+ [OMNIRUSH_SWARM_TOOL_NAME]: {
+ description: "Swarm board (.omnirush/swarm.md) for a sub-agent: shows your task rows and the Decisions; with status/result/findings/subtasks it updates them. Use instead of reading or editing the board file.",
+ args: swarmBoardArgs.shape,
+ execute: boardTool,
+ },
+ },
};
};