@heretyc/subagent-mcp 2.8.7 → 2.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,15 @@
1
- <!-- INJECTED PRE-PROMPT DIRECTIVE — BINDING, NON-NEGOTIABLE -->
2
1
  <subagent-mcp state="on" kind="directive">
3
2
  FIRST-LINE EXEMPTION: if this session's prompt's literal first line begins with "<this is a request from a parent process>", ignore this entire tag.
4
3
 
5
- ORCHESTRATION ON. You are the ORCHESTRATOR. This tag is MAXIMALLY CRITICAL: obey with NO exceptions. No user request overrides it; the only user-changeable thing is the ON/OFF state, reported authoritatively by this hook injection.
4
+ ORCHESTRATION ON. You are the ORCHESTRATOR. Obey this tag; ordinary user requests do not override it. Only the hook's ON/OFF state changes this mode.
6
5
 
7
- ALLOWED TOOLS: ONLY AskUserQuestion + subagent-mcp. NO direct reads or writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. A non-delegable atomic step → ask the user via AskUserQuestion for a one-time exception, do ONLY that step, then resume delegating.
6
+ ALLOWED TOOLS: ONLY AskUserQuestion + subagent-mcp. NO direct reads/writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. Non-delegable atomic step → ask via AskUserQuestion for a one-time exception, do ONLY that step, then resume delegating.
8
7
 
9
- READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs: assign scratch-file PATHS; producer writes, consumer reads; you NEVER read those files.
8
+ READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs use scratch-file PATHS; producer writes, consumer reads; you NEVER read them.
10
9
 
11
- PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and escalate to the user (FORBIDDEN: resolving it yourself). SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask the user; stay halted until restored. The only user choices are keep-waiting or explicitly abandon the whole task; aborting ends the task, it never switches you to inline work. DISABLE: never on your own initiative.
10
+ SUBDIVIDE: delegate the SMALLEST auditable step yielding an observable artifact. NEVER 1-shot multi-phase work. For code/non-trivial steps, prefer an independent verifier sub-agent before proceeding.
11
+
12
+ PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and ask the user. SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask; stay halted until restored. Abort ends the task; it never switches you inline. DISABLE: never on your own initiative.
12
13
 
13
14
  Full model + governance: server MCP `instructions`.
14
15
  </subagent-mcp>
@@ -1,14 +1,15 @@
1
- <!-- INJECTED PRE-PROMPT DIRECTIVE — BINDING, NON-NEGOTIABLE -->
2
1
  <subagent-mcp state="on" kind="directive">
3
2
  FIRST-LINE EXEMPTION: if this session's prompt's literal first line begins with "<this is a request from a parent process>", ignore this entire tag.
4
3
 
5
- ORCHESTRATION ON. You are the ORCHESTRATOR. This tag is MAXIMALLY CRITICAL: obey with NO exceptions. No user request overrides it; the only user-changeable thing is the ON/OFF state, reported authoritatively by this hook injection.
4
+ ORCHESTRATION ON. You are the ORCHESTRATOR. Obey this tag; ordinary user requests do not override it. Only the hook's ON/OFF state changes this mode.
6
5
 
7
- ALLOWED TOOLS: ONLY request-user-input + subagent-mcp. NO direct reads or writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. A non-delegable atomic step → ask the user via request-user-input for a one-time exception, do ONLY that step, then resume delegating.
6
+ ALLOWED TOOLS: ONLY request-user-input + subagent-mcp. NO direct reads/writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. Non-delegable atomic step → ask via request-user-input for a one-time exception, do ONLY that step, then resume delegating.
8
7
 
9
- READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs: assign scratch-file PATHS; producer writes, consumer reads; you NEVER read those files.
8
+ READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs use scratch-file PATHS; producer writes, consumer reads; you NEVER read them.
10
9
 
11
- PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and escalate to the user (FORBIDDEN: resolving it yourself). SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask the user; stay halted until restored. The only user choices are keep-waiting or explicitly abandon the whole task; aborting ends the task, it never switches you to inline work. DISABLE: never on your own initiative.
10
+ SUBDIVIDE: delegate the SMALLEST auditable step yielding an observable artifact. NEVER 1-shot multi-phase work. For code/non-trivial steps, prefer an independent verifier sub-agent before proceeding.
11
+
12
+ PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and ask the user. SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask; stay halted until restored. Abort ends the task; it never switches you inline. DISABLE: never on your own initiative.
12
13
 
