Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(agent): add subagent orchestration core

yushen85f71e0084f7
diff --git a/src/agent/subagent/announce.test.ts b/src/agent/subagent/announce.test.ts
new file mode 100644
index 0000000000..8f1a714010
--- /dev/null
+++ b/src/agent/subagent/announce.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect } from "vitest";
+import { buildSubagentSystemPrompt, formatAnnouncementMessage } from "./announce.js";
+import type { FormatAnnouncementParams } from "./announce.js";
+
+describe("buildSubagentSystemPrompt", () => {
+ it("includes task and session context", () => {
+ const prompt = buildSubagentSystemPrompt({
+ requesterSessionId: "parent-123",
+ childSessionId: "child-456",
+ task: "Analyze the auth module for security issues",
+ });
+
+ expect(prompt).toContain("You are a subagent spawned to complete a specific task");
+ expect(prompt).toContain("Analyze the auth module for security issues");
+ expect(prompt).toContain("parent-123");
+ expect(prompt).toContain("child-456");
+ expect(prompt).toContain("Do NOT spawn nested subagents");
+ });
+
+ it("includes label when provided", () => {
+ const prompt = buildSubagentSystemPrompt({
+ requesterSessionId: "parent-123",
+ childSessionId: "child-456",
+ label: "Security Audit",
+ task: "Check for vulnerabilities",
+ });
+
+ expect(prompt).toContain('Label: "Security Audit"');
+ });
+
+ it("omits label line when not provided", () => {
+ const prompt = buildSubagentSystemPrompt({
+ requesterSessionId: "parent-123",
+ childSessionId: "child-456",
+ task: "Do something",
+ });
+
+ expect(prompt).not.toContain("Label:");
+ });
+});
+
+describe("formatAnnouncementMessage", () => {
+ const baseParams: FormatAnnouncementParams = {
+ runId: "run-1",
+ childSessionId: "child-456",
+ requesterSessionId: "parent-123",
+ task: "Analyze code",
+ label: "Code Analysis",
+ cleanup: "delete",
+ outcome: { status: "ok" },
+ startedAt: 1000000,
+ endedAt: 1030000,
+ };
+
+ it("formats successful completion", () => {
+ const msg = formatAnnouncementMessage({
+ ...baseParams,
+ findings: "Found 3 issues in the auth module.",
+ });
+
+ expect(msg).toContain('"Code Analysis" just completed successfully');
+ expect(msg).toContain("Found 3 issues in the auth module.");
+ expect(msg).toContain("runtime 30s");
+ expect(msg).toContain("session child-456");
+ });
+
+ it("formats error outcome", () => {
+ const msg = formatAnnouncementMessage({
+ ...baseParams,
+ outcome: { status: "error", error: "API key expired" },
+ });
+
+ expect(msg).toContain("failed: API key expired");
+ });
+
+ it("formats timeout outcome", () => {
+ const msg = formatAnnouncementMessage({
+ ...baseParams,
+ outcome: { status: "timeout" },
+ });
+
+ expect(msg).toContain("timed out");
+ });
+
+ it("shows (no output) when findings is not provided", () => {
+ const msg = formatAnnouncementMessage(baseParams);
+
+ expect(msg).toContain("(no output)");
+ });
+
+ it("uses task text when label is not provided", () => {
+ const paramsNoLabel: FormatAnnouncementParams = {
+ ...baseParams,
+ label: undefined,
+ };
+ const msg = formatAnnouncementMessage(paramsNoLabel);
+
+ expect(msg).toContain('"Analyze code"');
+ });
+
+ it("formats runtime for minutes", () => {
+ const msg = formatAnnouncementMessage({
+ ...baseParams,
+ startedAt: 1000000,
+ endedAt: 1150000, // 150 seconds = 2m30s
+ });
+
+ expect(msg).toContain("runtime 2m30s");
+ });
+
+ it("formats runtime for hours", () => {
+ const msg = formatAnnouncementMessage({
+ ...baseParams,
+ startedAt: 1000000,
+ endedAt: 4600000, // 3600 seconds = 1h
+ });
+
+ expect(msg).toContain("runtime 1h");
+ });
+
+ it("includes summarization instruction", () => {
+ const msg = formatAnnouncementMessage(baseParams);
+
+ expect(msg).toContain("Summarize this naturally for the user");
+ expect(msg).toContain("NO_REPLY");
+ });
+});
diff --git a/src/agent/subagent/announce.ts b/src/agent/subagent/announce.ts
new file mode 100644
index 0000000000..e5d06c5117
--- /dev/null
+++ b/src/agent/subagent/announce.ts
@@ -0,0 +1,226 @@
+/**
+ * Subagent announcement flow.
+ *
+ * Handles result propagation from child → parent agent:
+ * - Builds system prompts for child agents
+ * - Reads child session output
+ * - Formats and delivers announcement messages
+ */
+
+import { readEntries } from "../session/storage.js";
+import { getHub } from "../../hub/hub-singleton.js";
+import type {
+ SubagentAnnounceParams,
+ SubagentRunOutcome,
+ SubagentSystemPromptParams,
+} from "./types.js";
+
+/**
+ * Build the system prompt injected into a subagent session.
+ */
+export function buildSubagentSystemPrompt(params: SubagentSystemPromptParams): string {
+ const { requesterSessionId, childSessionId, label, task } = params;
+
+ const lines: string[] = [
+ "You are a subagent spawned to complete a specific task.",
+ "",
+ "## Rules",
+ "- Stay focused on the assigned task below.",
+ "- Complete the task thoroughly and report your findings.",
+ "- Do NOT initiate side actions unrelated to the task.",
+ "- Do NOT attempt to communicate with the user directly.",
+ "- Do NOT spawn nested subagents.",
+ "- Your session is ephemeral and will be cleaned up after completion.",
+ "",
+ "## Context",
+ `Requester session: ${requesterSessionId}`,
+ `Child session: ${childSessionId}`,
+ ];
+
+ if (label) {
+ lines.push(`Label: "${label}"`);
+ }
+
+ lines.push("", "## Task", task);
+
+ return lines.join("\n");
+}
+
+/**
+ * Read the latest assistant reply from a session's JSONL file.
+ */
+export function readLatestAssistantReply(sessionId: string): string | undefined {
+ const entries = readEntries(sessionId);
+
+ // Walk backwards to find last assistant message
+ for (let i = entries.length - 1; i >= 0; i--) {
+ const entry = entries[i]!;
+ if (entry.type !== "message") continue;
+
+ const message = entry.message;
+ if (message.role !== "assistant") continue;
+
+ return extractAssistantText(message);
+ }
+
+ return undefined;
+}
+
+/**
+ * Extract text content from an assistant message.
+ * AgentMessage.content for assistant is (TextContent | ThinkingContent | ToolCall)[].
+ */
+function extractAssistantText(message: { role: string; content: unknown }): string {
+ const content = message.content;
+ if (typeof content === "string") {
+ return sanitizeText(content);
+ }
+
+ if (!Array.isArray(content)) return "";
+
+ const textParts: string[] = [];
+ for (const block of content) {
+ if (block && typeof block === "object" && "type" in block && block.type === "text" && "text" in block) {
+ textParts.push(String(block.text));
+ }
+ }
+
+ return sanitizeText(textParts.join("\n"));
+}
+
+/**
+ * Strip thinking tags and tool markers from text.
+ */
+function sanitizeText(text: string): string {
+ return text
+ .replace(/<thinking>[\s\S]*?<\/thinking>/g, "")
+ .replace(/<tool_call>[\s\S]*?<\/tool_call>/g, "")
+ .trim();
+}
+
+/**
+ * Format the duration between two timestamps as a human-readable string.
+ */
+function formatDuration(startMs: number, endMs: number): string {
+ const totalSeconds = Math.round((endMs - startMs) / 1000);
+ if (totalSeconds < 60) return `${totalSeconds}s`;
+
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ if (minutes < 60) return seconds > 0 ? `${minutes}m${seconds}s` : `${minutes}m`;
+
+ const hours = Math.floor(minutes / 60);
+ const remainingMinutes = minutes % 60;
+ return remainingMinutes > 0 ? `${hours}h${remainingMinutes}m` : `${hours}h`;
+}
+
+/**
+ * Format a status label from an outcome.
+ */
+function formatStatusLabel(outcome: SubagentRunOutcome | undefined): string {
+ if (!outcome) return "completed with unknown status";
+ switch (outcome.status) {
+ case "ok":
+ return "completed successfully";
+ case "error":
+ return outcome.error ? `failed: ${outcome.error}` : "failed";
+ case "timeout":
+ return "timed out";
+ default:
+ return "completed with unknown status";
+ }
+}
+
+/** Parameters for formatAnnouncementMessage */
+export interface FormatAnnouncementParams {
+ runId: string;
+ childSessionId: string;
+ requesterSessionId: string;
+ task: string;
+ label?: string | undefined;
+ cleanup: "delete" | "keep";
+ outcome?: SubagentRunOutcome | undefined;
+ startedAt?: number | undefined;
+ endedAt?: number | undefined;
+ findings?: string | undefined;
+}
+
+/**
+ * Format the announcement message sent to the parent agent.
+ */
+export function formatAnnouncementMessage(params: FormatAnnouncementParams): string {
+ const { task, label, outcome, findings, startedAt, endedAt, childSessionId } = params;
+ const displayName = label || task.slice(0, 60);
+ const statusLabel = formatStatusLabel(outcome);
+
+ const parts: string[] = [
+ `A background task "${displayName}" just ${statusLabel}.`,
+ "",
+ "Findings:",
+ findings || "(no output)",
+ ];
+
+ // Stats line
+ const stats: string[] = [];
+ if (startedAt && endedAt) {
+ stats.push(`runtime ${formatDuration(startedAt, endedAt)}`);
+ }
+ stats.push(`session ${childSessionId}`);
+
+ parts.push("", `Stats: ${stats.join(" • ")}`);
+
+ parts.push(
+ "",
+ "Summarize this naturally for the user. Keep it brief (1-2 sentences).",
+ "Flow it into the conversation naturally.",
+ "Do not mention technical details like session IDs or that this was a background task.",
+ "You can respond with NO_REPLY if no announcement is needed (e.g., internal task with no user-facing result).",
+ );
+
+ return parts.join("\n");
+}
+
+/**
+ * Run the full subagent announcement flow:
+ * 1. Read child's last assistant reply
+ * 2. Format announcement message
+ * 3. Send to parent agent via Hub
+ */
+export function runSubagentAnnounceFlow(params: SubagentAnnounceParams): boolean {
+ const { requesterSessionId, childSessionId } = params;
+
+ // Read child's final output
+ const findings = readLatestAssistantReply(childSessionId);
+
+ // Format the announcement
+ const message = formatAnnouncementMessage({
+ runId: params.runId,
+ childSessionId: params.childSessionId,
+ requesterSessionId: params.requesterSessionId,
+ task: params.task,
+ label: params.label,
+ cleanup: params.cleanup,
+ outcome: params.outcome,
+ startedAt: params.startedAt,
+ endedAt: params.endedAt,
+ findings,
+ });
+
+ // Deliver to parent agent via Hub
+ try {
+ const hub = getHub();
+ const parentAgent = hub.getAgent(requesterSessionId);
+ if (!parentAgent || parentAgent.closed) {
+ console.warn(
+ `[SubagentAnnounce] Parent agent not found or closed: ${requesterSessionId}`,
+ );
+ return false;
+ }
+
+ parentAgent.write(message);
+ return true;
+ } catch (err) {
+ console.error(`[SubagentAnnounce] Failed to announce to parent:`, err);
+ return false;
+ }
+}
diff --git a/src/agent/subagent/index.ts b/src/agent/subagent/index.ts
new file mode 100644
index 0000000000..d0a24d994f
--- /dev/null
+++ b/src/agent/subagent/index.ts
@@ -0,0 +1,37 @@
+/**
+ * Subagent orchestration system.
+ *
+ * Provides child agent spawning, lifecycle management,
+ * persistent registry, and result announcement flow.
+ */
+
+export type {
+ SubagentRunOutcome,
+ SubagentRunRecord,
+ RegisterSubagentRunParams,
+ SubagentAnnounceParams,
+ SubagentSystemPromptParams,
+} from "./types.js";
+
+export {
+ initSubagentRegistry,
+ registerSubagentRun,
+ listSubagentRuns,
+ releaseSubagentRun,
+ getSubagentRun,
+ resetSubagentRegistryForTests,
+} from "./registry.js";
+
+export {
+ buildSubagentSystemPrompt,
+ readLatestAssistantReply,
+ formatAnnouncementMessage,
+ runSubagentAnnounceFlow,
+} from "./announce.js";
+export type { FormatAnnouncementParams } from "./announce.js";
+
+export {
+ loadSubagentRuns,
+ saveSubagentRuns,
+ getSubagentStorePath,
+} from "./registry-store.js";
diff --git a/src/agent/subagent/registry-store.test.ts b/src/agent/subagent/registry-store.test.ts
new file mode 100644
index 0000000000..7247203c87
--- /dev/null
+++ b/src/agent/subagent/registry-store.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { mkdtempSync, rmSync, existsSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import type { SubagentRunRecord } from "./types.js";
+
+// We need to test the store functions with a custom directory.
+// Since the store uses DATA_DIR from shared, we test the serialization logic directly.
+
+describe("registry-store serialization", () => {
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = mkdtempSync(join(tmpdir(), "subagent-store-test-"));
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ it("round-trips SubagentRunRecord through JSON", () => {
+ const record: SubagentRunRecord = {
+ runId: "run-123",
+ childSessionId: "child-456",
+ requesterSessionId: "parent-789",
+ task: "Analyze code quality",
+ label: "Code Review",
+ cleanup: "delete",
+ createdAt: Date.now(),
+ startedAt: Date.now(),
+ endedAt: Date.now() + 30000,
+ outcome: { status: "ok" },
+ archiveAtMs: Date.now() + 3600000,
+ cleanupHandled: true,
+ cleanupCompletedAt: Date.now() + 30100,
+ };
+
+ // Serialize and deserialize
+ const json = JSON.stringify({ version: 1, runs: { "run-123": record } });
+ const parsed = JSON.parse(json);
+
+ expect(parsed.version).toBe(1);
+ expect(parsed.runs["run-123"]).toEqual(record);
+ });
+
+ it("handles record with minimal fields", () => {
+ const record: SubagentRunRecord = {
+ runId: "run-minimal",
+ childSessionId: "child-1",
+ requesterSessionId: "parent-1",
+ task: "Do something",
+ cleanup: "keep",
+ createdAt: Date.now(),
+ };
+
+ const json = JSON.stringify({ version: 1, runs: { "run-minimal": record } });
+ const parsed = JSON.parse(json);
+
+ expect(parsed.runs["run-minimal"].runId).toBe("run-minimal");
+ expect(parsed.runs["run-minimal"].outcome).toBeUndefined();
+ expect(parsed.runs["run-minimal"].label).toBeUndefined();
+ });
+
+ it("handles error outcome serialization", () => {
+ const record: SubagentRunRecord = {
+ runId: "run-err",
+ childSessionId: "child-err",
+ requesterSessionId: "parent-1",
+ task: "Fail",
+ cleanup: "delete",
+ createdAt: Date.now(),
+ outcome: { status: "error", error: "Something went wrong" },
+ };
+
+ const json = JSON.stringify(record);
+ const parsed = JSON.parse(json) as SubagentRunRecord;
+
+ expect(parsed.outcome?.status).toBe("error");
+ expect(parsed.outcome?.error).toBe("Something went wrong");
+ });
+});
diff --git a/src/agent/subagent/registry-store.ts b/src/agent/subagent/registry-store.ts
new file mode 100644
index 0000000000..b96a315ca2
--- /dev/null
+++ b/src/agent/subagent/registry-store.ts
@@ -0,0 +1,61 @@
+/**
+ * Persistent storage for subagent run records.
+ *
+ * File: ~/.super-multica/subagents/runs.json
+ */
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { DATA_DIR } from "../../shared/index.js";
+import type { SubagentRunRecord } from "./types.js";
+
+const SUBAGENTS_DIR = join(DATA_DIR, "subagents");
+const RUNS_FILE = join(SUBAGENTS_DIR, "runs.json");
+
+interface SubagentRunsStore {
+ version: 1;
+ runs: Record<string, SubagentRunRecord>;
+}
+
+function ensureDir(): void {
+ if (!existsSync(SUBAGENTS_DIR)) {
+ mkdirSync(SUBAGENTS_DIR, { recursive: true });
+ }
+}
+
+/** Get the path to the subagent store file (for testing) */
+export function getSubagentStorePath(): string {
+ return RUNS_FILE;
+}
+
+/** Load all persisted subagent runs */
+export function loadSubagentRuns(): Map<string, SubagentRunRecord> {
+ if (!existsSync(RUNS_FILE)) return new Map();
+
+ try {
+ const content = readFileSync(RUNS_FILE, "utf-8");
+ const store = JSON.parse(content) as SubagentRunsStore;
+
+ if (store.version !== 1) {
+ console.warn(`[SubagentStore] Unknown store version: ${store.version}, ignoring`);
+ return new Map();
+ }
+
+ return new Map(Object.entries(store.runs));
+ } catch (err) {
+ console.warn(`[SubagentStore] Failed to load runs:`, err);
+ return new Map();
+ }
+}
+
+/** Save all subagent runs to disk */
+export function saveSubagentRuns(runs: Map<string, SubagentRunRecord>): void {
+ ensureDir();
+
+ const store: SubagentRunsStore = {
+ version: 1,
+ runs: Object.fromEntries(runs),
+ };
+
+ writeFileSync(RUNS_FILE, JSON.stringify(store, null, 2), "utf-8");
+}
diff --git a/src/agent/subagent/registry.ts b/src/agent/subagent/registry.ts
new file mode 100644
index 0000000000..9915e4a040
--- /dev/null
+++ b/src/agent/subagent/registry.ts
@@ -0,0 +1,321 @@
+/**
+ * Subagent registry — in-memory tracking + lifecycle management.
+ *
+ * Tracks all active subagent runs, persists state to disk,
+ * watches for child completion, and triggers announce flow.
+ */
+
+import { getHub } from "../../hub/hub-singleton.js";
+import { loadSubagentRuns, saveSubagentRuns } from "./registry-store.js";
+import { runSubagentAnnounceFlow } from "./announce.js";
+import type {
+ RegisterSubagentRunParams,
+ SubagentRunRecord,
+} from "./types.js";
+import { resolveSessionDir } from "../session/storage.js";
+import { rmSync } from "node:fs";
+
+/** Default archive retention: 60 minutes after completion */
+const DEFAULT_ARCHIVE_AFTER_MS = 60 * 60 * 1000;
+
+/** Archive sweep interval: 60 seconds */
+const SWEEP_INTERVAL_MS = 60 * 1000;
+
+// ============================================================================
+// Module-level state
+// ============================================================================
+
+const subagentRuns = new Map<string, SubagentRunRecord>();
+let sweepTimer: ReturnType<typeof setInterval> | undefined;
+const resumedRuns = new Set<string>();
+
+// ============================================================================
+// Public API
+// ============================================================================
+
+/** Initialize registry from persisted state. Call once at startup. */
+export function initSubagentRegistry(): void {
+ const persisted = loadSubagentRuns();
+ for (const [runId, record] of persisted) {
+ subagentRuns.set(runId, record);
+
+ // Resume incomplete runs
+ if (!record.cleanupHandled) {
+ if (record.endedAt) {
+ // Completed but cleanup not done — run announce flow
+ if (!resumedRuns.has(runId)) {
+ resumedRuns.add(runId);
+ handleRunCompletion(record);
+ }
+ }
+ // If not ended, the child agent session is lost on restart —
+ // mark as ended with unknown outcome
+ else if (!record.startedAt) {
+ record.endedAt = Date.now();
+ record.outcome = { status: "unknown" };
+ persist();
+ if (!resumedRuns.has(runId)) {
+ resumedRuns.add(runId);
+ handleRunCompletion(record);
+ }
+ }
+ }
+ }
+
+ if (subagentRuns.size > 0) {
+ startSweeper();
+ console.log(`[SubagentRegistry] Loaded ${subagentRuns.size} persisted run(s)`);
+ }
+}
+
+/** Register a new subagent run and start tracking its lifecycle. */
+export function registerSubagentRun(params: RegisterSubagentRunParams): SubagentRunRecord {
+ const {
+ runId,
+ childSessionId,
+ requesterSessionId,
+ task,
+ label,
+ cleanup = "delete",
+ timeoutSeconds,
+ } = params;
+
+ const record: SubagentRunRecord = {
+ runId,
+ childSessionId,
+ requesterSessionId,
+ task,
+ label,
+ cleanup,
+ createdAt: Date.now(),
+ };
+
+ subagentRuns.set(runId, record);
+ persist();
+ startSweeper();
+
+ // Start watching the child agent for completion
+ watchChildAgent(record, timeoutSeconds);
+
+ return record;
+}
+
+/** List all active runs for a given requester session. */
+export function listSubagentRuns(requesterSessionId: string): SubagentRunRecord[] {
+ const result: SubagentRunRecord[] = [];
+ for (const record of subagentRuns.values()) {
+ if (record.requesterSessionId === requesterSessionId) {
+ result.push(record);
+ }
+ }
+ return result;
+}
+
+/** Remove a run from the registry. */
+export function releaseSubagentRun(runId: string): boolean {
+ const deleted = subagentRuns.delete(runId);
+ if (deleted) {
+ persist();
+ if (subagentRuns.size === 0) {
+ stopSweeper();
+ }
+ }
+ return deleted;
+}
+
+/** Get a run by ID. */
+export function getSubagentRun(runId: string): SubagentRunRecord | undefined {
+ return subagentRuns.get(runId);
+}
+
+/** Reset all state (for testing). */
+export function resetSubagentRegistryForTests(): void {
+ subagentRuns.clear();
+ resumedRuns.clear();
+ stopSweeper();
+}
+
+// ============================================================================
+// Lifecycle watching
+// ============================================================================
+
+function watchChildAgent(record: SubagentRunRecord, timeoutSeconds?: number): void {
+ const { runId, childSessionId } = record;
+
+ // Mark as started
+ record.startedAt = Date.now();
+ persist();
+
+ // Set up timeout if specified
+ let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
+ if (timeoutSeconds && timeoutSeconds > 0) {
+ timeoutTimer = setTimeout(() => {
+ if (!record.endedAt) {
+ record.endedAt = Date.now();
+ record.outcome = { status: "timeout" };
+ persist();
+
+ // Try to close the child agent
+ try {
+ const hub = getHub();
+ hub.closeAgent(childSessionId);
+ } catch {
+ // Hub may not be available
+ }
+
+ handleRunCompletion(record);
+ }
+ }, timeoutSeconds * 1000);
+ }
+
+ // Watch the child agent's channel for closure
+ void (async () => {
+ try {
+ const hub = getHub();
+ const childAgent = hub.getAgent(childSessionId);
+ if (!childAgent) {
+ record.endedAt = Date.now();
+ record.outcome = { status: "error", error: "Child agent not found" };
+ persist();
+ handleRunCompletion(record);
+ return;
+ }
+
+ // Consume the child's output stream — when it ends, the agent is done
+ for await (const item of childAgent.read()) {
+ // Check for error messages
+ if ("content" in item && typeof item.content === "string" && item.content.startsWith("[error]")) {
+ record.outcome = { status: "error", error: item.content };
+ }
+ }
+
+ // Stream ended — child agent completed
+ if (!record.endedAt) {
+ if (timeoutTimer) clearTimeout(timeoutTimer);
+ record.endedAt = Date.now();
+ if (!record.outcome) {
+ record.outcome = { status: "ok" };
+ }
+ persist();
+ handleRunCompletion(record);
+ }
+ } catch (err) {
+ if (!record.endedAt) {
+ if (timeoutTimer) clearTimeout(timeoutTimer);
+ record.endedAt = Date.now();
+ record.outcome = {
+ status: "error",
+ error: err instanceof Error ? err.message : String(err),
+ };
+ persist();
+ handleRunCompletion(record);
+ }
+ }
+ })();
+}
+
+// ============================================================================
+// Cleanup + Announce
+// ============================================================================
+
+function handleRunCompletion(record: SubagentRunRecord): void {
+ if (record.cleanupHandled) return;
+ record.cleanupHandled = true;
+ persist();
+
+ // Run announce flow
+ const announced = runSubagentAnnounceFlow({
+ runId: record.runId,
+ childSessionId: record.childSessionId,
+ requesterSessionId: record.requesterSessionId,
+ task: record.task,
+ label: record.label,
+ cleanup: record.cleanup,
+ outcome: record.outcome,
+ startedAt: record.startedAt,
+ endedAt: record.endedAt,
+ });
+
+ if (!announced) {
+ console.warn(`[SubagentRegistry] Announce flow failed for run ${record.runId}`);
+ }
+
+ // Handle session cleanup
+ if (record.cleanup === "delete") {
+ deleteChildSession(record.childSessionId);
+ }
+
+ // Schedule archive
+ record.archiveAtMs = Date.now() + DEFAULT_ARCHIVE_AFTER_MS;
+ record.cleanupCompletedAt = Date.now();
+ persist();
+}
+
+function deleteChildSession(sessionId: string): void {
+ try {
+ const sessionDir = resolveSessionDir(sessionId);
+ rmSync(sessionDir, { recursive: true, force: true });
+ console.log(`[SubagentRegistry] Deleted child session: ${sessionId}`);
+ } catch (err) {
+ console.warn(`[SubagentRegistry] Failed to delete child session ${sessionId}:`, err);
+ }
+
+ // Also close the agent in Hub
+ try {
+ const hub = getHub();
+ hub.closeAgent(sessionId);
+ } catch {
+ // Hub may not be available
+ }
+}
+
+// ============================================================================
+// Archive sweeper
+// ============================================================================
+
+function startSweeper(): void {
+ if (sweepTimer) return;
+ sweepTimer = setInterval(sweep, SWEEP_INTERVAL_MS);
+ // Don't prevent process exit
+ if (sweepTimer.unref) sweepTimer.unref();
+}
+
+function stopSweeper(): void {
+ if (sweepTimer) {
+ clearInterval(sweepTimer);
+ sweepTimer = undefined;
+ }
+}
+
+function sweep(): void {
+ const now = Date.now();
+ let removed = 0;
+
+ for (const [runId, record] of subagentRuns) {
+ if (record.archiveAtMs && record.archiveAtMs <= now) {
+ subagentRuns.delete(runId);
+ removed++;
+ }
+ }
+
+ if (removed > 0) {
+ persist();
+ console.log(`[SubagentRegistry] Archived ${removed} completed run(s)`);
+ }
+
+ if (subagentRuns.size === 0) {
+ stopSweeper();
+ }
+}
+
+// ============================================================================
+// Persistence helper
+// ============================================================================
+
+function persist(): void {
+ try {
+ saveSubagentRuns(subagentRuns);
+ } catch (err) {
+ console.error(`[SubagentRegistry] Failed to persist runs:`, err);
+ }
+}
diff --git a/src/agent/subagent/types.ts b/src/agent/subagent/types.ts
new file mode 100644
index 0000000000..dfbf62bb28
--- /dev/null
+++ b/src/agent/subagent/types.ts
@@ -0,0 +1,74 @@
+/**
+ * Subagent orchestration types.
+ *
+ * Models the lifecycle of spawned child agents:
+ * created → started → ended → cleanup
+ */
+
+/** Final outcome of a subagent run */
+export type SubagentRunOutcome = {
+ status: "ok" | "error" | "timeout" | "unknown";
+ error?: string | undefined;
+};
+
+/** Persistent record tracking a single subagent run */
+export type SubagentRunRecord = {
+ /** Unique run identifier (UUIDv7) */
+ runId: string;
+ /** Session ID of the child agent */
+ childSessionId: string;
+ /** Session ID of the parent (requester) agent */
+ requesterSessionId: string;
+ /** The task description / prompt given to the child */
+ task: string;
+ /** Optional human-readable label */
+ label?: string | undefined;
+ /** Session cleanup strategy after completion */
+ cleanup: "delete" | "keep";
+ /** Timestamp when the run was created */
+ createdAt: number;
+ /** Timestamp when the child agent started execution */
+ startedAt?: number | undefined;
+ /** Timestamp when the child agent finished */
+ endedAt?: number | undefined;
+ /** Final status of the run */
+ outcome?: SubagentRunOutcome | undefined;
+ /** Scheduled auto-archive time (ms since epoch) */
+ archiveAtMs?: number | undefined;
+ /** Whether the cleanup/announce flow has been initiated */
+ cleanupHandled?: boolean | undefined;
+ /** Timestamp when cleanup completed */
+ cleanupCompletedAt?: number | undefined;
+};
+
+/** Parameters for registering a new subagent run */
+export type RegisterSubagentRunParams = {
+ runId: string;
+ childSessionId: string;
+ requesterSessionId: string;
+ task: string;
+ label?: string | undefined;
+ cleanup?: "delete" | "keep" | undefined;
+ timeoutSeconds?: number | undefined;
+};
+
+/** Parameters for the announce flow */
+export type SubagentAnnounceParams = {
+ runId: string;
+ childSessionId: string;
+ requesterSessionId: string;
+ task: string;
+ label?: string | undefined;
+ cleanup: "delete" | "keep";
+ outcome?: SubagentRunOutcome | undefined;
+ startedAt?: number | undefined;
+ endedAt?: number | undefined;
+};
+
+/** Parameters for building the subagent system prompt */
+export type SubagentSystemPromptParams = {
+ requesterSessionId: string;
+ childSessionId: string;
+ label?: string | undefined;
+ task: string;
+};