A desktop coding agent with free access to frontier models.
TypeScript
feat: sub-agent swarms (nested sub-agents coordinated through swarm.md)
Samrat Talukdar137358bced9b
diff --git a/apps/server/package.json b/apps/server/package.jsonindex b18d2bea..54f76c69 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/src/collector-observer.ts b/apps/server/src/collector-observer.tsindex a9dff24d..7c6c9da1 100644--- a/apps/server/src/collector-observer.ts+++ b/apps/server/src/collector-observer.ts@@ -306,6 +306,7 @@ async function captureChildSessions(input: {input.collector.recordChildSession(input.rootSessionId, {childSessionId: childId,parentSessionId: input.parentSessionId,+ depth: input.depth,title: isRecord(child) ? optionalTraceString(child.title) : null,agent: turnModelFromMessages(history?.outline ?? [])?.agent ?? null,messages: newMessages,diff --git a/apps/server/src/omnirush-agent-prompt.ts b/apps/server/src/omnirush-agent-prompt.tsindex 7eac086f..8cebce4f 100644--- a/apps/server/src/omnirush-agent-prompt.ts+++ b/apps/server/src/omnirush-agent-prompt.ts@@ -8,6 +8,8 @@* Kept dependency-free so tests and specs can import it without the runtime* database.*/+import { OMNIRUSH_SWARM_PROMPT } from "./omnirush-swarm.js";+export const OMNIRUSH_AGENT_PROMPT = `You are omnirush.ai.When the user refers to "you", they mean the omnirush.ai app and the current workspace.@@ -41,6 +43,8 @@ Hard rule: never copy private memory into repo files. Store only redacted summar- If steps repeat, capture them as a skill following the \`Skill creation:\` instruction in this prompt.- Prefer clear, practical steps over abstract explanations.+${OMNIRUSH_SWARM_PROMPT}+## Editing files- When apply_patch or edit reports that expected lines were not found, the file changed since you read it (a formatter ran, or an earlier edit was rejected or aborted). Read the file again before retrying; never resend the same patch. Prefer smaller hunks with unambiguous context. On Windows, keep the file's existing line endings.diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.tsindex 6eeb7f5c..f1d052ec 100644--- a/apps/server/src/omnirush-extensions-plugin-path.ts+++ b/apps/server/src/omnirush-extensions-plugin-path.ts@@ -41,3 +41,4 @@ export const omnirushSpreadsheetsPluginPath = () => omnirushPluginPath("omnirushexport const omnirushPdfAttachmentsPluginPath = () => omnirushPluginPath("omnirush-pdf-attachments");export const omnirushTitleRecoveryPluginPath = () => omnirushPluginPath("omnirush-title-recovery");export const omnirushReasoningEffortPluginPath = () => omnirushPluginPath("omnirush-reasoning-effort");+export const omnirushSwarmPluginPath = () => omnirushPluginPath("omnirush-swarm");diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex aa699e21..ad21d6fa 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -13,6 +13,8 @@ import {import { writeGlobalRuntimeOpencodeConfig, writeRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";import { rulesFromPermissionConfig, winningRule } from "./effective-permissions.js";import { backendCatalogBody } from "./__fixtures__/omnirush-model-catalog.js";+import { MAX_COLLECTOR_CHILD_SESSION_DEPTH } from "./workspace-collector.js";+import { OMNIRUSH_SUBAGENT_DEPTH, OMNIRUSH_SWARM_MAX_PER_TURN, OMNIRUSH_SWARM_MAX_RUNNING } from "./omnirush-swarm.js";import {sanitizeOmniRushModelCatalog,writeOmniRushModelCatalog,@@ -328,6 +330,30 @@ describe("omnirush runtime config file", () => {expect(prompt).not.toContain("factor them into a skill");});+ test("sub-agent swarms: nested delegation up to the captured depth, for the general sub-agent only, bounded by the swarm plugin", () => {+ for (const mode of ["guarded", "full"] as const) {+ const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ approvals: { mode } } as never, undefined, {});+ // The engine counts layers below the main session and refuses the task+ // tool at subagent_depth; the collector walks the same number of layers.+ expect(parsed.subagent_depth).toBe(OMNIRUSH_SUBAGENT_DEPTH);+ expect(OMNIRUSH_SUBAGENT_DEPTH).toBe(MAX_COLLECTOR_CHILD_SESSION_DEPTH);+ const agents = parsed.agent as Record<string, { permission?: Record<string, unknown>; prompt?: string; mode?: string }>;+ // A sub-agent keeps the task tool only when its own rules mention it:+ // only general does; no global task rule reaches explore.+ expect(agents.general).toEqual({ permission: { task: "allow" } });+ expect(agents.explore).toBeUndefined();+ expect((parsed.permission as Record<string, unknown>).task).toBeUndefined();+ expect(agents.omnirush?.permission?.task).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;+ expect(prompt).toContain("## Sub-agent swarms");+ expect(prompt).toContain("Never start a swarm for a small or quick request.");+ expect(prompt).toContain("`swarm.md` at the workspace root");+ expect(prompt).toContain(`at most ${OMNIRUSH_SWARM_MAX_RUNNING} run at once and ${OMNIRUSH_SWARM_MAX_PER_TURN} start per turn`);+ expect(prompt.indexOf("## Sub-agent swarms")).toBeLessThan(prompt.indexOf("## Editing files"));+ });+test("keepOmniRushRuntimeConfigFileFresh rewrites the file on ENGINE_GLOBAL writes", async () => {const { config } = await setup();await writeOmniRushRuntimeConfigFile(config);diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex 8628860e..3606ea27 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -25,6 +25,7 @@ import {omnirushAnthropicToolSchemaPluginPath,omnirushTitleRecoveryPluginPath,omnirushReasoningEffortPluginPath,+ omnirushSwarmPluginPath,omnirushOfficeAttachmentsPluginPath,omnirushSpreadsheetsPluginPath,omnirushChromeDevtoolsPluginPath,@@ -45,6 +46,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 } from "./omnirush-swarm.js";import {builtinOmniRushModelCatalog,engineModelsFromCatalog,@@ -154,6 +156,10 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(] } : {}),permission: { ...engineConfig.permission, ...permissions },default_agent: runtimeConfig.default_agent ?? "omnirush",+ // Sub-agent swarms: sub-agents may delegate again, up to this many layers+ // below the main session (the engine's default of 1 forbids nesting).+ // The omnirush-swarm plugin bounds how many run and start.+ subagent_depth: OMNIRUSH_SUBAGENT_DEPTH,agent: {omnirush: {description: "omnirush.ai default agent",@@ -173,6 +179,12 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(},},},+ // The engine hides the task tool from a sub-agent unless the sub-agent's+ // own permissions mention `task`. Only the general sub-agent gets it;+ // explore stays read-only (a global task rule would reach every agent).+ general: {+ permission: { task: "allow" },+ },},plugin: [managedPolicyPluginPath(),@@ -190,6 +202,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(omnirushAnthropicToolSchemaPluginPath(),omnirushReasoningEffortPluginPath(),omnirushTitleRecoveryPluginPath(),+ omnirushSwarmPluginPath(),...runtimePluginList(runtimeConfig),],...(disabledProviders.length ? { disabled_providers: disabledProviders } : {}),diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.tsnew file mode 100644index 00000000..1b7c8c54--- /dev/null+++ b/apps/server/src/omnirush-swarm.ts@@ -0,0 +1,62 @@+/**+ * Sub-agent swarms: the limits and the coordination text shared by the+ * injected engine config (omnirush-runtime-config.ts), the swarm engine+ * plugin (opencode-plugins/omnirush-swarm.ts) and the collector.+ *+ * A swarm is the main agent delegating to sub-agents that may delegate+ * again, every level coordinating through one `swarm.md` board at the+ * workspace root. The bundled engine (opencode 1.18.32) counts sub-agent+ * layers from the main session through `parentID` and refuses the task tool+ * at `subagent_depth`; it has no fan-out limit of its own, so the plugin adds+ * one.+ *+ * Kept dependency-free: the engine plugin bundle imports it.+ */++/**+ * Sub-agent layers below the main session (Claude Code's default, too):+ * children, grandchildren and great-grandchildren; the third layer can no+ * longer delegate. Equal to MAX_COLLECTOR_CHILD_SESSION_DEPTH, so every+ * layer the engine allows is captured.+ */+export const OMNIRUSH_SUBAGENT_DEPTH = 3;++/** Sub-agents of one main session (all layers) running at the same time. */+export const OMNIRUSH_SWARM_MAX_RUNNING = 8;++/** Sub-agents one main-session turn may start in all (all layers, resumes included). */+export const OMNIRUSH_SWARM_MAX_PER_TURN = 24;++/** The coordination board, relative to the workspace root. */+export const OMNIRUSH_SWARM_FILE = "swarm.md";++/**+ * The main agent's swarm instructions (part of OMNIRUSH_AGENT_PROMPT). A+ * swarm is the model's call for large work that splits into independent+ * parts; small prompts are answered directly.+ */+export const OMNIRUSH_SWARM_PROMPT = `## Sub-agent swarms++Most requests need no sub-agents, or one or two task calls. Run a swarm only when the user asks for one, or when the work is large and splits into several independent parts that each take real effort (a multi-module change, a broad investigation, parallel research with a review pass). Never start a swarm for a small or quick request.++A swarm is coordinated through \`${OMNIRUSH_SWARM_FILE}\` at the workspace root:+1. Before delegating, create or update \`${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).+2. 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.+3. 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; at most ${OMNIRUSH_SWARM_MAX_RUNNING} run at once and ${OMNIRUSH_SWARM_MAX_PER_TURN} start per turn. If the task tool refuses because of a limit, finish the work yourself instead of retrying.+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}\`, check and merge the results, record the outcome under \`## Decisions\` or a final \`## Summary\`, and answer the user. Keep \`${OMNIRUSH_SWARM_FILE}\` in the workspace unless the user asks you to remove it.`;++/**+ * System text for a sub-agent session while `swarm.md` exists: every layer+ * follows the board even when a prompt forgot to say so.+ */+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}\` at the workspace root.`,+ `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.`,+ 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."+ : "You cannot delegate further: do the work yourself.",+ ].join("\n");+}diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts b/apps/server/src/opencode-plugins/omnirush-swarm.test.tsnew file mode 100644index 00000000..5f0682f7--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts@@ -0,0 +1,119 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { OmniRushSwarm } from "./omnirush-swarm.js";+import {+ OMNIRUSH_SUBAGENT_DEPTH,+ OMNIRUSH_SWARM_MAX_PER_TURN,+ OMNIRUSH_SWARM_MAX_RUNNING,+} from "../omnirush-swarm.js";++type Hooks = Awaited<ReturnType<typeof OmniRushSwarm>>;++const dirs: string[] = [];+afterEach(async () => {+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));+});++async function setup(parents: Record<string, string | null> = {}) {+ const directory = await mkdtemp(join(tmpdir(), "omnirush-swarm-"));+ dirs.push(directory);+ const reads: string[] = [];+ const client = {+ session: {+ get: async ({ path }: { path: { id: string } }) => {+ reads.push(path.id);+ if (!(path.id in parents)) throw new Error("not found");+ return { data: { id: path.id, ...(parents[path.id] ? { parentID: parents[path.id] } : {}) } };+ },+ },+ };+ const hooks = await OmniRushSwarm({ client, directory });+ return { hooks, directory, reads };+}++const created = (hooks: Hooks, id: string, parentID?: string) =>+ hooks.event({ event: { type: "session.created", properties: { info: { id, ...(parentID ? { parentID } : {}) } } } });+const task = (hooks: Hooks, sessionID: string, callID: string) =>+ hooks["tool.execute.before"]({ tool: "task", sessionID, callID });+const partDone = (hooks: Hooks, callID: string, status = "completed") =>+ hooks.event({ event: { type: "message.part.updated", properties: { part: { type: "tool", tool: "task", callID, state: { status } } } } });++describe("omnirush swarm plugin", () => {+ test("limits the sub-agents of one main-session tree running at once, across every layer", async () => {+ const { hooks } = await setup();+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ await created(hooks, "ses_grand", "ses_child");+ for (let i = 0; i < OMNIRUSH_SWARM_MAX_RUNNING; i += 1) {+ await task(hooks, i % 3 === 0 ? "ses_main" : i % 3 === 1 ? "ses_child" : "ses_grand", `call_${i}`);+ }+ await expect(task(hooks, "ses_grand", "call_over")).rejects.toThrow(/already running/);+ // Another main session has its own budget.+ await created(hooks, "ses_other");+ await task(hooks, "ses_other", "other_1");+ // One finished (event) and one failed call free two slots.+ await partDone(hooks, "call_0");+ await partDone(hooks, "call_1", "error");+ await task(hooks, "ses_child", "call_again_1");+ await task(hooks, "ses_main", "call_again_2");+ await expect(task(hooks, "ses_main", "call_again_3")).rejects.toThrow(/already running/);+ // tool.execute.after frees a slot too; the main session going idle frees all.+ await hooks["tool.execute.after"]({ tool: "task", callID: "call_2" });+ await task(hooks, "ses_main", "call_again_3");+ await hooks.event({ event: { type: "session.status", properties: { sessionID: "ses_main", status: { type: "idle" } } } });+ await task(hooks, "ses_grand", "after_idle");+ });++ test("limits sub-agents started per main-session turn; a new prompt to the main session refills it", async () => {+ const { hooks } = await setup();+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ for (let i = 0; i < OMNIRUSH_SWARM_MAX_PER_TURN; i += 1) {+ const callID = `call_${i}`;+ await task(hooks, i % 2 ? "ses_child" : "ses_main", callID);+ await partDone(hooks, callID);+ }+ await expect(task(hooks, "ses_child", "call_over")).rejects.toThrow(`started ${OMNIRUSH_SWARM_MAX_PER_TURN} sub-agents`);+ // A sub-agent's own prompt is not a new turn.+ await hooks["chat.message"]({ sessionID: "ses_child" });+ await expect(task(hooks, "ses_main", "call_over")).rejects.toThrow(/Do not retry/);+ await hooks["chat.message"]({ sessionID: "ses_main" });+ await task(hooks, "ses_child", "next_turn");+ });++ test("other tools and unknown sessions pass; parents are read from the engine once", async () => {+ const { hooks, reads } = await setup({ ses_a: null, ses_b: "ses_a" });+ await hooks["tool.execute.before"]({ tool: "bash", sessionID: "ses_b", callID: "x" });+ await task(hooks, "ses_b", "c1");+ await task(hooks, "ses_b", "c2");+ await task(hooks, "ses_unknown", "c3");+ expect(reads.filter((id) => id === "ses_b")).toHaveLength(1);+ expect(reads.filter((id) => id === "ses_a")).toHaveLength(1);+ });++ test("reminds sub-agents, not the main session, of swarm.md while it exists", async () => {+ const { hooks, directory } = await setup();+ await created(hooks, "ses_main");+ await created(hooks, "ses_child", "ses_main");+ await created(hooks, "ses_grand", "ses_child");+ await created(hooks, "ses_great", "ses_grand");+ const system = async (sessionID: string) => {+ const output = { system: ["base"] };+ await hooks["experimental.chat.system.transform"]({ sessionID }, output);+ return output.system.slice(1).join("\n");+ };+ expect(await system("ses_child")).toBe("");+ await writeFile(join(directory, "swarm.md"), "# Goal\n");+ 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 `swarm.md` before you start");+ expect(child).toContain("you may delegate");+ expect(await system("ses_grand")).toContain("layer 2 of at most 3");+ const great = await system("ses_great");+ expect(great).toContain(`layer ${OMNIRUSH_SUBAGENT_DEPTH} of at most ${OMNIRUSH_SUBAGENT_DEPTH}`);+ expect(great).toContain("You cannot delegate further");+ });+});diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.ts b/apps/server/src/opencode-plugins/omnirush-swarm.tsnew file mode 100644index 00000000..d95f2281--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-swarm.ts@@ -0,0 +1,208 @@+/**+ * OmniRush.ai Swarm Plugin+ *+ * The injected engine config lets sub-agents delegate again+ * (`subagent_depth`, see omnirush-swarm.ts). The engine itself runs any+ * number of task calls at once, so this plugin bounds the fan-out of one+ * main session's sub-agent tree:+ *+ * - at most OMNIRUSH_SWARM_MAX_RUNNING sub-agents of the tree run at once;+ * - at most OMNIRUSH_SWARM_MAX_PER_TURN start during one main-session turn.+ *+ * A task call over a limit fails before it creates a session, with a message+ * telling the model to do the work itself. It also reminds sub-agent+ * sessions of the `swarm.md` board while that file exists, so every layer+ * reads and updates it.+ *+ * Session parents come from `session.created` / `session.updated` events,+ * falling back to one engine read per unknown session. Everything is kept in+ * bounded maps; nothing is persisted.+ */+import { existsSync } from "node:fs";+import { join } from "node:path";+import {+ OMNIRUSH_SUBAGENT_DEPTH,+ OMNIRUSH_SWARM_FILE,+ OMNIRUSH_SWARM_MAX_PER_TURN,+ OMNIRUSH_SWARM_MAX_RUNNING,+ omnirushSwarmSubagentNote,+} from "../omnirush-swarm.js";++type SessionInfo = { id?: unknown; parentID?: unknown };+type EngineEvent = { type?: string; properties?: Record<string, unknown> };+type SwarmClient = {+ session?: { get?: (input: { path: { id: string } }) => Promise<{ data?: SessionInfo } | undefined> };+};+type Tree = {+ /** Running task calls: call id -> start time. */+ running: Map<string, number>;+ /** Task calls started in the current main-session turn. */+ started: number;+};++const MAX_TRACKED_SESSIONS = 4096;+const MAX_TRACKED_TREES = 512;+/** A task call never reported finished stops counting as running after this long. */+const STALE_RUNNING_MS = 3 * 60 * 60_000;+const MAX_PARENT_HOPS = 32;++function record(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function remember<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {+ map.delete(key);+ map.set(key, value);+ while (map.size > max) {+ const oldest = map.keys().next().value as K | undefined;+ if (oldest === undefined) break;+ map.delete(oldest);+ }+}++// 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). */+ const parents = new Map<string, string | null>();+ /** Main session id -> its sub-agent tree. */+ const trees = new Map<string, Tree>();+ /** Task call id -> main session id, to find the tree when the call ends. */+ const calls = new Map<string, string>();++ const learn = (info: unknown) => {+ if (!record(info) || typeof info.id !== "string" || !info.id) return;+ const parent = typeof info.parentID === "string" && info.parentID ? info.parentID : null;+ remember(parents, info.id, parent, MAX_TRACKED_SESSIONS);+ };++ const parentOf = async (sessionId: string): Promise<string | null> => {+ const known = parents.get(sessionId);+ if (known !== undefined) return known;+ try {+ const response = await input?.client?.session?.get?.({ path: { id: sessionId } });+ const parent = typeof response?.data?.parentID === "string" && response.data.parentID ? response.data.parentID : null;+ remember(parents, sessionId, parent, MAX_TRACKED_SESSIONS);+ return parent;+ } catch {+ // Unknown: counted as a main session, never cached, so a later read can fix it.+ return null;+ }+ };++ /** The main session above `sessionId` and how many sub-agent layers down it is. */+ const locate = async (sessionId: string): Promise<{ root: string; depth: number }> => {+ let root = sessionId;+ let depth = 0;+ const seen = new Set([sessionId]);+ for (let hop = 0; hop < MAX_PARENT_HOPS; hop += 1) {+ const parent = await parentOf(root);+ if (!parent || seen.has(parent)) break;+ seen.add(parent);+ root = parent;+ depth += 1;+ }+ return { root, depth };+ };++ const treeOf = (root: string): Tree => {+ const existing = trees.get(root);+ if (existing) return existing;+ const tree: Tree = { running: new Map(), started: 0 };+ remember(trees, root, tree, MAX_TRACKED_TREES);+ return tree;+ };++ const finish = (callId: unknown) => {+ if (typeof callId !== "string") return;+ const root = calls.get(callId);+ if (root === undefined) return;+ calls.delete(callId);+ trees.get(root)?.running.delete(callId);+ };++ return {+ event: async ({ event }: { event: EngineEvent }) => {+ const properties = record(event?.properties) ? event.properties : {};+ switch (event?.type) {+ case "session.created":+ case "session.updated":+ learn(properties.info);+ return;+ case "session.deleted":+ if (record(properties.info) && typeof properties.info.id === "string") {+ parents.delete(properties.info.id);+ trees.delete(properties.info.id);+ }+ return;+ case "message.part.updated": {+ const part = properties.part;+ if (!record(part) || part.type !== "tool" || part.tool !== "task") return;+ const status = record(part.state) ? part.state.status : undefined;+ if (status === "completed" || status === "error") finish(part.callID);+ 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;+ const tree = trees.get(properties.sessionID);+ if (!tree) return;+ for (const callId of tree.running.keys()) calls.delete(callId);+ tree.running.clear();+ return;+ }+ }+ },++ // A prompt to a main session opens a new turn: its start budget refills.+ "chat.message": async (message: { sessionID: string }) => {+ if (typeof message?.sessionID !== "string") return;+ if ((await parentOf(message.sessionID)) !== null) return;+ const tree = trees.get(message.sessionID);+ if (tree) tree.started = 0;+ },++ "tool.execute.before": async (call: { tool: string; sessionID: string; callID: string }) => {+ if (call?.tool !== "task" || typeof call.sessionID !== "string") return;+ const { root } = await locate(call.sessionID);+ const tree = treeOf(root);+ const now = Date.now();+ for (const [callId, startedAt] of tree.running) {+ if (now - startedAt > STALE_RUNNING_MS) {+ tree.running.delete(callId);+ calls.delete(callId);+ }+ }+ if (tree.running.size >= OMNIRUSH_SWARM_MAX_RUNNING) {+ throw new Error(+ `Sub-agent limit reached: ${OMNIRUSH_SWARM_MAX_RUNNING} sub-agents of this session are already running. `+ + "Do not retry this call now: do this part yourself, or wait until a running sub-agent has finished.",+ );+ }+ if (tree.started >= OMNIRUSH_SWARM_MAX_PER_TURN) {+ throw new Error(+ `Sub-agent limit reached: this turn already started ${OMNIRUSH_SWARM_MAX_PER_TURN} sub-agents. `+ + "Do not retry: do the remaining work yourself.",+ );+ }+ tree.started += 1;+ if (typeof call.callID === "string" && call.callID) {+ tree.running.set(call.callID, now);+ remember(calls, call.callID, root, MAX_TRACKED_SESSIONS);+ }+ },++ "tool.execute.after": async (call: { tool: string; callID: string }) => {+ if (call?.tool === "task") finish(call.callID);+ },++ "experimental.chat.system.transform": async (request: { sessionID?: string }, output: { system: string[] }) => {+ const directory = input?.directory;+ if (!directory || typeof request?.sessionID !== "string" || !Array.isArray(output?.system)) return;+ if ((await parentOf(request.sessionID)) === null) return;+ if (!existsSync(join(directory, OMNIRUSH_SWARM_FILE))) return;+ const { depth } = await locate(request.sessionID);+ output.system.push(omnirushSwarmSubagentNote(Math.min(Math.max(depth, 1), OMNIRUSH_SUBAGENT_DEPTH)));+ },+ };+};diff --git a/apps/server/src/workspace-collector.server.e2e.test.ts b/apps/server/src/workspace-collector.server.e2e.test.tsindex 65f28356..84875fbc 100644--- a/apps/server/src/workspace-collector.server.e2e.test.ts+++ b/apps/server/src/workspace-collector.server.e2e.test.ts@@ -109,6 +109,9 @@ function startMockEngine(input: { provider: string; model: string; history?: Engconst root: EngineMessage[] = [...(input.history ?? [])];const child: EngineMessage[] = [];const grandchild: EngineMessage[] = [];+ // A swarm three layers deep, and a fourth layer past the capture depth.+ const great: EngineMessage[] = [];+ const tooDeep: EngineMessage[] = [];const workflow: EngineMessage[] = [];const prompts: unknown[] = [];const workflowPrompts: unknown[] = [];@@ -176,6 +179,8 @@ function startMockEngine(input: { provider: string; model: string; history?: Engroot.push(message("ses_root", `user_${turn}`, "user", `prompt ${turn}`), message("ses_root", `assistant_${turn}`, "assistant", `answer ${turn}`));if (turn === 1 || turn === 2) child.push(message("ses_child", `child_${turn}`, "assistant", `child answer ${turn} for [email protected]`));if (turn === 1 || turn === 3) grandchild.push(message("ses_grandchild", `grand_${turn}`, "assistant", `grandchild answer ${turn}`));+ if (turn === 1) great.push(message("ses_great", `great_${turn}`, "assistant", `great-grandchild answer ${turn}`));+ if (turn === 1) tooDeep.push(message("ses_toodeep", `deep_${turn}`, "assistant", `too deep ${turn}`));setTimeout(() => { busy = false; }, control.busyMs);return new Response(null, { status: 204 });}@@ -188,7 +193,11 @@ function startMockEngine(input: { provider: string; model: string; history?: Engif (pathname === "/session/ses_child/message") return messagePage(url, child);if (pathname === "/session/ses_child/children") return Response.json([session("ses_grandchild", "ses_child")]);if (pathname === "/session/ses_grandchild/message") return messagePage(url, grandchild);- if (pathname === "/session/ses_grandchild/children") return Response.json([]);+ if (pathname === "/session/ses_grandchild/children") return Response.json([session("ses_great", "ses_grandchild")]);+ if (pathname === "/session/ses_great/message") return messagePage(url, great);+ if (pathname === "/session/ses_great/children") return Response.json([session("ses_toodeep", "ses_great")]);+ if (pathname === "/session/ses_toodeep/message") return messagePage(url, tooDeep);+ if (pathname === "/session/ses_toodeep/children") return Response.json([]);if (pathname === "/session/ses_root/todo") return Response.json([]);return Response.json({ code: "not_found", message: `Not found: ${request.method} ${pathname}` }, { status: 404 });},@@ -463,15 +472,19 @@ describe("workspace collector server integration", () => {provider_id: "omnirush", model_id: "gpt-5.6-sol", variant: "high", agent: "build",});const children = events(trace).filter((event) => event.type === "session.child");- expect(children.map((event) => [event.data?.child_session_id, event.data?.parent_session_id, event.data?.title, event.data?.agent])).toEqual([- ["ses_child", "ses_root", "Subtask ses_child", "build"],- ["ses_grandchild", "ses_child", "Subtask ses_grandchild", "build"],+ // Every swarm layer the engine allows (3) is captured with its parent and+ // depth; a fourth layer is not walked.+ expect(children.map((event) => [event.data?.child_session_id, event.data?.parent_session_id, event.data?.depth, event.data?.title, event.data?.agent])).toEqual([+ ["ses_child", "ses_root", 1, "Subtask ses_child", "build"],+ ["ses_grandchild", "ses_child", 2, "Subtask ses_grandchild", "build"],+ ["ses_great", "ses_grandchild", 3, "Subtask ses_great", "build"],]);+ expect(JSON.stringify(children)).not.toContain("ses_toodeep");expect((children[0]?.data?.messages as unknown[]).length).toBe(1);expect(JSON.stringify(children)).not.toContain("[email protected]");- expect(trace.session).toEqual({ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild"] });+ expect(trace.session).toEqual({ provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild", "ses_great"] });const end = anthropic.uploads.at(-1)!.envelope;- expect(end.session.child_session_ids).toEqual(["ses_child", "ses_grandchild"]);+ expect(end.session.child_session_ids).toEqual(["ses_child", "ses_grandchild", "ses_great"]);expect(end.session.provider_id).toBe("anthropic");// The prompt and turn milestones are both recorded even though nothing changed.expect(events(trace).filter((event) => event.type === "collector.trigger").map((event) => event.data)).toEqual([@@ -496,7 +509,7 @@ describe("workspace collector server integration", () => {const childEvents = (envelope: Envelope | undefined) => events(envelope).filter((event) => event.type === "session.child").map((event) => [event.data?.child_session_id, (event.data?.messages as Array<{ info: { id: string } }>).map((message) => message.info.id)]);- expect(childEvents(turnOne)).toEqual([["ses_child", ["child_1"]], ["ses_grandchild", ["grand_1"]]]);+ expect(childEvents(turnOne)).toEqual([["ses_child", ["child_1"]], ["ses_grandchild", ["grand_1"]], ["ses_great", ["great_1"]]]);// Turn 2: only the child spoke again, and only its new message is uploaded.expect(childEvents(turnTwo)).toEqual([["ses_child", ["child_2"]]]);expect(events(turnTwo).find((event) => event.type === "turn.completed")?.data).toEqual({@@ -511,7 +524,7 @@ describe("workspace collector server integration", () => {await second.stop();const resumedStart = gateway.uploads.find((upload) => upload.envelope.snapshot_type === "start" && upload.envelope.session_segment === 2)!;expect(resumedStart.envelope.session_resumed).toBe(true);- expect(resumedStart.envelope.session).toEqual({ provider_id: "openai", model_id: "gpt-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild"] });+ expect(resumedStart.envelope.session).toEqual({ provider_id: "openai", model_id: "gpt-5", variant: "high", child_session_ids: ["ses_child", "ses_grandchild", "ses_great"] });const turnThree = traces(gateway.uploads)[2]!;expect(turnThree.session_resumed).toBe(true);expect(childEvents(turnThree)).toEqual([["ses_grandchild", ["grand_3"]]]);diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.tsindex 554b3405..d16ab90f 100644--- a/apps/server/src/workspace-collector.ts+++ b/apps/server/src/workspace-collector.ts@@ -217,6 +217,8 @@ export type CollectorSessionBlock = {export type CollectorChildSession = {childSessionId: string;parentSessionId: string;+ /** Sub-agent layer below the root session: 1 for a child, 2 for a grandchild, ... */+ depth?: number;title: string | null;agent: string | null;/** Engine messages of the child that are new since the last checkpoint. */@@ -3686,6 +3688,7 @@ export class WorkspaceCollector {this.appendTrace(state, "session.child", {child_session_id: child.childSessionId,parent_session_id: child.parentSessionId,+ ...(Number.isSafeInteger(child.depth) && child.depth! >= 1 && child.depth! <= MAX_COLLECTOR_CHILD_SESSION_DEPTH ? { depth: child.depth } : {}),title: child.title ? clampCollectorText(child.title, MAX_GIT_SUBJECT_CHARS) : null,agent: child.agent ? clampCollectorText(child.agent, MAX_ENVIRONMENT_FIELD_CHARS) : null,messages: child.messages,