Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Run subagents in any coding agent you have installed, from any MCP client. You pick the harness and model, it handles the rest.

It is an MCP server. A coding agent calls it with a harness, a model and effort, a prompt, and a working directory; Subturn starts a session in that harness with the logins you already have, hands back the harness's own session id, and the caller collects the answer later. Codex, Claude Code, Grok, and OpenCode are supported today. The npm package, the MCP server name, and the CLI binary are all called `subturn`. Why it is shaped this way is in [AGENTS.md](AGENTS.md).
It is an MCP server. A coding agent calls it with a harness, a model and effort, a prompt, and a working directory; Subturn starts a session in that harness with the logins you already have, hands back the harness's own session id, and the caller collects the answer later. Codex, Claude Code, Grok, OpenCode, and Antigravity are supported today. The npm package, the MCP server name, and the CLI binary are all called `subturn`. Why it is shaped this way is in [AGENTS.md](AGENTS.md).

## Install and wire up

Expand Down Expand Up @@ -37,7 +37,7 @@ Here is a whole file, as an example. Give it the same scope as the server: your
```markdown
Delegate through the `subturn` MCP server. Never call the harness CLIs from Bash.

Spawn with a harness (`claude`, `codex`, `grok`, `opencode`), a full model id and a reasoning effort (both passed verbatim), a prompt, and an absolute cwd. After the few seconds the harness needs to come up you get its own session id back while the subagent runs on; if anything fails before the session exists, the spawn itself errors with the full detail inline. `await` the id for the outcome, waiting up to `timeout` seconds (default and max 300, `0` for a snapshot; the turn keeps running if the wait runs out): final text, usage, and the model and effort the harness acknowledged on success, bare `failed` or `cancelled` otherwise. `resume` the id with a new prompt to continue the conversation once its turn is no longer running; harness, model, effort, and cwd carry over, the id stays the same, and the conversation stays resumable for 7 days after its last turn. `cancel` kills a running turn and keeps the session. Every "why" is in `inspect`, which returns the raw evidence and works mid-run. Turns die at their deadline (default 3600 s), so fire-and-forget is safe; fan-out is just several spawns. Give the subagent a disposable cwd or worktree when cleanliness matters and diff it afterwards.
Spawn with a harness (`claude`, `codex`, `grok`, `opencode`, `antigravity`), a full model id and a reasoning effort (both passed verbatim), a prompt, and an absolute cwd. After the few seconds the harness needs to come up you get its own session id back while the subagent runs on; if anything fails before the session exists, the spawn itself errors with the full detail inline. `await` the id for the outcome, waiting up to `timeout` seconds (default and max 300, `0` for a snapshot; the turn keeps running if the wait runs out): final text, usage, and the model and effort the harness acknowledged on success, bare `failed` or `cancelled` otherwise. `resume` the id with a new prompt to continue the conversation once its turn is no longer running; harness, model, effort, and cwd carry over, the id stays the same, and the conversation stays resumable for 7 days after its last turn. `cancel` kills a running turn and keeps the session. Every "why" is in `inspect`, which returns the raw evidence and works mid-run. Turns die at their deadline (default 3600 s), so fire-and-forget is safe; fan-out is just several spawns. Give the subagent a disposable cwd or worktree when cleanliness matters and diff it afterwards.

- The prompt is all the subagent sees. Put everything it needs in it.
- Subagents cannot delegate further. Cross-checks and reviews are separate spawns from here.
Expand Down Expand Up @@ -67,7 +67,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio

## How it works

**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's auth file, the `credential` table in OpenCode's database). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence.
**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's auth file, the `credential` table in OpenCode's database, Antigravity's OAuth token / keychain / `GEMINI_API_KEY`). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence.

**Sessions** live under `~/.local/state/subturn/sessions/<session-id>/` (`SUBTURN_STATE_DIR` overrides). The directory holds the record, the prompt, the spawn command, the event stream as it happens, stderr, the acknowledged bundle where the harness echoes one, and the final text, so `inspect` works on a running session. Retention is 7 days after the last turn (`SUBTURN_RETENTION_DAYS`), swept on each spawn or on demand by `prune`; the resume window is the retention window, because the harness state needed for resume lives in the same directory. The deadline default is 3600 s (`SUBTURN_DEADLINE_S`), the maximum six hours.

Expand All @@ -77,12 +77,13 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio

**Plugins** (`src/plugins`) answer a small interface per harness: detection hints, auth, advertised models, shadow home, launch, and post-turn hygiene. Adding a harness is one entry in the registry; plugin modules load on first use.

| harness | transport | bundle | resume | session hygiene |
|----------|-----------|--------|--------|-----------------|
| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; the user's credentials snapshotted into a private `opencode.db` with the session tables emptied |
| grok | native ACP (`grok agent … stdio`) | `-m` / `--reasoning-effort` every turn; ack read from `session/new` | ACP `session/load` | shadow home via `GROK_HOME`; `auth.json` symlinked back |
| codex | headless `codex exec --json` | `-m` / `-c model_reasoning_effort=` every turn | `codex exec resume <id>` in the session's `CODEX_HOME` shadow | shadow home via `CODEX_HOME`; `auth.json` symlinked back; the user's `config.toml` deliberately not shared |
| claude | headless `claude -p --output-format stream-json` | `--model` / `--effort` every turn | `claude -p --resume <id>` after restoring parked files | default config dir, because keychain auth is bound to it; session files parked out of `~/.claude/projects` the moment a turn ends |
| harness | transport | bundle | resume | session hygiene |
|-------------|-----------|--------|--------|-----------------|
| antigravity | native ACP (`agy acp`) | `session/set_config_option` `model` then `thought_level`, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow home via `--gemini-dir` + `GEMINI_HOME`; file OAuth token copied privately (`0600`) when present, desktop keyring shared automatically; `--include-default-customizations=false` |
| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; the user's credentials snapshotted into a private `opencode.db` with the session tables emptied |
| grok | native ACP (`grok agent … stdio`) | `-m` / `--reasoning-effort` every turn; ack read from `session/new` | ACP `session/load` | shadow home via `GROK_HOME`; `auth.json` symlinked back |
| codex | headless `codex exec --json` | `-m` / `-c model_reasoning_effort=` every turn | `codex exec resume <id>` in the session's `CODEX_HOME` shadow | shadow home via `CODEX_HOME`; `auth.json` symlinked back; the user's `config.toml` deliberately not shared |
| claude | headless `claude -p --output-format stream-json` | `--model` / `--effort` every turn | `claude -p --resume <id>` after restoring parked files | default config dir, because keychain auth is bound to it; session files parked out of `~/.claude/projects` the moment a turn ends |

Every plugin launches its harness in a validated permissive posture (`--dangerously-bypass-approvals-and-sandbox`, `--dangerously-skip-permissions`, `--always-approve`, or Subturn's own allow-everything ACP permission handler). Concurrent sessions of one harness do not collide: shadow state is per session.

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"claude-code",
"grok",
"opencode",
"antigravity",
"acp"
],
"type": "module",
Expand Down
21 changes: 15 additions & 6 deletions src/core/acp-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ const SESSION_LOAD_TIMEOUT_MS = 120_000; // replay of a long history takes time

export interface AcpTurnPlan {
argv: string[];
/** Optional ACP `authenticate` methodId sent right after `initialize`
* (e.g. antigravity's `gemini-api-key` when authenticating via env var). */
authMethodId?: string;
/** Applied after session/new or session/load; returns the
* acknowledged-bundle record for ack.json, or null when the harness
* echoes nothing. Throw to fail. Runs on resumed turns too — this is
Expand Down Expand Up @@ -160,6 +163,11 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
throw new Error(`initialize: unexpected protocolVersion in ${JSON.stringify(initResult)}`);
}

if (plan.authMethodId !== undefined) {
const authResult = await client.request("authenticate", { methodId: plan.authMethodId }, INITIALIZE_TIMEOUT_MS);
ctx.emit({ type: "authenticate_result", methodId: plan.authMethodId, result: authResult ?? null });
}

let sessionNewResult: Record<string, unknown> | null = null;
if (ctx.nativeSessionId !== undefined) {
// Non-forking resume: same session id, conversation continues.
Expand Down Expand Up @@ -247,8 +255,8 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise

const stopReason = isRecord(promptResult) ? promptResult["stopReason"] : undefined;
const finalText = finalChunks.join("");
if (stopReason === "cancelled") {
return { ok: false, error: `prompt stopReason=cancelled\nstderr tail:\n${spawned.stderrTail()}` };
if (stopReason === "cancelled" || stopReason === "refusal") {
return { ok: false, error: `prompt stopReason=${stopReason}\nstderr tail:\n${spawned.stderrTail()}` };
}
const outcome: LaunchOutcome = { ok: true, finalText };
const usage = extractUsage(usageCandidates);
Expand All @@ -266,11 +274,12 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
client.close();
// Graceful: give the harness a moment to exit on stdin close, then kill
// the group (adapter children can outlive the leader).
const exited = await Promise.race([
spawned.waitExit().then(() => true),
new Promise<false>((r) => setTimeout(r, 3000, false)),
const exit = await Promise.race([
spawned.waitExit(),
new Promise<null>((r) => setTimeout(r, 3000, null)),
]);
if (!exited) ctx.emit({ type: "close_forced_kill", pid: spawned.pid });
if (exit === null) ctx.emit({ type: "close_forced_kill", pid: spawned.pid });
else ctx.emit({ type: "exit", code: exit.code, signal: exit.signal });
spawned.killGroup();
}
}
19 changes: 11 additions & 8 deletions src/faces/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,30 +122,33 @@ async function cmdStatus(): Promise<void> {
// Human-only. Probes: version/auth/handshake — never a prompt.
const { loadPlugins } = await import("../plugins/index.ts");
const { resolvePin } = await import("../core/discovery.ts");
const plugins = await loadPlugins();
const col = Math.max(9, ...[...plugins.keys()].map((n) => n.length));
const pad = " ".repeat(col + 1);
const rows: string[] = [];
for (const [name, plugin] of await loadPlugins()) {
for (const [name, plugin] of plugins) {
const pin = await resolvePin(name, plugin.hints);
if (pin === null) {
rows.push(`${name.padEnd(9)} not installed`);
rows.push(`${name.padEnd(col)} not installed`);
continue;
}
const auth = await plugin.auth();
let modelsLine = "";
if (auth.ok) {
const models = await plugin.models(pin.binPath);
modelsLine = models !== null
? `\n${" ".repeat(10)}models: ${models.join(", ")}`
: `\n${" ".repeat(10)}models: (no cheap advertisement for this harness)`;
? `\n${pad}models: ${models.join(", ")}`
: `\n${pad}models: (no cheap advertisement for this harness)`;
}
const others = pin.candidates.filter((c) => c.binPath !== pin.binPath);
const othersLine = others.length > 0
? `${" ".repeat(10)}also installed, older: ${others.map((c) => `${c.binPath} (${c.version})`).join(", ")}\n`
? `${pad}also installed, older: ${others.map((c) => `${c.binPath} (${c.version})`).join(", ")}\n`
: "";
rows.push(
`${name.padEnd(9)} ${pin.version}\n` +
`${" ".repeat(10)}binary: ${pin.binPath}\n` +
`${name.padEnd(col)} ${pin.version}\n` +
`${pad}binary: ${pin.binPath}\n` +
othersLine +
`${" ".repeat(10)}auth: ${auth.ok ? "ok" : "NOT AUTHORIZED"} — ${auth.detail}` +
`${pad}auth: ${auth.ok ? "ok" : "NOT AUTHORIZED"} — ${auth.detail}` +
modelsLine,
);
}
Expand Down
75 changes: 51 additions & 24 deletions src/plugins/acp-models-probe.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// plugins/acp-models-probe.ts — throwaway ACP handshake for CLI `status`:
// spawn the agent, initialize + session/new in a temp cwd, read the
// advertised models, kill. Never sends a prompt; costs no quota. Models are
// read from either shape a harness advertises them in: grok's
// `models.availableModels[].modelId`, or opencode's `configOptions[]` entry
// with id "model" (`options[].value`).
// read preferentially from `configOptions[]` entry with id "model"
// (`options[].value`, used by opencode and antigravity where
// `models.availableModels` may carry legacy effort-suffixed ids), falling
// back to `models.availableModels[].modelId` (grok).

import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
Expand All @@ -13,9 +14,50 @@ import { AcpClient } from "../core/acp.ts";
import { spawnHarness } from "../core/child.ts";
import { isRecord } from "../core/json.ts";

/** Extract deduplicated model ids from a `session/new` response, preferring
* `configOptions[id="model"]` when it yields at least one id and falling back
* to `models.availableModels[].modelId`. */
export function extractAcpModels(res: unknown): string[] | null {
if (!isRecord(res)) return null;
const fromConfig: string[] = [];
const configOptions = res["configOptions"];
if (Array.isArray(configOptions)) {
for (const o of configOptions) {
if (!isRecord(o) || o["id"] !== "model" || !Array.isArray(o["options"])) continue;
for (const entry of o["options"]) {
if (!isRecord(entry)) continue;
if (typeof entry["value"] === "string" && entry["value"] !== "") {
fromConfig.push(entry["value"]);
} else if (Array.isArray(entry["options"])) {
// Grouped select option (ACP v1): flatten nested options.
for (const nested of entry["options"]) {
if (isRecord(nested) && typeof nested["value"] === "string" && nested["value"] !== "") {
fromConfig.push(nested["value"]);
}
}
}
}
}
}
if (fromConfig.length > 0) return [...new Set(fromConfig)];

const fromAvailable: string[] = [];
const models = isRecord(res["models"]) ? res["models"] : null;
const available = models?.["availableModels"];
if (Array.isArray(available)) {
for (const m of available) {
if (isRecord(m) && typeof m["modelId"] === "string" && m["modelId"] !== "") {
fromAvailable.push(m["modelId"]);
}
}
}
return fromAvailable.length > 0 ? [...new Set(fromAvailable)] : null;
}

export async function probeAcpModels(
argv: string[],
env: Record<string, string>,
opts?: { authMethodId?: string },
): Promise<string[] | null> {
const cwd = mkdtempSync(path.join(tmpdir(), "subturn-probe-"));
const stderrFile = path.join(cwd, "stderr.log");
Expand All @@ -31,31 +73,16 @@ export async function probeAcpModels(
onSessionUpdate: () => { /* none expected before a prompt */ },
});
try {
await client.request("initialize", {
const init = await client.request("initialize", {
protocolVersion: 1,
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
}, 20_000);
const res = await client.request("session/new", { cwd, mcpServers: [] }, 30_000);
if (!isRecord(res)) return null;
const ids: string[] = [];
const models = isRecord(res["models"]) ? res["models"] : null;
const available = models?.["availableModels"];
if (Array.isArray(available)) {
for (const m of available) {
if (isRecord(m) && typeof m["modelId"] === "string") ids.push(m["modelId"]);
}
if (!isRecord(init) || init["protocolVersion"] !== 1) return null;
if (opts?.authMethodId !== undefined) {
await client.request("authenticate", { methodId: opts.authMethodId }, 20_000);
}
const configOptions = res["configOptions"];
if (Array.isArray(configOptions)) {
for (const o of configOptions) {
if (!isRecord(o) || o["id"] !== "model" || !Array.isArray(o["options"])) continue;
for (const v of o["options"]) {
if (isRecord(v) && typeof v["value"] === "string") ids.push(v["value"]);
}
}
}
// grok advertises the same ids in both shapes.
return ids.length > 0 ? [...new Set(ids)] : null;
const res = await client.request("session/new", { cwd, mcpServers: [] }, 30_000);
return extractAcpModels(res);
} catch {
return null;
} finally {
Expand Down
Loading
Loading