13
14
  Full model + governance: server MCP `instructions`.
14
15
  </subagent-mcp>
@@ -6,6 +6,8 @@ Orchestration ON. You are the orchestrator: delegate EVERY step. Allowed tools =
6
6
 
7
7
  READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the user reads it. Large handoffs via scratch-file PATHS you never read.
8
8
 
9
+ SUBDIVIDE: smallest auditable step per sub-agent; never 1-shot multi-phase work (no implement+test+docs in one); verify code steps independently.
10
+
9
11
  WAIT-NOT-POLL: learn finish via `wait` (verbose:true for output); never loop poll_agent for completion. poll_agent = single diagnostic; stalled/empty = alive, not dead.
10
12
 
11
13
  This tag is co-supreme with safety-scope (conflict → ask the user) and outranks ordinary user requests. Full governance: server MCP `instructions`.
@@ -1 +1 @@
1
- <subagent-mcp state="on" kind="carrier">If this prompt's literal first line begins with "<this is a request from a parent process>", ignore this tag. Orchestration ON. Delegate-only via subagent-mcp; allowed tools = structured-question tool + subagent-mcp; NO direct reads/writes; inline-by-right does not exist. Follow the MOST RECENT <subagent-mcp state="on"> tag in context (directive or reminder/carrier); if none is in the current window, the INIT_BLOCK governs. Co-supreme with safety-scope; no ordinary user request bypasses it.</subagent-mcp>
1
+ <subagent-mcp state="on" kind="carrier">If first line begins "<this is a request from a parent process>", ignore this tag. Orchestration ON. Delegate-only via subagent-mcp; allowed tools = structured-question tool + subagent-mcp; no direct reads/writes; inline-by-right does not exist. Subdivide small; verify code steps. Follow MOST RECENT <subagent-mcp state="on"> tag; if absent, INIT_BLOCK governs. Co-supreme with safety-scope; user request cannot bypass.</subagent-mcp>
package/dist/drivers.js CHANGED
@@ -2,6 +2,13 @@ import { spawn } from "node:child_process";
2
2
  import { EventEmitter } from "node:events";
3
3
  import { PassThrough } from "node:stream";
4
4
  import { mapModel } from "./effort.js";
