Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(agent): background subagents, so a parent can keep working in parallel (#175)

Abdurrahman Fakhrulfc57e6df5be3
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index af44ebb8..c59e92d6 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,7 +8,8 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `agent` surgical edit, content search, glob and a todo list
+- `agent` background subagents, so a parent can keep working in parallel
+- `agent` surgical edit, content search, glob and a todo list (#173)
- `perf` hydration mark chain, and the LCP conclusion it overturns
- `tui` close the opencode TUI gap on the seams MSO already owns (#166)
@@ -34,7 +35,6 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Docs**
-- `bench` capture the measured before-baseline for the Phase 4/5 comparison
- `migration` Phase 5 edge-behaviour spike, verified with curl
- `progress` record Phase 2 completion, the bun install fix and the Phase 6 no-go
- `progress` record the perf gate and the numbers it retracted
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 269e8797..03eb1319 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.17.0 version=2026.10.18.3 tools=123 read=61 write=39 exec=23 -->
+<!-- mcp-toolset: server=1.17.0 version=2026.10.18.3 tools=126 read=62 write=39 exec=25 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.17.0` |
| Toolset | `2026.10.18.3` |
| Toolset changed at | `2026-10-18T13:24:00+00:00` |
-| Transport tools | **125** |
-| Model/operator tools | **123** |
-| Read | **61** |
+| Transport tools | **128** |
+| Model/operator tools | **126** |
+| Read | **62** |
| Write | **39** |
-| Exec | **23** |
+| Exec | **25** |
| App-only bridges | **2** |
-### Read (61)
+### Read (62)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -30,6 +30,7 @@
- `agent_session_flow`
- `agent_session_resume`
- `agent_sessions_list`
+- `agent_subagent_status`
- `apps_list`
- `apps_logs`
- `browser_status`
@@ -124,12 +125,14 @@
- `workflow_finish`
- `workflow_start`
-### Exec (23)
+### Exec (25)
- `a2a_handoff`
- `a2a_message_send`
- `a2a_task_cancel`
+- `agent_subagent_cancel`
- `agent_subagent_run`
+- `agent_subagent_start`
- `browser_power`
- `exec_job_cancel`
- `exec_job_start`
@@ -157,20 +160,20 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.17.0 version=2026.10.18.3 tools=123 read=61 write=39 exec=23 app-only=2 total=125 -->
+<!-- mcp-chatgpt-profile: server=1.17.0 version=2026.10.18.3 tools=126 read=62 write=39 exec=25 app-only=2 total=128 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **125** |
-| ChatGPT model/operator tools | **123** |
-| Read | **61** |
+| ChatGPT transport tools | **128** |
+| ChatGPT model/operator tools | **126** |
+| Read | **62** |
| Write | **39** |
-| Exec | **23** |
+| Exec | **25** |
| App-only bridges | **2** |
-### ChatGPT read (61)
+### ChatGPT read (62)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -182,6 +185,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `agent_session_flow`
- `agent_session_resume`
- `agent_sessions_list`
+- `agent_subagent_status`
- `apps_list`
- `apps_logs`
- `browser_status`
@@ -276,12 +280,14 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `workflow_finish`
- `workflow_start`
-### ChatGPT exec (23)
+### ChatGPT exec (25)
- `a2a_handoff`
- `a2a_message_send`
- `a2a_task_cancel`
+- `agent_subagent_cancel`
- `agent_subagent_run`
+- `agent_subagent_start`
- `browser_power`
- `exec_job_cancel`
- `exec_job_start`
diff --git a/lib/agent/subagent-jobs.test.ts b/lib/agent/subagent-jobs.test.ts
new file mode 100644
index 00000000..57fd6e5d
--- /dev/null
+++ b/lib/agent/subagent-jobs.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ startSubagentJob,
+ getSubagentJob,
+ cancelSubagentJob,
+ _resetSubagentJobsForTest,
+ MAX_CONCURRENT_PER_PRINCIPAL,
+ MAX_RETAINED_JOBS,
+ RETENTION_MS,
+} from "./subagent-jobs";
+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+import type { CapabilityRunContext } from "@/lib/capabilities/tool";
+import type { SubagentOutcome, SubagentRunnerFn } from "./subagent-jobs";
+
+const stubCapabilities: CapabilityRuntime = { list: vi.fn(() => []), invoke: vi.fn() };
+const stubAuthority: CapabilityRunContext = { principal: "principal-1", scope: "exec" };
+const ok = (text: string): SubagentOutcome => ({ subagentId: "sub-1", name: "worker", status: "completed" as const, text, rounds: 1, toolCalls: [], maxScope: "read" as const });
+const base = { principal: "principal-1", parentSessionId: "session-1", objective: "obj", capabilities: stubCapabilities, authority: stubAuthority };
+
+describe("background subagent jobs", () => {
+ beforeEach(() => { _resetSubagentJobsForTest(); });
+
+ it("1. start returns a job id and running, and runner was invoked", async () => {
+ const runner = vi.fn(async () => ok("ok"));
+ const res = await startSubagentJob({ ...base, name: "analyzer" }, runner);
+ expect(res.jobId).toMatch(/^subagent_job_/);
+ expect(res.name).toBe("analyzer");
+ expect(res.status).toBe("running");
+ expect(runner).toHaveBeenCalled();
+ });
+
+ it("2. status reports completed with result once runner resolves", async () => {
+ let resolveRunner!: (val: SubagentOutcome) => void;
+ const runner = vi.fn<SubagentRunnerFn>(() => new Promise((resolve) => { resolveRunner = resolve; }));
+ const res = await startSubagentJob(base, runner);
+ let status = getSubagentJob(res.jobId, "principal-1");
+ expect(status.status).toBe("running");
+ expect(status.result).toBeUndefined();
+
+ resolveRunner(ok("analysis complete"));
+ await new Promise((r) => setTimeout(r, 10));
+ status = getSubagentJob(res.jobId, "principal-1");
+ expect(status.status).toBe("completed");
+ expect(status.result).toBe("analysis complete");
+ expect(status.finishedAt).toBeDefined();
+ expect(typeof status.elapsedMs).toBe("number");
+ });
+
+ it("3. status reports failed with error when runner rejects", async () => {
+ const runner = vi.fn(async () => { throw new Error("model context window exceeded"); });
+ const res = await startSubagentJob(base, runner);
+ await new Promise((r) => setTimeout(r, 10));
+ const status = getSubagentJob(res.jobId, "principal-1");
+ expect(status.status).toBe("failed");
+ expect(status.error).toBe("model context window exceeded");
+ });
+
+ it("4. cancel aborts the run and status becomes cancelled", async () => {
+ let observedSignal: AbortSignal | undefined;
+ const runner = vi.fn<SubagentRunnerFn>(async ({ authority }) => {
+ observedSignal = authority.signal;
+ return new Promise<SubagentOutcome>((_, reject) => {
+ authority.signal?.addEventListener("abort", () => reject(authority.signal?.reason || new Error("aborted")));
+ });
+ });
+ const res = await startSubagentJob(base, runner);
+ expect(observedSignal?.aborted).toBe(false);
+
+ const cancelled = cancelSubagentJob(res.jobId, "principal-1");
+ expect(cancelled.status).toBe("cancelled");
+ expect(observedSignal?.aborted).toBe(true);
+ await new Promise((r) => setTimeout(r, 10));
+ expect(getSubagentJob(res.jobId, "principal-1").status).toBe("cancelled");
+ });
+
+ it("5. second principal gets not found for another principal's job id", async () => {
+ const res = await startSubagentJob(base, vi.fn<SubagentRunnerFn>(() => new Promise(() => {})));
+ expect(() => getSubagentJob(res.jobId, "principal-2")).toThrow("subagent job not found");
+ expect(() => cancelSubagentJob(res.jobId, "principal-2")).toThrow("subagent job not found");
+ });
+
+ it("6. starting beyond concurrent cap fails with clear message", async () => {
+ const runner = vi.fn<SubagentRunnerFn>(() => new Promise(() => {}));
+ for (let i = 0; i < MAX_CONCURRENT_PER_PRINCIPAL; i++) await startSubagentJob(base, runner);
+ await expect(startSubagentJob(base, runner)).rejects.toThrow(`Too many active subagent jobs (max ${MAX_CONCURRENT_PER_PRINCIPAL})`);
+ });
+
+ it("7. finished job past retention window reports expired and drops result", async () => {
+ const res = await startSubagentJob(base, vi.fn(async () => ok("secret answer")));
+ await new Promise((r) => setTimeout(r, 10));
+ expect(getSubagentJob(res.jobId, "principal-1").result).toBe("secret answer");
+
+ const originalNow = Date.now;
+ try {
+ Date.now = () => originalNow() + RETENTION_MS + 10_000;
+ const status = getSubagentJob(res.jobId, "principal-1");
+ expect(status.status).toBe("expired");
+ expect(status.result).toBeUndefined();
+ } finally { Date.now = originalNow; }
+ });
+
+ it("8. total retained jobs capped and oldest finished evicted", async () => {
+ let done1!: (v: SubagentOutcome) => void, done2!: (v: SubagentOutcome) => void, callIdx = 0;
+ const runner = vi.fn<SubagentRunnerFn>(() => {
+ callIdx++;
+ if (callIdx === 1) return new Promise((r) => { done1 = r; });
+ if (callIdx === 2) return new Promise((r) => { done2 = r; });
+ return new Promise(() => {});
+ });
+
+ const j1 = await startSubagentJob({ ...base, principal: "p-a" }, runner);
+ done1(ok("1"));
+ await new Promise((r) => setTimeout(r, 10));
+ const j2 = await startSubagentJob({ ...base, principal: "p-a" }, runner);
+ done2(ok("2"));
+ await new Promise((r) => setTimeout(r, 10));
+
+ const runningIds: string[] = [];
+ for (let i = 2; i < MAX_RETAINED_JOBS; i++) {
+ const j = await startSubagentJob({ ...base, principal: `p-${i}` }, runner);
+ runningIds.push(j.jobId);
+ }
+ await startSubagentJob({ ...base, principal: "p-new" }, runner);
+ expect(() => getSubagentJob(j1.jobId, "p-a")).toThrow("subagent job not found");
+ expect(getSubagentJob(j2.jobId, "p-a").status).toBe("completed");
+ expect(getSubagentJob(runningIds[0], "p-2").status).toBe("running");
+ });
+});
diff --git a/lib/agent/subagent-jobs.ts b/lib/agent/subagent-jobs.ts
new file mode 100644
index 00000000..8fb2ca3b
--- /dev/null
+++ b/lib/agent/subagent-jobs.ts
@@ -0,0 +1,172 @@
+import { randomUUID } from "node:crypto";
+import { runSessionSubagent } from "./subagent-runner";
+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+import type { CapabilityRunContext } from "@/lib/capabilities/tool";
+
+export const MAX_CONCURRENT_PER_PRINCIPAL = 4;
+export const MAX_RETAINED_JOBS = 32;
+export const RETENTION_MS = 30 * 60_000;
+
+export type SubagentJobStatus = "running" | "completed" | "failed" | "cancelled" | "expired";
+
+export type SubagentJob = {
+ jobId: string;
+ principal: string;
+ name: string;
+ status: SubagentJobStatus;
+ startedAt: string;
+ finishedAt?: string;
+ result?: string;
+ error?: string;
+ controller?: AbortController;
+};
+
+export type SubagentOutcome = {
+ subagentId: string;
+ name: string;
+ status: "completed" | "partial" | "timeout";
+ text: string;
+ rounds: number;
+ toolCalls: Array<{ name: string; ok: boolean }>;
+ maxScope: "read" | "write" | "exec";
+};
+
+export type SubagentRunnerFn = (input: {
+ principal: string;
+ parentSessionId: string;
+ objective: string;
+ name?: string;
+ maxScope?: string;
+ maxTurns?: number;
+ timeoutMs?: number;
+ explicitContext?: string;
+ capabilities: CapabilityRuntime;
+ authority: CapabilityRunContext;
+}) => Promise<SubagentOutcome>;
+
+const jobs = new Map<string, SubagentJob>();
+
+function cleanup(now = Date.now()) {
+ for (const job of jobs.values()) {
+ if (job.status !== "running" && job.finishedAt && (now - Date.parse(job.finishedAt) > RETENTION_MS)) {
+ job.status = "expired";
+ job.result = undefined;
+ }
+ }
+}
+
+function evictIfFull() {
+ if (jobs.size < MAX_RETAINED_JOBS) return;
+ let oldestFinished: SubagentJob | undefined;
+ for (const job of jobs.values()) {
+ if (job.status !== "running" && job.finishedAt) {
+ if (!oldestFinished || Date.parse(job.finishedAt) < Date.parse(oldestFinished.finishedAt!)) {
+ oldestFinished = job;
+ }
+ }
+ }
+ if (oldestFinished) jobs.delete(oldestFinished.jobId);
+}
+
+function ownedJob(jobId: string, principal: string): SubagentJob {
+ cleanup();
+ const job = jobs.get(jobId);
+ if (!job || job.principal !== principal) throw new Error("subagent job not found");
+ return job;
+}
+
+export function publicJob(job: SubagentJob, now = Date.now()) {
+ const isFinished = job.status !== "running" && Boolean(job.finishedAt);
+ const endMs = isFinished ? Date.parse(job.finishedAt!) : now;
+ const elapsedMs = Math.max(0, endMs - Date.parse(job.startedAt));
+ return {
+ jobId: job.jobId,
+ status: job.status,
+ name: job.name,
+ startedAt: job.startedAt,
+ ...(job.finishedAt ? { finishedAt: job.finishedAt } : {}),
+ ...(job.status === "completed" && job.result !== undefined ? { result: job.result } : {}),
+ ...(job.status === "failed" && job.error !== undefined ? { error: job.error } : {}),
+ elapsedMs,
+ };
+}
+
+export async function startSubagentJob(
+ input: {
+ principal: string;
+ parentSessionId: string;
+ objective: string;
+ name?: string;
+ maxScope?: string;
+ maxTurns?: number;
+ timeoutMs?: number;
+ explicitContext?: string;
+ capabilities: CapabilityRuntime;
+ authority: CapabilityRunContext;
+ },
+ runner: SubagentRunnerFn = runSessionSubagent,
+) {
+ cleanup();
+ const active = [...jobs.values()].filter((j) => j.principal === input.principal && j.status === "running").length;
+ if (active >= MAX_CONCURRENT_PER_PRINCIPAL) {
+ throw new Error(`Too many active subagent jobs (max ${MAX_CONCURRENT_PER_PRINCIPAL})`);
+ }
+ evictIfFull();
+ const jobId = `subagent_job_${randomUUID()}`;
+ const name = String(input.name || "worker").trim().replace(/[\r\n\t]+/g, " ").slice(0, 60) || "worker";
+ const startedAt = new Date().toISOString();
+ const controller = new AbortController();
+ const job: SubagentJob = { jobId, principal: input.principal, name, status: "running", startedAt, controller };
+ jobs.set(jobId, job);
+
+ const signal = input.authority.signal
+ ? AbortSignal.any([controller.signal, input.authority.signal])
+ : controller.signal;
+ const runAuthority: CapabilityRunContext = { ...input.authority, signal };
+
+ (async () => {
+ try {
+ const outcome = await runner({ ...input, authority: runAuthority });
+ if (controller.signal.aborted) {
+ job.status = "cancelled";
+ } else if (outcome.status === "completed" || outcome.status === "partial") {
+ job.status = "completed";
+ job.result = outcome.text;
+ } else {
+ job.status = "failed";
+ job.error = outcome.status === "timeout" ? "subagent timeout" : outcome.text;
+ }
+ } catch (err) {
+ if (controller.signal.aborted) {
+ job.status = "cancelled";
+ } else {
+ job.status = "failed";
+ job.error = err instanceof Error ? err.message : String(err);
+ }
+ } finally {
+ job.finishedAt = new Date().toISOString();
+ job.controller = undefined;
+ }
+ })();
+
+ return { jobId: job.jobId, name: job.name, startedAt: job.startedAt, status: "running" as const };
+}
+
+export function getSubagentJob(jobId: string, principal: string) {
+ return publicJob(ownedJob(jobId, principal));
+}
+
+export function cancelSubagentJob(jobId: string, principal: string) {
+ const job = ownedJob(jobId, principal);
+ if (job.status === "running" && job.controller) {
+ job.status = "cancelled";
+ job.finishedAt = new Date().toISOString();
+ job.controller.abort(new Error("subagent job cancelled by caller"));
+ job.controller = undefined;
+ }
+ return publicJob(job);
+}
+
+export function _resetSubagentJobsForTest() {
+ jobs.clear();
+}
diff --git a/lib/mcp/client-budgets.test.ts b/lib/mcp/client-budgets.test.ts
index 31f57a79..032da094 100644
--- a/lib/mcp/client-budgets.test.ts
+++ b/lib/mcp/client-budgets.test.ts
@@ -14,7 +14,9 @@ it("checks published metadata limits separately from MSO's byte policy without i
}
}
const descriptors = TOOLS.map(tool => toolDescriptor(tool, "chatgpt"));
- // Internal project budgets, NOT an OpenAI/MCP token guarantee.
- expect(Buffer.byteLength(JSON.stringify(descriptors))).toBeLessThan(96 * 1024);
+ // Internal project budgets, NOT an OpenAI/MCP token guarantee. Kept equal to the
+ // companion ceiling in chatgpt-profile.test.ts: two tests measuring the same payload
+ // with different numbers is how one of them silently becomes the real limit.
+ expect(Buffer.byteLength(JSON.stringify(descriptors))).toBeLessThan(100 * 1024);
expect(Math.max(...descriptors.map(d => Buffer.byteLength(JSON.stringify(d))))).toBeLessThan(8 * 1024);
});
diff --git a/lib/mcp/mcp-only-reasons.ts b/lib/mcp/mcp-only-reasons.ts
index 4398b6ee..f39b5847 100644
--- a/lib/mcp/mcp-only-reasons.ts
+++ b/lib/mcp/mcp-only-reasons.ts
@@ -79,6 +79,9 @@ export const MCP_ONLY: Record<string, string> = {
"a2a.task.cancel": "A2A remote task cancellation stays approval-gated in the external agent harness",
"a2a.handoff": "explicit agent-to-agent delegation is intentionally MCP/terminal-only until Alfa receives its own scoped orchestration model",
"agent.subagent.run": "same-session isolated subagent orchestration belongs to the terminal/MCP agent runtime; Alfa browser threads do not yet share durable AgentSession identity or its approval boundary",
+ "agent.subagent.start": "same-session asynchronous subagent orchestration belongs to the terminal/MCP agent runtime; Alfa browser threads do not yet share durable AgentSession identity or its approval boundary",
+ "agent.subagent.status": "status exists to poll an asynchronous subagent run owned by the authenticated MCP client; Alfa has no matching subagent lifecycle",
+ "agent.subagent.cancel": "cancellation of an asynchronous subagent run remains bound to the authenticated MCP client and AgentSession",
"local.agent.reply": "correlated replies belong to the durable Local Agents session mailbox; Alfa browser threads do not share that session identity or inbox",
"local.agent.request.wait": "bounded request observation is tied to the durable Local Agents mailbox/correlation ledger; Alfa browser threads do not own that AgentSession sender identity",
"local.agent.request": "fresh-worker execution from another durable AgentSession context belongs to the terminal/MCP orchestration runtime; Alfa browser threads neither share that isolated session store nor its exec delegation boundary",
diff --git a/lib/mcp/tools-subagents.ts b/lib/mcp/tools-subagents.ts
index 9c4aa13d..f18a5125 100644
--- a/lib/mcp/tools-subagents.ts
+++ b/lib/mcp/tools-subagents.ts
@@ -1,37 +1,92 @@
import { runSessionSubagent } from "@/lib/agent/subagent-runner";
+import {
+ startSubagentJob,
+ getSubagentJob,
+ cancelSubagentJob,
+} from "@/lib/agent/subagent-jobs";
import { allows, parseScope } from "./scope";
import { type McpTool, S, str } from "./tool-kit";
-export const SUBAGENT_TOOLS: McpTool[] = [{
- name: "agent_subagent_run",
- description: "Spawn one foreground focused subagent inside the current durable MSO Agent session. The worker gets an isolated context window and only the explicit objective/context supplied here; intermediate tool calls stay out of the parent conversation and only the final result returns. It does not create a Local Agent peer, does not run after this call returns, cannot recursively spawn subagents, and cannot use session/memory/local-agent/A2A tools. Use subagents for independent research/review/workstreams where isolation helps; do simple sequential work directly.",
- scope: "exec",
- limit: { key: "agent.subagent", max: 12, windowMs: 60_000 },
- audit: { action: "agent.subagent", targetArg: "name" },
- inputSchema: S({
- objective: { type: "string", description: "Exact focused task for the worker, maximum 24 KiB." },
- name: { type: "string", description: "Optional short display name, e.g. reviewer or researcher." },
- max_scope: { type: "string", enum: ["read", "write", "exec"], description: "Maximum host-tool authority delegated to the child. Default read. The parent call itself is exec-gated as the delegation approval boundary." },
- max_turns: { type: "number", description: "1 to the server-configured OS_SUBAGENT_MAX_TURNS limit (default 12, absolute max 48); default 6." },
- timeout_ms: { type: "number", description: "1000-120000 ms; default 60000." },
- context: { type: "string", description: "Optional explicit parent context. Hidden parent transcript is never copied automatically." },
- }, ["objective"]),
- run: async (a, context) => {
- if (!context.principal || !context.sessionId) throw new Error("subagent requires a conversation-bound MSO session");
- const requested = parseScope(typeof a.max_scope === "string" ? a.max_scope : "read");
- if (!allows(context.scope, requested)) throw new Error(`subagent max_scope ${requested} exceeds caller scope ${context.scope}`);
- if (!context.capabilities) throw new Error("capability runtime unavailable for subagent delegation");
- return runSessionSubagent({
- principal: context.principal,
- parentSessionId: context.sessionId,
- objective: str(a, "objective"),
- name: typeof a.name === "string" ? a.name : undefined,
- maxScope: requested,
- maxTurns: Number(a.max_turns) || undefined,
- timeoutMs: Number(a.timeout_ms) || undefined,
- explicitContext: typeof a.context === "string" ? a.context : undefined,
- capabilities: context.capabilities,
- authority: context,
- });
+function validateSubagentDelegation(a: Record<string, unknown>, context: Parameters<McpTool["run"]>[1]) {
+ if (!context.principal || !context.sessionId) throw new Error("subagent requires a conversation-bound MSO session");
+ const requested = parseScope(typeof a.max_scope === "string" ? a.max_scope : "read");
+ if (!allows(context.scope, requested)) throw new Error(`subagent max_scope ${requested} exceeds caller scope ${context.scope}`);
+ if (!context.capabilities) throw new Error("capability runtime unavailable for subagent delegation");
+ return {
+ principal: context.principal,
+ parentSessionId: context.sessionId,
+ objective: str(a, "objective"),
+ name: typeof a.name === "string" ? a.name : undefined,
+ maxScope: requested,
+ maxTurns: Number(a.max_turns) || undefined,
+ timeoutMs: Number(a.timeout_ms) || undefined,
+ explicitContext: typeof a.context === "string" ? a.context : undefined,
+ capabilities: context.capabilities,
+ authority: context,
+ };
+}
+
+const SUBAGENT_INPUT_PROPERTIES = {
+ objective: { type: "string", description: "Exact focused task for the worker, maximum 24 KiB." },
+ name: { type: "string", description: "Optional short display name, e.g. reviewer or researcher." },
+ max_scope: { type: "string", enum: ["read", "write", "exec"], description: "Maximum host-tool authority delegated to the child. Default read. The parent call itself is exec-gated as the delegation approval boundary." },
+ max_turns: { type: "number", description: "1 to the server-configured OS_SUBAGENT_MAX_TURNS limit (default 12, absolute max 48); default 6." },
+ timeout_ms: { type: "number", description: "1000-120000 ms; default 60000." },
+ context: { type: "string", description: "Optional explicit parent context. Hidden parent transcript is never copied automatically." },
+};
+
+export const SUBAGENT_TOOLS: McpTool[] = [
+ {
+ name: "agent_subagent_run",
+ description: "Spawn one foreground focused subagent inside the current durable MSO Agent session. The worker gets an isolated context window and only the explicit objective/context supplied here; intermediate tool calls stay out of the parent conversation and only the final result returns. It does not create a Local Agent peer, does not run after this call returns, cannot recursively spawn subagents, and cannot use session/memory/local-agent/A2A tools. Use subagents for independent research/review/workstreams where isolation helps; do simple sequential work directly.",
+ chatgptDescription: "Spawn isolated worker.",
+ scope: "exec",
+ limit: { key: "agent.subagent", max: 12, windowMs: 60_000 },
+ audit: { action: "agent.subagent", targetArg: "name" },
+ inputSchema: S(SUBAGENT_INPUT_PROPERTIES, ["objective"]),
+ run: async (a, context) => {
+ const input = validateSubagentDelegation(a, context);
+ return runSessionSubagent(input);
+ },
+ },
+ {
+ name: "agent_subagent_start",
+ description: "Start one background focused subagent inside the current durable MSO Agent session and return immediately with a job ID. The worker gets an isolated context window with the same scope, turn, and tool restrictions as foreground subagents. It cannot recursively spawn subagents and cannot use session/memory/local-agent/A2A tools. Bounded to 4 concurrent jobs per principal and retained in-memory for 30 minutes after completion; process restart discards jobs. Read status with agent_subagent_status.",
+ chatgptDescription: "Start background worker.",
+ scope: "exec",
+ limit: { key: "agent.subagent", max: 12, windowMs: 60_000 },
+ audit: { action: "agent.subagent", targetArg: "name" },
+ inputSchema: S(SUBAGENT_INPUT_PROPERTIES, ["objective"]),
+ run: async (a, context) => {
+ const input = validateSubagentDelegation(a, context);
+ return startSubagentJob(input);
+ },
+ },
+ {
+ name: "agent_subagent_status",
+ description: "Read status of one background subagent job owned by this client. Completed results are retained in-memory for 30 minutes after completion, after which status transitions to expired and result is discarded. Jobs disappear if the process restarts.",
+ chatgptDescription: "Check background worker.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ limit: { key: "exec.job.status", max: 120, windowMs: 60_000 },
+ inputSchema: S({ job_id: { type: "string", description: "Exact job id returned by agent_subagent_start." } }, ["job_id"]),
+ run: (a, context) => {
+ if (!context.principal) throw new Error("subagent requires an authenticated MSO client");
+ return Promise.resolve(getSubagentJob(str(a, "job_id"), context.principal));
+ },
+ },
+ {
+ name: "agent_subagent_cancel",
+ description: "Cancel one still-running background subagent job owned by this client. Aborts the worker via AbortSignal. Repeated cancellation is idempotent.",
+ chatgptDescription: "Cancel background worker.",
+ scope: "exec",
+ annotations: { destructiveHint: true, idempotentHint: true },
+ limit: { key: "exec.job.cancel", max: 30, windowMs: 60_000 },
+ audit: { action: "agent.subagent", targetArg: "job_id" },
+ inputSchema: S({ job_id: { type: "string", description: "Exact job id returned by agent_subagent_start." } }, ["job_id"]),
+ run: (a, context) => {
+ if (!context.principal) throw new Error("subagent requires an authenticated MSO client");
+ return Promise.resolve(cancelSubagentJob(str(a, "job_id"), context.principal));
+ },
},
-}];
+];