@heretyc/subagent-mcp 2.10.4 → 2.12.1

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.
package/dist/drivers.js CHANGED
@@ -108,6 +108,12 @@ class AsyncInputQueue {
108
108
  for (const taker of this.takers.splice(0))
109
109
  taker({ value: undefined, done: true });
110
110
  }
111
+ // True when the consumer (SDK query loop) is blocked awaiting input and nothing
112
+ // is buffered — i.e. the model turn ended and it is idle. A watchdog uses this
113
+ // to decide whether a resume turn is warranted.
114
+ get isAwaitingInput() {
115
+ return !this.closed && this.items.length === 0 && this.takers.length > 0;
116
+ }
111
117
  [Symbol.asyncIterator]() {
112
118
  return {
113
119
  next: () => {
@@ -147,6 +153,48 @@ function userMessage(text) {
147
153
  function textInput(text) {
148
154
  return { type: "text", text, text_elements: [] };
149
155
  }
156
+ // Server->client RPC methods that block on a client answer (elicitation /
157
+ // approval). Matched case-insensitively so provider-namespaced variants
158
+ // (e.g. "codex/requestUserInput", "session/requestApproval") are covered.
159
+ function isElicitationMethod(method) {
160
+ return /requestuserinput|elicit|approv/i.test(method);
161
+ }
162
+ // Shape the `result` payload for an elicitation reply. When the RPC offered a
163
+ // discrete option set, select only an exact case-insensitive label match and
164
+ // echo its identifier; otherwise pass the answer through as text.
165
+ function buildElicitationResult(options, answer) {
166
+ if (options && options.length > 0) {
167
+ const norm = answer.trim().toLowerCase();
168
+ const chosen = options.find((opt) => {
169
+ const label = optionLabel(opt);
170
+ return label !== null && norm === label.trim().toLowerCase();
171
+ });
172
+ if (chosen) {
173
+ const id = optionId(chosen);
174
+ return id !== null ? { optionId: id } : { option: chosen };
175
+ }
176
+ }
177
+ return { text: answer };
178
+ }
179
+ function optionLabel(opt) {
180
+ for (const key of ["label", "name", "title", "text", "value", "id"]) {
181
+ const v = opt[key];
182
+ if (typeof v === "string" && v.length > 0)
183
+ return v;
184
+ }
185
+ return null;
186
+ }
187
+ function optionId(opt) {
188
+ for (const key of ["id", "value", "optionId", "label", "name"]) {
189
+ const v = opt[key];
190
+ if (typeof v === "string" || typeof v === "number")
191
+ return v;
192
+ }
193
+ return null;
194
+ }
195
+ function isJsonRpcId(id) {
196
+ return typeof id === "string" || typeof id === "number";
197
+ }
150
198
  export class MockJsonlDriver {
151
199
  child;
152
200
  provider;
@@ -254,6 +302,10 @@ export class CodexAppServerDriver {
254
302
  initialized = false;
255
303
  turnInFlight = false;
256
304
  maxQueueDepth = 32;
305
+ // An inbound server->client RPC (elicitation, e.g. requestUserInput / approval)
306
+ // awaiting a reply. While set, the next send() answers this request instead of
307
+ // enqueuing a new turn — otherwise the in-flight question turn wedges the queue.
308
+ pendingServerRequest = null;
257
309
  constructor(child, options) {
258
310
  this.child = child;
259
311
  this.options = options;
@@ -301,6 +353,18 @@ export class CodexAppServerDriver {
301
353
  if (!this.initialized || !this.threadId) {
302
354
  return Promise.reject(new Error("codex app-server thread is not initialized"));
303
355
  }
356
+ if (this.pendingServerRequest) {
357
+ // The message is the user's answer to a parked server-side elicitation.
358
+ // Reply on the same JSON-RPC id (mirroring the { id, result } envelope our
359
+ // own request() responses arrive in) instead of enqueuing a fresh turn.
360
+ const req = this.pendingServerRequest;
361
+ this.pendingServerRequest = null;
362
+ return writeLine(this.child.stdin, {
363
+ jsonrpc: "2.0",
364
+ id: req.id,
365
+ result: buildElicitationResult(req.options, message),
366
+ });
367
+ }
304
368
  if (this.queuedTurns.length >= this.maxQueueDepth) {
305
369
  return Promise.reject(new Error(`provider input queue is full (${this.maxQueueDepth})`));
306
370
  }
@@ -315,6 +379,7 @@ export class CodexAppServerDriver {
315
379
  this.process.kill("SIGKILL");
316
380
  this.rejectPending(new Error("codex app-server driver was killed"));
317
381
  this.queuedTurns.length = 0;
382
+ this.pendingServerRequest = null;
318
383
  }
319
384
  async drainQueuedTurns() {
320
385
  if (this.drainActive)
@@ -406,6 +471,16 @@ export class CodexAppServerDriver {
406
471
  pending.resolve(message);
407
472
  }
408
473
  }
474
+ else if (isJsonRpcId(message.id) &&
475
+ typeof message.method === "string" &&
476
+ isElicitationMethod(message.method)) {
477
+ // Inbound server->client RPC (elicitation) that is NOT a reply to one of
478
+ // our requests. Park it so the next send() answers it instead of queuing a
479
+ // new turn; leaving it unanswered wedges the in-flight question turn.
480
+ const params = (message.params ?? {});
481
+ const options = Array.isArray(params.options) ? params.options : undefined;
482
+ this.pendingServerRequest = { id: message.id, method: message.method, options };
483
+ }
409
484
  if (message.method === "turn/started" && message.params && typeof message.params === "object") {
410
485
  const turn = (message.params.turn ?? {});
411
486
  if (typeof turn.id === "string")
@@ -448,6 +523,10 @@ export class ClaudeSdkDriver {
448
523
  queue = Promise.resolve();
449
524
  queryHandle = null;
450
525
  closedFlag = false;
526
+ // Debounce for notifyTaskComplete(): set when a resume turn is pushed, cleared
527
+ // as soon as the model streams any message (see pump). Prevents a stalled agent
528
+ // from being resumed more than once per idle cycle.
529
+ resumePending = false;
451
530
  constructor(queryFn) {
452
531
  this.queryFn = queryFn;
453
532
  }
@@ -490,6 +569,30 @@ export class ClaudeSdkDriver {
490
569
  this.queue = next.catch(() => { });
491
570
  return next;
492
571
  }
572
+ // Wake the SDK query loop after the agent's own background task finishes. The
573
+ // loop parks on `await next input` once the model turn ends; nothing else
574
+ // pushes a resume, so a sub-agent that spawned a bg task would stall forever.
575
+ // Pushes a synthetic user turn through the SAME input queue send() uses.
576
+ //
577
+ // WIRING: the notification source (task_notification for THIS agent's bg task)
578
+ // is not visible inside drivers.ts. The owning server/monitor must call
579
+ // driver.notifyTaskComplete() when it observes this agent's background
580
+ // task_notification while the agent is `stalled` with an empty input queue
581
+ // (see AsyncInputQueue.isAwaitingInput). Guarded so repeat calls are no-ops
582
+ // until the model next produces output.
583
+ notifyTaskComplete(text) {
584
+ if (this.closed || this.resumePending)
585
+ return Promise.resolve();
586
+ this.resumePending = true;
587
+ const resumeText = text ?? "Your background task has completed. Resume and continue where you left off.";
588
+ const next = this.queue.then(() => {
589
+ if (this.closed)
590
+ return;
591
+ return this.input.push(userMessage(resumeText));
592
+ });
593
+ this.queue = next.catch(() => { });
594
+ return next;
595
+ }
493
596
  kill() {
494
597
  if (this.closedFlag)
495
598
  return;
@@ -503,6 +606,9 @@ export class ClaudeSdkDriver {
503
606
  let started = false;
504
607
  try {
505
608
  for await (const message of query) {
609
+ // The model is producing output again: clear the resume debounce so a
610
+ // future bg-task completion can wake it once more.
611
+ this.resumePending = false;
506
612
  const text = claudeMessageText(message);
507
613
  if (!started && text && isClaudeSessionLimit(text)) {
508
614
  // Launch-time failover only applies before startup resolves/spawn grace ends;
@@ -1,29 +1,29 @@
1
- // subagent-mcp — Global Concurrent Subagent Cap
2
- // ------------------------------------------------------------------
3
- // SOLE source of truth for the machine-wide limit on how many subagents
4
- // may be ALIVE AT ONCE across EVERY session, process, and user on this
5
- // machine. There is NO environment-variable override.
6
- //
7
- // The whole recursive descendant tree counts toward this ONE number: a
8
- // subagent that itself launches subagents adds to the same machine-wide
9
- // total, and OTHER active agentic sessions count too.
10
- //
11
- // RE-READ on every launch_agent call — edits take effect immediately, no
12
- // server restart required.
13
- //
14
- // Value rules (forcibly applied to the number below):
15
- // - missing / unset / non-integer / 0 / negative -> reset to default 20
16
- // - 1 through 9 -> forced UP to minimum 10
17
- // - 10 or greater -> used as-is
18
- //
1
+ // subagent-mcp — Global Concurrent Subagent Cap
2
+ // ------------------------------------------------------------------
3
+ // SOLE source of truth for the machine-wide limit on how many subagents
4
+ // may be ALIVE AT ONCE across EVERY session, process, and user on this
5
+ // machine. There is NO environment-variable override.
6
+ //
7
+ // The whole recursive descendant tree counts toward this ONE number: a
8
+ // subagent that itself launches subagents adds to the same machine-wide
9
+ // total, and OTHER active agentic sessions count too.
10
+ //
11
+ // RE-READ on every launch_agent call — edits take effect immediately, no
12
+ // server restart required.
13
+ //
14
+ // Value rules (forcibly applied to the number below):
15
+ // - missing / unset / non-integer / 0 / negative -> reset to default 20
16
+ // - 1 through 9 -> forced UP to minimum 10
17
+ // - 10 or greater -> used as-is
18
+ //
19
19
  // Zombie culling is always enabled. There is no config knob. Before cap
20
20
  // rejection, launch/tool/hook paths refresh live owned slots, preserve stale
21
21
  // slots whose owner server is still alive, and cull stale slots whose owner is
22
22
  // gone. Managed stale slots terminate the child process tree, then force-kill
23
23
  // after 20s when needed; unmanaged stale slots are only unlinked.
24
- //
25
- // When the cap is reached after culling, launch_agent is REJECTED (never
26
- // queued). Free a slot with list_agents + kill_agent, then retry.
27
- {
28
- "globalConcurrentSubagents": 20
29
- }
24
+ //
25
+ // When the cap is reached after culling, launch_agent is REJECTED (never
26
+ // queued). Free a slot with list_agents + kill_agent, then retry.
27
+ {
28
+ "globalConcurrentSubagents": 20
29
+ }
package/dist/index.js CHANGED
@@ -24,9 +24,8 @@ import * as modelMode from "./orchestration/model-mode.js";
24
24
  import { startLivenessHeartbeat } from "./orchestration/liveness.js";
25
25
  import { ensureParentMarker } from "./launch-prompt.js";
26
26
  const agents = new Map();
27
- const MAX_CLAUDE = 5;
28
- const MAX_CODEX = 5;
29
27
  const deadlockWindow = createDeadlockWindow();
28
+ const STDOUT_RING_BYTES = 2 * 1024 * 1024;
30
29
  // Advanced-ruleset gate: per-process latch with exactly the deadlock-window
31
30
  // scoping. The env-check runs lazily at the FIRST launch_agent call; success
32
31
  // latches enabled/disabled for the process lifetime, failure never latches.
@@ -290,12 +289,96 @@ function failureTypeForError(error, stderr) {
290
289
  : classifyFailureReason(error.message, stderr);
291
290
  }
292
291
  const isWindows = process.platform === "win32";
293
- let _npmPrefix = null;
292
+ // Resolved lazily and memoized on first use so that plain CLI invocations never
293
+ // spawn `npm prefix -g` at import time. The server warms this once during
294
+ // startup (see main()) so a live, long-lived server never stalls mid-request.
295
+ let npmPrefixCache;
294
296
  function getNpmPrefix() {
295
- if (!_npmPrefix) {
296
- _npmPrefix = execSync("npm prefix -g", { encoding: "utf-8" }).trim();
297
+ if (npmPrefixCache === undefined) {
298
+ npmPrefixCache = execSync("npm prefix -g", { encoding: "utf-8" }).trim();
299
+ }
300
+ return npmPrefixCache;
301
+ }
302
+ const CLAUDE_BACKGROUND_RESUME_TEXT = "Your background task has completed. Resume and continue where you left off.";
303
+ export function isClaudeBackgroundWakeLine(line) {
304
+ const trimmed = line.trim();
305
+ if (!trimmed)
306
+ return false;
307
+ try {
308
+ const evt = JSON.parse(trimmed);
309
+ if (evt.type === "result")
310
+ return false;
311
+ const method = typeof evt.method === "string" ? evt.method : "";
312
+ const type = typeof evt.type === "string" ? evt.type : "";
313
+ const name = typeof evt.name === "string" ? evt.name : "";
314
+ const marker = `${method} ${type} ${name}`.toLowerCase();
315
+ if (marker.includes("task_notification") || marker.includes("task-notification"))
316
+ return true;
317
+ if (marker.includes("background") && marker.includes("complete"))
318
+ return true;
319
+ if (marker.includes("taskoutput") && marker.includes("complete"))
320
+ return true;
321
+ // No concrete Claude bg-task-complete JSONL fixture exists in-repo. As a
322
+ // backstop, any non-result JSONL activity after a finished turn means the
323
+ // still-live SDK stream observed something new and needs a nudge.
324
+ return true;
325
+ }
326
+ catch {
327
+ return false;
328
+ }
329
+ }
330
+ function noteBackgroundResumeSignal(agent, at) {
331
+ if (agent.provider !== "claude" || agent.driver.closed)
332
+ return;
333
+ agent.bgTaskResumeObservedAt = Math.max(agent.bgTaskResumeObservedAt ?? 0, at);
334
+ }
335
+ export async function maybeResumeAfterBackgroundTask(agent, now = Date.now()) {
336
+ if (agent.provider !== "claude")
337
+ return false;
338
+ if (agent.driver.closed)
339
+ return false;
340
+ if (agent.bgTaskResumeInFlight)
341
+ return false;
342
+ const observedAt = agent.bgTaskResumeObservedAt ?? 0;
343
+ if (observedAt === 0 || observedAt <= (agent.bgTaskResumeSentAt ?? 0))
344
+ return false;
345
+ agent.bgTaskResumeInFlight = true;
346
+ try {
347
+ if (typeof agent.driver.notifyTaskComplete === "function") {
348
+ await agent.driver.notifyTaskComplete(CLAUDE_BACKGROUND_RESUME_TEXT);
349
+ }
350
+ else {
351
+ await agent.driver.send(CLAUDE_BACKGROUND_RESUME_TEXT);
352
+ }
353
+ agent.bgTaskResumeSentAt = observedAt;
354
+ agent.status = "processing";
355
+ agent.lastExitCode = agent.exitCode;
356
+ agent.lastExitedAt = agent.exitedAt;
357
+ agent.exitCode = null;
358
+ agent.exitedAt = null;
359
+ agent.waitReported = false;
360
+ agent.turnCompleted = false;
361
+ agent.lastActivity = now;
362
+ return true;
363
+ }
364
+ finally {
365
+ agent.bgTaskResumeInFlight = false;
366
+ }
367
+ }
368
+ function handleCompletedStdoutLines(agent, lines, at) {
369
+ let turnWasComplete = agent.turnCompleted === true;
370
+ for (const line of lines) {
371
+ if (turnWasComplete && isClaudeBackgroundWakeLine(line)) {
372
+ noteBackgroundResumeSignal(agent, at);
373
+ }
374
+ if (isTurnCompletedLine(agent.provider, line)) {
375
+ turnWasComplete = true;
376
+ agent.turnCompleted = true;
377
+ agent.status = "finished";
378
+ if (agent.exitedAt === null)
379
+ agent.exitedAt = at;
380
+ }
297
381
  }
298
- return _npmPrefix;
299
382
  }
300
383
  function resolveExe(provider) {
301
384
  return resolveExeFor(provider, process.platform, { existsSync, npmPrefix: getNpmPrefix });
@@ -311,17 +394,6 @@ function cleanupUcSettings(agentState) {
311
394
  agentState.ucSettingsPath = undefined;
312
395
  }
313
396
  }
314
- // Concurrency cap accounting: only `processing` agents count against a
315
- // provider's cap. `stalled` agents (live but quiet past the heartbeat window) do
316
- // NOT count, freeing a slot while they idle.
317
- function countProcessing(provider) {
318
- let count = 0;
319
- for (const a of agents.values()) {
320
- if (a.provider === provider && a.status === "processing")
321
- count++;
322
- }
323
- return count;
324
- }
325
397
  // Synchronously reconcile a single agent's status against the pure transition
326
398
  // helper. Folds the live process exitCode into AgentState first so an already-
327
399
  // exited process is reported as completed/failed immediately (no monitor lag).
@@ -347,6 +419,12 @@ const reconcileInterval = setInterval(() => {
347
419
  for (const agent of agents.values()) {
348
420
  reconcileAgent(agent, now);
349
421
  refreshLiveSlotMetadata(agent, now);
422
+ if (agent.bgTaskResumeObservedAt && agent.bgTaskResumeObservedAt > (agent.bgTaskResumeSentAt ?? 0)) {
423
+ void maybeResumeAfterBackgroundTask(agent, now).then((resumed) => {
424
+ if (resumed)
425
+ updateSlotMetadata(agent);
426
+ });
427
+ }
350
428
  }
351
429
  }, 10000);
352
430
  reconcileInterval.unref();
@@ -363,7 +441,7 @@ const ORCHESTRATION_INSTRUCTIONS = "subagent-mcp - CANONICAL OPERATING MODEL (fu
363
441
  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.";
364
442
  const server = new McpServer({
365
443
  name: "subagent-mcp",
366
- version: "2.10.4",
444
+ version: "2.12.1",
367
445
  description: "Launches always-interactive local Claude and Codex sub-agent sessions and is the orchestrator's sole launch channel. Claude runs via the Claude Agent SDK over the local Claude Code executable; Codex via `codex app-server` over stdio. The server never calls Anthropic or OpenAI HTTP APIs directly.",
368
446
  }, {
369
447
  instructions: process.env.SUBAGENT_MCP_SUBAGENT === "1"
@@ -394,13 +472,6 @@ function cleanupUcSettingsPath(ucSettingsPath) {
394
472
  // process. Any launch-time failure cleans up and is reported so the attempt loop
395
473
  // silently advances to the next candidate.
396
474
  async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rulesetInfo) {
397
- // Concurrency cap for this provider.
398
- const running = countProcessing(candidate.provider);
399
- const max = candidate.provider === "claude" ? MAX_CLAUDE : MAX_CODEX;
400
- if (running >= max) {
401
- const reason = `Maximum ${max} concurrent ${candidate.provider} agents already running. Current: ${running}`;
402
- return { reason, failure_type: "permanent" };
403
- }
404
475
  // Build the command. haiku ignores effort; pass "high" placeholder for the
405
476
  // "none" sentinel (buildCommand drops it for haiku anyway).
406
477
  const effortForBuild = candidate.effort === "none" ? "high" : candidate.effort;
@@ -499,6 +570,8 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
499
570
  stderr: "",
500
571
  exitCode: null,
501
572
  exitedAt: null,
573
+ lastExitCode: null,
574
+ lastExitedAt: null,
502
575
  // Launch time is the initial heartbeat. Only PARSED VISIBLE provider stream
503
576
  // items refresh lastActivity afterwards (see the stdout handler); raw
504
577
  // stdout/stderr chunks do NOT, so `stalled` means exactly "no visible
@@ -529,6 +602,9 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
529
602
  // Accumulate all complete lines into stored stdout.
530
603
  for (const line of lines) {
531
604
  agentState.stdout += line + "\n";
605
+ if (agentState.stdout.length > STDOUT_RING_BYTES) {
606
+ agentState.stdout = agentState.stdout.slice(-STDOUT_RING_BYTES);
607
+ }
532
608
  }
533
609
  if (items.length > 0) {
534
610
  // Heartbeat refreshes only on parsed visible provider stream items,
@@ -541,11 +617,12 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
541
617
  // logical interactive session can remain available for later messages.
542
618
  // Scan COMPLETE lines only so a marker split across chunks is matched
543
619
  // once fully assembled (never on a partial fragment).
544
- if (lines.some((l) => isTurnCompletedLine(agentState.provider, l))) {
545
- agentState.turnCompleted = true;
546
- agentState.status = "finished";
547
- if (agentState.exitedAt === null)
548
- agentState.exitedAt = at;
620
+ handleCompletedStdoutLines(agentState, lines, at);
621
+ if (agentState.bgTaskResumeObservedAt && agentState.bgTaskResumeObservedAt > (agentState.bgTaskResumeSentAt ?? 0)) {
622
+ void maybeResumeAfterBackgroundTask(agentState, at).then((resumed) => {
623
+ if (resumed)
624
+ updateSlotMetadata(agentState);
625
+ });
549
626
  }
550
627
  });
551
628
  }
@@ -565,15 +642,13 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
565
642
  agentState.streamBuf = "";
566
643
  for (const line of lines) {
567
644
  agentState.stdout += line + "\n";
645
+ if (agentState.stdout.length > STDOUT_RING_BYTES) {
646
+ agentState.stdout = agentState.stdout.slice(-STDOUT_RING_BYTES);
647
+ }
568
648
  }
569
649
  // A completion marker may arrive only in this final flush (no trailing
570
650
  // newline) — the grace window's success exception needs it.
571
- if (lines.some((l) => isTurnCompletedLine(agentState.provider, l))) {
572
- agentState.turnCompleted = true;
573
- agentState.status = "finished";
574
- if (agentState.exitedAt === null)
575
- agentState.exitedAt = at;
576
- }
651
+ handleCompletedStdoutLines(agentState, lines, at);
577
652
  if (items.length > 0) {
578
653
  agentState.lastActivity = at;
579
654
  agentState.visibleStream = retainLastN(agentState.visibleStream, items.map((it) => ({ ...it, at })), 3);
@@ -973,13 +1048,10 @@ server.tool("poll_agent", "Get an agent's current status and output. `processing
973
1048
  model: agent.model,
974
1049
  status: agent.status,
975
1050
  exit_code: agent.exitCode,
976
- stdout_tail: stdoutTail,
977
- stderr_tail: stderrTail,
978
1051
  started_at: agent.startedAt,
979
1052
  last_activity: agent.lastActivity,
980
1053
  cwd: agent.cwd,
981
1054
  ...liveness,
982
- ...(agent.routingTier !== undefined ? { routing_tier: agent.routingTier } : {}),
983
1055
  ...(agent.rulesetApplied
984
1056
  ? {
985
1057
  ruleset_applied: true,
@@ -998,7 +1070,11 @@ server.tool("poll_agent", "Get an agent's current status and output. `processing
998
1070
  at: it.at !== undefined ? formatLocalIso(it.at) : null,
999
1071
  })),
1000
1072
  ...(params.verbose
1001
- ? { final_output: extractFinalTurn(agent.provider, agent.stdout) }
1073
+ ? {
1074
+ stdout_tail: stdoutTail,
1075
+ stderr_tail: stderrTail,
1076
+ final_output: extractFinalTurn(agent.provider, agent.stdout),
1077
+ }
1002
1078
  : {}),
1003
1079
  }),
1004
1080
  },
@@ -1119,6 +1195,8 @@ server.tool("send_message", "Enqueue a user message for an open interactive agen
1119
1195
  await agent.driver.send(params.message);
1120
1196
  const now = Date.now();
1121
1197
  agent.status = "processing";
1198
+ agent.lastExitCode = agent.exitCode;
1199
+ agent.lastExitedAt = agent.exitedAt;
1122
1200
  agent.exitCode = null;
1123
1201
  agent.exitedAt = null;
1124
1202
  agent.waitReported = false;
@@ -1218,7 +1296,7 @@ server.tool("wait", "Blocks until one or more sub-agents reach a reportable stat
1218
1296
  a.waitReported = true;
1219
1297
  const payload = { finished: unreported.map(buildFinishedEntry) };
1220
1298
  return {
1221
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1299
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1222
1300
  };
1223
1301
  }
1224
1302
  // Step 2: nothing alive and nothing unreported (includes stopped-but-not-yet-closed).
@@ -1233,7 +1311,7 @@ server.tool("wait", "Blocks until one or more sub-agents reach a reportable stat
1233
1311
  message: "No agents are running or waiting to finish.",
1234
1312
  };
1235
1313
  return {
1236
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1314
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1237
1315
  };
1238
1316
  }
1239
1317
  // Step 3: block-poll until a terminal agent appears or deadline passes
@@ -1246,7 +1324,7 @@ server.tool("wait", "Blocks until one or more sub-agents reach a reportable stat
1246
1324
  a.waitReported = true;
1247
1325
  const payload = { finished: unreported.map(buildFinishedEntry) };
1248
1326
  return {
1249
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1327
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1250
1328
  };
1251
1329
  }
1252
1330
  }
@@ -1260,7 +1338,7 @@ server.tool("wait", "Blocks until one or more sub-agents reach a reportable stat
1260
1338
  hint: "15 minutes elapsed with no agent finishing. Call wait again to block for another 15 minutes or until the next agent finishes.",
1261
1339
  };
1262
1340
  return {
1263
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1341
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1264
1342
  };
1265
1343
  }));
1266
1344
  // Tool 7: orchestration-mode
@@ -1519,6 +1597,7 @@ if (isMain) {
1519
1597
  // default-ON this rarely fires.
1520
1598
  // (the tool's enabled:false writes a disable record via writeDisable /
1521
1599
  // writeDisableCwd; it does not call disable().)
1600
+ getNpmPrefix();
1522
1601
  startLivenessHeartbeat();
1523
1602
  const transport = new StdioServerTransport();
1524
1603
  await server.connect(transport);
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { closeSync, openSync, readFileSync, readSync, statSync, } from "node:fs";
2
+ import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
5
  import * as marker from "./marker.js";
6
6
  import * as reminder from "./reminder.js";
7
7
  import { cullStaleSlots, slotDir, ZOMBIE_FORCE_GRACE_MS, } from "../concurrency.js";
@@ -37,9 +37,18 @@ export const REMINDER_PERIOD = 5;
37
37
  * === <repoRoot>/directives.
38
38
  */
39
39
  export function resolveDirectivesDir(env) {
40
- const root = env.CLAUDE_PLUGIN_ROOT || env.PLUGIN_ROOT;
41
- if (root) {
42
- return join(root, "directives");
40
+ const rootEnvName = env.CLAUDE_PLUGIN_ROOT !== undefined
41
+ ? "CLAUDE_PLUGIN_ROOT"
42
+ : env.PLUGIN_ROOT !== undefined
43
+ ? "PLUGIN_ROOT"
44
+ : undefined;
45
+ if (rootEnvName) {
46
+ const root = env[rootEnvName] ?? "";
47
+ const directivesDir = join(root, "directives");
48
+ if (!isAbsolute(root) || !existsSync(directivesDir)) {
49
+ throw new Error(`${rootEnvName} must be an absolute path with an existing directives directory: ${root}`);
50
+ }
51
+ return directivesDir;
43
52
  }
44
53
  const here = dirname(fileURLToPath(import.meta.url));
45
54
  // Compiled location is dist/orchestration/hook-core.js, so ../../directives
@@ -50,8 +59,9 @@ export function resolveDirectivesDir(env) {
50
59
  }
51
60
  /** Read a directive asset by filename. On ANY failure return '' (fail-safe). */
52
61
  export function readDirective(env, fileName) {
62
+ const directivesDir = resolveDirectivesDir(env);
53
63
  try {
54
- return readFileSync(join(resolveDirectivesDir(env), fileName), "utf8");
64
+ return readFileSync(join(directivesDir, fileName), "utf8");
55
65
  }
56
66
  catch {
57
67
  return "";