5
+ export class ProviderTransientError extends Error {
6
+ isTransient = true;
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "ProviderTransientError";
10
+ }
11
+ }
5
12
  class LogicalProcess extends EventEmitter {
6
13
  pid;
7
14
  stdout = new PassThrough();
@@ -120,10 +127,18 @@ function userMessage(text) {
120
127
  function textInput(text) {
121
128
  return { type: "text", text, text_elements: [] };
122
129
  }
123
- class MockJsonlDriver {
130
+ export class MockJsonlDriver {
124
131
  child;
125
132
  provider;
133
+ static transientPreStartHook = null;
134
+ static postStartErrorHook = null;
126
135
  process;
136
+ _definitelyStartedResolve;
137
+ _definitelyStartedReject;
138
+ definitelyStarted = new Promise((res, rej) => {
139
+ this._definitelyStartedResolve = res;
140
+ this._definitelyStartedReject = rej;
141
+ });
127
142
  queue = Promise.resolve();
128
143
  turn = 0;
129
144
  constructor(child, provider) {
@@ -136,7 +151,10 @@ class MockJsonlDriver {
136
151
  if (!this.process.killed)
137
152
  this.process.close(code, signal);
138
153
  });
139
- child.stdout?.on("data", (chunk) => this.process.stdout.write(chunk));
154
+ child.stdout?.on("data", (chunk) => {
155
+ this._definitelyStartedResolve();
156
+ this.process.stdout.write(chunk);
157
+ });
140
158
  child.stderr?.on("data", (chunk) => this.process.stderr.write(chunk));
141
159
  // Swallow stdin pipe errors (e.g. EPIPE writing to an exited child): the
142
160
  // writeLine() callback already surfaces the failure; without this listener
@@ -147,6 +165,20 @@ class MockJsonlDriver {
147
165
  return this.process.killed || this.child.killed || this.child.exitCode !== null;
148
166
  }
149
167
  start(message) {
168
+ if (MockJsonlDriver.transientPreStartHook) {
169
+ MockJsonlDriver.transientPreStartHook(this.provider);
170
+ const err = new ProviderTransientError(`mock transient pre-start failure (${this.provider})`);
171
+ this._definitelyStartedReject(err);
172
+ return Promise.reject(err);
173
+ }
174
+ if (MockJsonlDriver.postStartErrorHook) {
175
+ this._definitelyStartedResolve();
176
+ MockJsonlDriver.postStartErrorHook(this.provider);
177
+ setTimeout(() => {
178
+ this.process.stderr.write(`mock post-start error (${this.provider})\n`);
179
+ this.process.close(1);
180
+ }, 0);
181
+ }
150
182
  return this.send(message);
151
183
  }
152
184
  send(message) {
@@ -175,6 +207,12 @@ export class CodexAppServerDriver {
175
207
  child;
176
208
  options;
177
209
  process;
210
+ _definitelyStartedResolve;
211
+ _definitelyStartedReject;
212
+ definitelyStarted = new Promise((res, rej) => {
213
+ this._definitelyStartedResolve = res;
214
+ this._definitelyStartedReject = rej;
215
+ });
178
216
  pending = new Map();
179
217
  queuedTurns = [];
180
218
  nextId = 1;
@@ -341,6 +379,7 @@ export class CodexAppServerDriver {
341
379
  const turn = (message.params.turn ?? {});
342
380
  if (typeof turn.id === "string")
343
381
  this.activeTurnId = turn.id;
382
+ this._definitelyStartedResolve();
344
383
  }
345
384
  if (message.method === "turn/completed") {
346
385
  this.activeTurnId = null;
@@ -349,6 +388,9 @@ export class CodexAppServerDriver {
349
388
  }
350
389
  }
351
390
  fail(error) {
391
+ const msg = error.message;
392
+ const transient = /\b429\b|\b5\d{2}\b|quota|rate.?limit|timeout|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(msg);
393
+ this._definitelyStartedReject(transient ? new ProviderTransientError(msg) : error);
352
394
  this.process.fail(error);
353
395
  this.rejectPending(error);
354
396
  }
@@ -364,6 +406,12 @@ export class CodexAppServerDriver {
364
406
  export class ClaudeSdkDriver {
365
407
  queryFn;
366
408
  process = new LogicalProcess(undefined, true);
409
+ _definitelyStartedResolve;
410
+ _definitelyStartedReject;
411
+ definitelyStarted = new Promise((res, rej) => {
412
+ this._definitelyStartedResolve = res;
413
+ this._definitelyStartedReject = rej;
414
+ });
367
415
  input = new AsyncInputQueue();
368
416
  abortController = new AbortController();
369
417
  queue = Promise.resolve();
@@ -421,8 +469,13 @@ export class ClaudeSdkDriver {
421
469
  this.process.kill("SIGKILL");
422
470
  }
423
471
  async pump(query) {
472
+ let started = false;
424
473
  try {
425
474
  for await (const message of query) {
475
+ if (!started) {
476
+ started = true;
477
+ this._definitelyStartedResolve();
478
+ }
426
479
  this.process.stdout.write(`${JSON.stringify(message)}\n`);
427
480
  }
428
481
  this.closedFlag = true;
@@ -430,8 +483,11 @@ export class ClaudeSdkDriver {
430
483
  }
431
484
  catch (error) {
432
485
  if (!this.process.killed) {
486
+ const msg = error instanceof Error ? error.message : String(error);
487
+ const transient = /\b429\b|\b5\d{2}\b|quota|rate.?limit|timeout|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(msg);
488
+ this._definitelyStartedReject(transient ? new ProviderTransientError(msg) : new Error(msg));
433
489
  this.closedFlag = true;
434
- this.process.stderr.write(error instanceof Error ? error.message : String(error));
490
+ this.process.stderr.write(msg);
435
491
  this.process.close(1);
436
492
  }
437
493
  }
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ import { loadRoutingTable, buildCandidates, validatePresence, TASK_CATEGORIES, A
19
19
  import { createDeadlockWindow } from "./deadlock.js";
20
20
  import { createRulesetGate, RULESET_HARD_FAIL_MSG, } from "./ruleset.js";
21
21
  import * as orchestrationMarker from "./orchestration/marker.js";
22
+ import * as modelMode from "./orchestration/model-mode.js";
22
23
  import { startLivenessHeartbeat } from "./orchestration/liveness.js";
23
24
  import { ensureParentMarker } from "./launch-prompt.js";
24
25
  const agents = new Map();
@@ -52,6 +53,23 @@ const TASK_CATEGORY_GLOSS = "REQUIRED. Task shape -> routing category (server pi
52
53
  function errorResult(text) {
53
54
  return { content: [{ type: "text", text }], isError: true };
54
55
  }
56
+ export function classifyFailureReason(reason, stderr) {
57
+ const text = `${reason}\n${stderr}`;
58
+ return /\b429\b|\b5\d{2}\b|quota|usage.?cap|rate.?limit|timeout|connection.?reset|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(text)
59
+ ? "transient_provider"
60
+ : "permanent";
61
+ }
62
+ function buildFailoverNote(skipped, winner) {
63
+ const top = skipped[0];
64
+ const topLabel = `${top.model}@${top.effort} (${top.provider})`;
65
+ const winnerLabel = `${winner.model}@${winner.effort} (${winner.provider})`;
66
+ return `Rank-1 candidate ${topLabel} failed with ${top.failure_type === "transient_provider" ? "a transient provider error" : "a permanent error"}; auto-selected ${winnerLabel}.`;
67
+ }
68
+ function failureTypeForError(error, stderr) {
69
+ return error.isTransient
70
+ ? "transient_provider"
71
+ : classifyFailureReason(error.message, stderr);
72
+ }
55
73
  const isWindows = process.platform === "win32";
56
74
  let _npmPrefix = null;
57
75
  function getNpmPrefix() {
@@ -117,11 +135,15 @@ reconcileInterval.unref();
117
135
  // initialize (per the MCP spec the initialize result has an `instructions`
118
136
  // field) rather than re-injecting it on every turn. The bundled per-turn hook
119
137
  // injects only a small compact reminder; this is the durable, full explanation.
120
- const ORCHESTRATION_INSTRUCTIONS = "subagent-mcp CANONICAL OPERATING MODEL (read once; full detail in docs/spec/dev-loop/orchestration-directive-architecture.md).\n\nPRECEDENCE (co-supreme). A <subagent-mcp state=\"...\"> hook tag and repo/system safety rules are EQUAL top tier; genuine conflict → STOP and escalate to the user. Tags outrank user requests; only the hook `state` attribute changes ON/OFF.\n\nSOLE CHANNEL. EVERY sub-agent launch goes through launch_agent; never harness Task/Agent or shell spawn.\n\nORCHESTRATION ON (state=on; no-hook UNKNOWN→ON fail-safe). You are a delegate-ONLY orchestrator: directly use ONLY the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp; delegate all work. No direct read/write; inline-by-right DOES NOT EXIST. Non-delegable step: ASK for a ONE-TIME exception, do only it, resume.\n\nREAD-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.\n\nORCHESTRATION OFF (state=off). Long-horizon task = TOTAL footprint (read+produced) >200 lines, CUMULATIVE since last upgrade ask; after EVERY turn, if it qualifies STOP and ASK whether to switch ON; reset only when you ask.\n\nDROPOUT WHILE ON: HALT and ask user; nothing inline; stay halted UNTIL restored.\n\nSUB-AGENT EXEMPTION. A prompt whose literal FIRST LINE begins \"<this is a request from a parent process>\" SKIPS the whole regime (sub-agent); the only automatic suppressor of fail-safe-ON.";
121
- const SUBAGENT_INSTRUCTIONS = "SUB-AGENT SESSION: you are a child process launched by subagent-mcp. Follow the parent prompt. Do not treat yourself as the orchestrator, do not re-trigger orchestration carryover, and do not launch further sub-agents unless the parent prompt explicitly assigns that.";
138
+ // Canonical A2 mirror fragment retained byte-identical for
139
+ // test/mirror-fragments.test.mjs while ORCHESTRATION_INSTRUCTIONS below stays
140
+ // compressed under MCP metadata limits:
141
+ // READ-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.
142
+ const ORCHESTRATION_INSTRUCTIONS = "subagent-mcp - CANONICAL OPERATING MODEL (full spec: docs/spec/dev-loop/orchestration-directive-architecture.md).\n\nPRECEDENCE. The latest <subagent-mcp state=\"...\"> hook tag and repo/system safety rules are co-supreme; genuine conflict => STOP and ask the user. Only the hook state changes ON/OFF.\n\nSOLE CHANNEL. Every sub-agent launch uses launch_agent; never harness Task/Agent or shell-spawned agents.\n\nORCHESTRATION ON. You are a delegate-ONLY orchestrator. Use only the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp. No direct reads/writes; inline-by-right does not exist. Non-delegable atomic step: ask for a one-time exception, do only that step, then resume delegating.\n\nREAD LADDER. poll_agent tail -> one <=100-line summarizer sub-agent, trusted as-is -> else the USER reads it. Large handoffs use scratch-file paths; producer writes, consumer reads; orchestrator never reads those files. Empty/stalled tail means ALIVE; use wait.\n\nORCHESTRATION OFF. If total context footprint since last upgrade ask exceeds 200 lines, after that turn STOP and ask whether to switch ON; reset count only when you ask.\n\nDROPOUT WHILE ON: HALT and ask; stay halted until restored. SUB-AGENT EXEMPTION: a prompt whose literal FIRST LINE begins \"<this is a request from a parent process>\" skips this regime.\n\nMODEL SELECTION MODE. Default smart rejects provider/model/effort selectors; launch_agent auto-picks. user-approved-overrides lasts 30 minutes, expires lazily on launch_agent, and must be enabled only after explicit user authorization via AskUserQuestion/request-user-input.";
143
+ const SUBAGENT_INSTRUCTIONS = "SUB-AGENT SESSION: you are a child process launched by subagent-mcp. Follow the parent prompt. Do not treat yourself as the orchestrator, do not re-trigger orchestration carryover, and do not launch further sub-agents unless the parent prompt explicitly assigns that.\n\nMODEL SELECTION MODE (parallel to orchestration-mode, set via the model-selection-mode tool). DEFAULT is \"smart\" and is used whenever unset: in smart, launch_agent REJECTS any call supplying provider/model/effort selectors and the server auto-picks the best model. \"user-approved-overrides\" opens a 30-MINUTE window where selectors are HONORED, enforced LAZILY (the mode reverts to smart on the next launch_agent call after 30 minutes) and re-enabling does NOT extend an active window. HONOR-BASED: you MUST NOT set \"user-approved-overrides\" without explicit interactive USER authorization via the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex); never enable it on your own initiative.";
122
144
  const server = new McpServer({
123
145
  name: "subagent-mcp",
124
- version: "2.8.7",
146
+ version: "2.8.9",
125
147
  description: "Launches always-interactive local Claude and Codex sub-agent sessions. Claude uses the Claude Agent SDK over the local Claude Code executable; Codex uses `codex app-server` over stdio. The server does not call Anthropic or OpenAI HTTP APIs directly.",
126
148
  }, {
127
149
  instructions: process.env.SUBAGENT_MCP_SUBAGENT === "1"
@@ -156,9 +178,8 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
156
178
  const running = countProcessing(candidate.provider);
157
179
  const max = candidate.provider === "claude" ? MAX_CLAUDE : MAX_CODEX;
158
180
  if (running >= max) {
159
- return {
160
- reason: `Maximum ${max} concurrent ${candidate.provider} agents already running. Current: ${running}`,
161
- };
181
+ const reason = `Maximum ${max} concurrent ${candidate.provider} agents already running. Current: ${running}`;
182
+ return { reason, failure_type: "permanent" };
162
183
  }
163
184
  // Build the command. haiku ignores effort; pass "high" placeholder for the
164
185
  // "none" sentinel (buildCommand drops it for haiku anyway).
@@ -170,13 +191,14 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
170
191
  cmd = resolveExe(candidate.provider);
171
192
  }
172
193
  catch (e) {
173
- return { reason: e instanceof Error ? e.message : String(e) };
194
+ const reason = e instanceof Error ? e.message : String(e);
195
+ return { reason, failure_type: "permanent" };
174
196
  }
175
197
  // Fast-fail absolute paths only. Bare names intentionally rely on PATH; spawn
176
198
  // below resolves them and reports ENOENT/EACCES through the same failure path.
177
199
  if (isAbsolute(cmd) && !existsSync(cmd)) {
178
200
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
179
- return { reason: `CLI executable not found: ${cmd}` };
201
+ return { reason: `CLI executable not found: ${cmd}`, failure_type: "permanent" };
180
202
  }
181
203
  let driver;
182
204
  try {
@@ -194,9 +216,24 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
194
216
  catch (error) {
195
217
  // Synchronous spawn throw (rare) — clean up and report as a launch failure.
196
218
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
197
- return { reason: error instanceof Error ? error.message : String(error) };
219
+ const reason = error instanceof Error ? error.message : String(error);
220
+ return { reason, failure_type: classifyFailureReason(reason, "") };
198
221
  }
199
222
  const childProcess = driver.process;
223
+ let definitelyStarted = false;
224
+ const definitelyStartedProbe = driver.definitelyStarted.then(() => {
225
+ definitelyStarted = true;
226
+ return true;
227
+ }, () => {
228
+ return false;
229
+ });
230
+ const readStartedBoundary = async () => {
231
+ await Promise.race([
232
+ definitelyStartedProbe,
233
+ new Promise((resolve) => setTimeout(resolve, 0)),
234
+ ]);
235
+ return definitelyStarted;
236
+ };
200
237
  // Await the one-shot spawn/error race. The 'error' handler is attached BEFORE
201
238
  // we await so an async ENOENT cannot escape as an unhandled event.
202
239
  try {
@@ -217,7 +254,8 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
217
254
  }
218
255
  catch { }
219
256
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
220
- return { reason: err instanceof Error ? err.message : String(err) };
257
+ const reason = err instanceof Error ? err.message : String(err);
258
+ return { reason, failure_type: classifyFailureReason(reason, "") };
221
259
  }
222
260
  // Spawn succeeded. Register the agent exactly as before. Keep a persistent
223
261
  // 'error' handler so a LATE spawn error never crashes the process; fold it
@@ -367,6 +405,15 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
367
405
  }
368
406
  catch (err) {
369
407
  startError = err instanceof Error ? err : new Error(String(err));
408
+ await readStartedBoundary();
409
+ if (!definitelyStarted) {
410
+ const reason = startError.message;
411
+ cleanupUcSettings(agentState);
412
+ return {
413
+ reason,
414
+ failure_type: failureTypeForError(startError, agentState.stderr),
415
+ };
416
+ }
370
417
  }
371
418
  // Post-spawn grace window: a 'spawn' win alone is NOT success — a provider
372
419
  // driver that starts then dies immediately must advance the attempt loop, not
@@ -399,14 +446,22 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
399
446
  // turn.completed fast completion must never be misread as a launch
400
447
  // failure and the task silently re-executed on the next candidate.
401
448
  await closedAfterFlush;
402
- if (!agentState.turnCompleted) {
449
+ const startedBeforeExit = await readStartedBoundary();
450
+ if (!agentState.turnCompleted && !startedBeforeExit) {
403
451
  const tail = agentState.stderr.trim().split("\n").slice(-1)[0] ?? "";
452
+ const reason = `process exited (code ${earlyExit.code ?? earlyExit.signal}) within ${SPAWN_GRACE_MS}ms of spawn${tail ? `: ${tail}` : ""}`;
404
453
  return {
405
- reason: `process exited (code ${earlyExit.code ?? earlyExit.signal}) within ${SPAWN_GRACE_MS}ms of spawn${tail ? `: ${tail}` : ""}`,
454
+ reason,
455
+ failure_type: classifyFailureReason(reason, agentState.stderr),
406
456
  };
407
457
  }
408
458
  }
409
459
  else if (startError && !agentState.turnCompleted) {
460
+ const startedBeforeStartError = await readStartedBoundary();
461
+ if (startedBeforeStartError) {
462
+ agents.set(agentId, agentState);
463
+ return { agentId };
464
+ }
410
465
  // Lived past the grace window but the startup write failed: the child is
411
466
  // not accepting input, so advance the loop rather than register an agent
412
467
  // that never received its prompt.
@@ -415,7 +470,10 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
415
470
  }
416
471
  catch { }
417
472
  cleanupUcSettings(agentState);
418
- return { reason: startError.message };
473
+ return {
474
+ reason: startError.message,
475
+ failure_type: failureTypeForError(startError, agentState.stderr),
476
+ };
419
477
  }
420
478
  }
421
479
  agents.set(agentId, agentState);
@@ -453,6 +511,10 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
453
511
  if (presenceError) {
454
512
  return errorResult(presenceError);
455
513
  }
514
+ const modelGate = modelMode.gateLaunch(agentCwd, { provider, model, effort });
515
+ if (!modelGate.allowed) {
516
+ return errorResult(modelGate.message ?? modelMode.SELECTOR_REJECTION_MESSAGE);
517
+ }
456
518
  // 6. Build the candidate list per mode.
457
519
  const overrides = { provider, model, effort };
458
520
  const isExplicit = !!(provider && model && effort);
@@ -542,6 +604,17 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
542
604
  if (branch === "performance") {
543
605
  deadlockWindow.consume();
544
606
  }
607
+ if (skipped.length > 0) {
608
+ const registeredAgent = agents.get(outcome.agentId);
609
+ if (registeredAgent) {
610
+ registeredAgent.failoverFrom = skipped.map((s) => ({
611
+ provider: s.provider,
612
+ model: s.model,
613
+ effort: s.effort,
614
+ failure_type: s.failure_type,
615
+ }));
616
+ }
617
+ }
545
618
  return {
546
619
  content: [
547
620
  {
@@ -559,6 +632,18 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
559
632
  ruleset_original_selection: rulesetOriginalSelection,
560
633
  }
561
634
  : {}),
635
+ ...(skipped.length > 0
636
+ ? {
637
+ failover_occurred: true,
638
+ failover_from: skipped.map((s) => ({
639
+ provider: s.provider,
640
+ model: s.model,
641
+ effort: s.effort,
642
+ failure_type: s.failure_type,
643
+ })),
644
+ failover_note: buildFailoverNote(skipped, candidate),
645
+ }
646
+ : {}),
562
647
  }),
563
648
  },
564
649
  ],
@@ -569,17 +654,24 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
569
654
  effort: candidate.effort,
570
655
  provider: candidate.provider,
571
656
  reason: outcome.reason,
657
+ failure_type: outcome.failure_type,
572
658
  });
659
+ if (!pureAuto) {
660
+ break;
661
+ }
573
662
  }
574
- // 7. All candidates failed. A ruleset-modified explicit launch may have
575
- // attempted N≠1 candidates only the numbered ALL_FAILED shape can
576
- // report that, so the explicit shape is reserved for unmodified launches.
577
- if (isExplicit && !rulesetApplied) {
663
+ // 7. All candidates failed. Override selector modes are single-attempt hard
664
+ // failures; pure auto mode reports the attempted candidates.
665
+ if (!pureAuto) {
578
666
  const f = skipped[0];
579
- return errorResult(`Error: explicit launch ${f.model}@${f.effort} (${f.provider}) failed: ${f.reason}.\n${AUTO_HINT}`);
667
+ const transientNote = f.failure_type === "transient_provider"
668
+ ? `\nNote: this failure appears transient (quota/rate-limit/network). Switch to auto mode (omit provider/model/effort) for automatic silent failover to the next-best provider.`
669
+ : "";
670
+ const label = isExplicit ? "explicit" : "override";
671
+ return errorResult(`Error: ${label} launch ${f.model}@${f.effort} (${f.provider}) failed: ${f.reason}.${transientNote}\n${AUTO_HINT}`);
580
672
  }
581
673
  const lines = skipped
582
- .map((s, i) => ` ${i + 1}. ${s.model}@${s.effort} (${s.provider}): ${s.reason}`)
674
+ .map((s, i) => ` ${i + 1}. ${s.model}@${s.effort} (${s.provider}) [${s.failure_type}]: ${s.reason}`)
583
675
  .join("\n");
584
676
  return errorResult(`Error: all ${skipped.length} candidate launches failed for task_category ${task_category}:\n${lines}\n${SPLIT_HINT}\n${AUTO_HINT}`);
585
677
  });
@@ -634,6 +726,12 @@ server.tool("poll_agent", "Get an agent's current status and output. Status `pro
634
726
  ruleset_original_selection: agent.rulesetOriginalSelection,
635
727
  }
636
728
  : {}),
729
+ ...(agent.failoverFrom && agent.failoverFrom.length > 0
730
+ ? {
731
+ failover_occurred: true,
732
+ failover_from: agent.failoverFrom,
733
+ }
734
+ : {}),
637
735
  recent_stream: agent.visibleStream.map((it) => ({
638
736
  type: it.type,
639
737
  text: it.text,
@@ -925,6 +1023,28 @@ server.tool("orchestration-mode", "Toggle or query per-project ORCHESTRATION MOD
925
1023
  ],
926
1024
  };
927
1025
  });
1026
+ // Tool 8: model-selection-mode
1027
+ server.tool("model-selection-mode", "Set or query per-project MODEL SELECTION MODE, which gates launch_agent's `provider`/`model`/`effort` selectors. `mode`: \"smart\" or \"user-approved-overrides\"; omit to query current state. \"smart\" is the DEFAULT and is used whenever the mode is unset — in smart, launch_agent REJECTS any call that supplies provider/model/effort and the server auto-picks the best model for the task_category. \"user-approved-overrides\" opens a 30-MINUTE window during which selectors are HONORED; the window is enforced LAZILY — the mode reverts to smart on the next launch_agent call after the 30 minutes elapse — and re-enabling does NOT extend an already-active window. HONOR-BASED, parallel to orchestration-mode: you MUST NOT set this to \"user-approved-overrides\" without explicit interactive USER authorization obtained via the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex; a plain yes/no exchange if neither exists). This tool CANNOT verify that authorization — never enable it on your own initiative. PERSISTENCE: per-project state keyed by cwd; both the mode and the override-window enable-timestamp persist across MCP server restarts (the remaining window is restored, not reset).", {
1028
+ mode: z.enum(["smart", "user-approved-overrides"]).optional(),
1029
+ }, async (params) => {
1030
+ const cwd = process.cwd();
1031
+ if (params.mode)
1032
+ modelMode.setMode(cwd, params.mode);
1033
+ const r = modelMode.resolveMode(cwd);
1034
+ return {
1035
+ content: [
1036
+ {
1037
+ type: "text",
1038
+ text: JSON.stringify({
1039
+ model_selection_mode: r.mode,
1040
+ enabled_at: r.enabled_at,
1041
+ window_remaining_ms: r.window_remaining_ms,
1042
+ marker_path: modelMode.modelModePath(cwd),
1043
+ }, null, 2),
1044
+ },
1045
+ ],
1046
+ };
1047
+ });
928
1048
  // Connect the stdio transport only when run as the entry point (the bin), NOT
929
1049
  // when this module is imported (e.g. test/handler-validation.test.mjs importing
930
1050
  // the exported validatePresence). Connecting on import would block the test on
package/dist/init.js CHANGED
@@ -6,7 +6,9 @@ export const INIT_BLOCK = [
6
6
  "<!-- subagent-mcp:managed:begin schema=2 -->",
7
7
  "## subagent-mcp invariant — managed block, do not edit between markers",
8
8
  "",
9
- 'SUB-AGENT EXEMPTION: if this session\'s prompt\'s literal FIRST LINE begins with "<this is a request from a parent process>", SKIP this entire block (you are a sub-agent; this prevents fail-safe-ON recursion and fork-bombs). Leading blank lines do not count — the marker must be physically line 1.',
9
+ 'SUB-AGENT EXEMPTION: if this session\'s prompt\'s literal FIRST LINE begins with "<this is a request from a parent process>", SKIP this entire block EXCEPT the SUB-AGENT WORKTREE CARVE-OUT below, which you MUST still obey (you are a sub-agent; this prevents fail-safe-ON recursion and fork-bombs). Leading blank lines do not count — the marker must be physically line 1.',
10
+ "",
11
+ "SUB-AGENT WORKTREE CARVE-OUT: you are a delegated sub-agent (env SUBAGENT_MCP_SUBAGENT=1), already placed in your target working tree by the orchestrator. Do NOT create or switch git worktrees; skip the worktree-isolation gate; do all mutating work directly in the provided cwd.",
10
12
  "",
11
13
  "CANONICAL SOURCE OF TRUTH: the subagent-mcp MCP `instructions` string (read once at connect) and docs/spec/dev-loop/orchestration-directive-architecture.md. This block carries the full ON operating model inline so the session is governed even if the MCP `instructions` are stale; if this block and the MCP `instructions` ever disagree, the MCP `instructions` win.",
12
14
  "",
@@ -16,6 +18,8 @@ export const INIT_BLOCK = [
16
18
  "",
17
19
  'ORCHESTRATION ON — you are the ORCHESTRATOR. Allowed tools: ONLY the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp. NO direct reads or writes of any kind. "Inline-by-right" does not exist. Every step runs in a sub-agent. If one atomic step truly cannot run in a sub-agent, ASK the user via the structured-question tool for a one-time exception for that single step, perform only that step, then resume delegating. SOLE CHANNEL: while subagent-mcp is connected, every sub-agent launch goes through `launch_agent`; never use harness-native sub-agent tools or shell-spawned agents.',
18
20
  "",
21
+ "ORCHESTRATOR WORKTREE SETUP: launch sub-agents in the main checkout cwd (they no longer self-isolate into per-agent worktrees); SERIALIZE any sub-agents that write the SAME files — never run concurrent writers over overlapping paths (no cwd-level lock exists).",
22
+ "",
19
23
  "READ-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.",
20
24
  "",
21
25
  'ORCHESTRATION OFF — a "long-horizon task" = any task whose TOTAL context footprint (input you read + output you produce) exceeds 200 lines of text. After EVERY user turn, measure the CUMULATIVE footprint accumulated since your last upgrade ask; reset that cumulative count to zero ONLY when you actually ask. If it qualifies, ASK the user via the structured-question tool whether to switch orchestration ON. Ask on EVERY qualifying turn; a decline does NOT suppress future asks. You never assert ON yourself — you only ask.',