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
2 changes: 1 addition & 1 deletion CLAUDE.local.template.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Spawn with a harness (`codex`, `claude`, `grok`, `opencode`), a full model id an

## Routing

`sol` = codex `gpt-5.6-sol`, `luna` = codex `gpt-5.6-luna`, `glm` = opencode `zai-coding-plan/glm-5.3`. `/` = any of these, `+` = both, findings merged. For `fable`, `opus`, `sonnet` and `haiku` don't use MCP, use native subagents instead
`sol` = codex `gpt-6.1-sol`, `luna` = codex `gpt-6-luna`, `glm` = opencode `zai-coding-plan/glm-5.3`. `/` = any of these, `+` = both, findings merged. For `fable`, `opus`, `sonnet` and `haiku` don't use MCP, use native subagents instead

| Task | Default | When the default falls short |
|---|---|---|
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ npm install -g subturn
claude mcp add subturn -- subturn serve
```

Requires Node 22 or newer. Until the package is published, `npx github:eshatalov/subturn` works the same way. From a checkout, `npm install` builds `dist/` and the server is `node dist/faces/mcp.js`.
Requires Node 22.13 or newer, and OpenCode 2 or newer for that harness. Until the package is published, `npx github:eshatalov/subturn` works the same way. From a checkout, `npm install` builds `dist/` and the server is `node dist/faces/mcp.js`.

## The caller's whole manual

Expand Down Expand Up @@ -54,7 +54,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 and OpenCode's auth files). 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). 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 @@ -66,7 +66,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio

| 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`; `auth.json` symlinked back |
| 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 |
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
],
"type": "module",
"engines": {
"node": ">=22"
"node": ">=22.13"
},
"bin": {
"subturn": "dist/faces/cli.js"
Expand Down
46 changes: 42 additions & 4 deletions src/core/acp-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,25 @@ import path from "node:path";
const INITIALIZE_TIMEOUT_MS = 30_000;
const SESSION_NEW_TIMEOUT_MS = 60_000;
const SESSION_LOAD_TIMEOUT_MS = 120_000; // replay of a long history takes time
const CONFIG_SETTLE_MS = 5_000;

/** Runs `attempt`; when the harness refuses it with -32602, runs it again
* after each config_option_update, giving up CONFIG_SETTLE_MS after the
* first try. For a harness that opens a session before its option list has
* loaded and announces the rest. */
export type RetryOnConfigUpdate = (attempt: () => Promise<unknown>) => Promise<unknown>;

export interface AcpTurnPlan {
argv: 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
* where model+effort are re-applied explicitly. */
configure?: (client: AcpClient, sessionId: string) => Promise<Record<string, unknown> | null>;
configure?: (
client: AcpClient,
sessionId: string,
retryOnConfigUpdate: RetryOnConfigUpdate,
) => Promise<Record<string, unknown> | null>;
/** Extract the acknowledged bundle from the session/new response (grok:
* models.currentModelId + reasoningEffort meta). */
ackFromSessionNew?: (result: Record<string, unknown>) => Record<string, unknown> | null;
Expand Down Expand Up @@ -74,8 +85,8 @@ function extractUsage(candidates: unknown[]): Usage | undefined {
const out = c["output_tokens"] ?? c["outputTokens"];
const total = c["total_tokens"] ?? c["totalTokens"];
const cacheRead = c["cache_read_input_tokens"] ?? c["cachedReadTokens"] ?? c["cache_read_tokens"];
const cacheCreate = c["cache_creation_input_tokens"] ?? c["cacheCreationTokens"];
const reasoning = c["reasoning_tokens"] ?? c["reasoningTokens"];
const cacheCreate = c["cache_creation_input_tokens"] ?? c["cacheCreationTokens"] ?? c["cachedWriteTokens"];
const reasoning = c["reasoning_tokens"] ?? c["reasoningTokens"] ?? c["thoughtTokens"];
const cost = c["cost_usd"] ?? c["costUsd"] ?? c["total_cost_usd"];
if (typeof inp === "number") usage.input_tokens = inp;
if (typeof out === "number") usage.output_tokens = out;
Expand All @@ -102,6 +113,8 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
const usageCandidates: unknown[] = [];
let activeSessionId = "";
let collecting = false; // off until the prompt goes out (replay isn't ours)
let configUpdates = 0;
let onConfigUpdate: (() => void) | null = null;

const client = new AcpClient(spawned.child, {
emit: (e) => ctx.emit(e),
Expand All @@ -111,6 +124,10 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
return;
}
ctx.emit({ type: collecting ? "session_update" : "session_update_replay", update });
if (update["sessionUpdate"] === "config_option_update") {
configUpdates++;
onConfigUpdate?.();
}
if (!collecting) return;
if (update["sessionUpdate"] === "agent_message_chunk") {
const content = update["content"];
Expand Down Expand Up @@ -147,6 +164,27 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
client.onExtNotification(method, (params) => handler(params, sink));
}

const nextConfigUpdate = (timeoutMs: number): Promise<boolean> =>
new Promise((resolve) => {
const timer = setTimeout(() => { onConfigUpdate = null; resolve(false); }, timeoutMs);
onConfigUpdate = () => { clearTimeout(timer); onConfigUpdate = null; resolve(true); };
});
const retryOnConfigUpdate: RetryOnConfigUpdate = async (attempt) => {
const deadline = Date.now() + CONFIG_SETTLE_MS;
for (;;) {
const seen = configUpdates; // an update landing mid-attempt counts
try {
return await attempt();
} catch (e) {
if (!(e instanceof RpcError) || e.code !== -32602) throw e;
const left = deadline - Date.now();
if (left <= 0) throw e;
if (configUpdates === seen && !(await nextConfigUpdate(left))) throw e;
ctx.emit({ type: "configure_retry", refused: e.message });
}
}
};

try {
const initResult = await client.request("initialize", {
protocolVersion: 1,
Expand Down Expand Up @@ -190,7 +228,7 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise
ackBase = plan.ackFromSessionNew(sessionNewResult);
}
if (plan.configure !== undefined) {
const configureAck = await plan.configure(client, activeSessionId);
const configureAck = await plan.configure(client, activeSessionId, retryOnConfigUpdate);
if (configureAck !== null) ackBase = { ...(ackBase ?? {}), ...configureAck };
}
if (currentAck() !== null) {
Expand Down
2 changes: 1 addition & 1 deletion src/faces/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const specs: VerbSpec[] = [
type: "object",
properties: {
harness: str(`One of ${harnessList()}.`),
model: str("Model id as the harness names it, e.g. gpt-5.6-sol, zai-coding-plan/glm-5.3, grok-4.6."),
model: str("Model id as the harness names it, e.g. gpt-6.1-sol, zai-coding-plan/glm-5.3, grok-4.6."),
effort: str("Reasoning effort as the harness names it, e.g. low, medium, high."),
prompt: str("What you want done."),
cwd: str("Absolute directory the subagent works in. It can write anything there."),
Expand Down
28 changes: 21 additions & 7 deletions src/plugins/acp-models-probe.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// 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.
// 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`).

import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -34,14 +37,25 @@ export async function probeAcpModels(
}, 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)) return null;
const ids = available
.filter(isRecord)
.map((m) => (typeof m["modelId"] === "string" ? m["modelId"] : null))
.filter((m): m is string => m !== null);
return ids.length > 0 ? ids : null;
if (Array.isArray(available)) {
for (const m of available) {
if (isRecord(m) && typeof m["modelId"] === "string") ids.push(m["modelId"]);
}
}
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;
} catch {
return null;
} finally {
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// Posture: `--dangerously-skip-permissions` — claude's validated bypass
// mode; no permission prompt can fire in print mode with it.
//
// Hygiene by parking, NOT a shadow home (proven by live smoke 2026-09-01):
// Hygiene by parking, NOT a shadow home:
// claude's keychain credentials are per-config-dir — the service name is
// "Claude Code-credentials-<8-hex hash of the dir>" — so any fresh
// CLAUDE_CONFIG_DIR shadow starts logged out, and the owner refuses extra
Expand Down
7 changes: 3 additions & 4 deletions src/plugins/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// validated non-interactive full-access mode; no approval prompt exists in
// exec mode with it. `--skip-git-repo-check` keeps non-repo cwds working.
// stdin carries the prompt and is closed immediately (codex hangs on an
// open stdin — recorded harness homework).
// open stdin).
//
// Shadow home: CODEX_HOME relocates the whole home; the user's real
// ~/.codex/auth.json is symlinked back in (auth.json is the one
Expand Down Expand Up @@ -128,9 +128,8 @@ export const codexPlugin: Plugin = {
// Resume: `codex exec resume <id>` continues the stored rollout in this
// session's CODEX_HOME shadow — non-forking, same conversation. Model
// and effort are re-applied explicitly (never server defaults). The
// resume subcommand takes the same flags EXCEPT --color (validated live
// 2026-09-01: `--color` is rejected there), so --color rides only on
// the fresh-exec argv.
// resume subcommand takes the same flags EXCEPT --color (it rejects it),
// so --color rides only on the fresh-exec argv.
const argv = ctx.nativeSessionId !== undefined
? [ctx.binPath, "exec", "resume", ...bundleFlags, ctx.nativeSessionId, "-"]
: [ctx.binPath, "exec", "--color", "never", ...bundleFlags, "-"]; // prompt from stdin
Expand Down
12 changes: 7 additions & 5 deletions src/plugins/fake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ export const fakePlugin: Plugin = {
}
return runAcpTurn(ctx, {
argv: [process.execPath, script],
configure: async (client, sessionId) => {
const modelRes = await client.request(
"session/set_config_option",
{ sessionId, configId: "model", value: ctx.model },
15_000,
configure: async (client, sessionId, retryOnConfigUpdate) => {
const modelRes = await retryOnConfigUpdate(() =>
client.request(
"session/set_config_option",
{ sessionId, configId: "model", value: ctx.model },
15_000,
),
);
const effortRes = await client.request(
"session/set_config_option",
Expand Down
13 changes: 6 additions & 7 deletions src/plugins/grok.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
// all tool executions), plus Subturn's ACP client's allow-everything
// permission handler as a backstop.
//
// Past-ACP quirk (observed live): grok can complete a
// prompt via the private `_x.ai/session/prompt_complete` notification
// without ever answering the standard session/prompt request. The turn
// races both; the promptId rides in _meta.promptId/_meta.requestId.
// Quirk: grok can complete a prompt via the private
// `_x.ai/session/prompt_complete` notification without ever answering the
// standard session/prompt request. The turn races both; the promptId rides
// in _meta.promptId/_meta.requestId.
//
// Shadow home: GROK_HOME relocates the whole home (sessions land under
// $GROK_HOME/sessions); the user's real ~/.grok/auth.json is symlinked in.
Expand Down Expand Up @@ -92,10 +92,9 @@ export const grokPlugin: Plugin = {
],
grokCompletionRace: true,
extNotifications: {
// Grok's private session channel (validated live 2026-09-02):
// Grok's private session channel:
// - `model_changed` fires when the server re-selects the model
// AFTER session/new (a launch campaign flipped grok-4.5 to
// grok-4.6 despite `-m`); the ack must follow.
// AFTER session/new, even against `-m`; the ack must follow.
// - `turn_completed` carries the turn's usage (camelCase) and
// `modelUsage` keyed by the model that actually served it.
"_x.ai/session_notification": (params, sink) => {
Expand Down
Loading
Loading