@vicary/pi-subagents 0.89.0 → 0.89.2

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.
Files changed (79) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-7W2IQFP4.js → chunk-464OJSDP.js} +4 -4
  5. package/bundle/{chunk-ETDE2VYK.js → chunk-4KQW5R6U.js} +2 -2
  6. package/bundle/{chunk-PFZZMVD5.js → chunk-4X3T5CPK.js} +12 -12
  7. package/bundle/{chunk-JRO2CU4D.js → chunk-5TXWZB73.js} +1 -1
  8. package/bundle/{chunk-CFIYO2IV.js → chunk-62OHSCQ6.js} +64 -12
  9. package/bundle/{chunk-7J4ZXMY7.js → chunk-72334PEI.js} +6 -4
  10. package/bundle/{chunk-S77ZKDLS.js → chunk-77VQEATI.js} +1 -1
  11. package/bundle/{chunk-HZDLR73C.js → chunk-AHGJSJYY.js} +4 -3
  12. package/bundle/{chunk-4ALRHKGE.js → chunk-DGLXVN3F.js} +1 -1
  13. package/bundle/{chunk-SLLZJ5EC.js → chunk-DHY5TY2Y.js} +237 -199
  14. package/bundle/{chunk-OVBUEVOT.js → chunk-DNDNLHTL.js} +11 -11
  15. package/bundle/{chunk-NQ26PJSQ.js → chunk-FF5K5HQU.js} +11 -6
  16. package/bundle/{chunk-HSHLPYCQ.js → chunk-FO2GIU5F.js} +27 -18
  17. package/bundle/{chunk-JFACGAJT.js → chunk-JEYG7CNC.js} +8 -4
  18. package/bundle/{chunk-7JLNWAMO.js → chunk-LODNNILA.js} +99 -30
  19. package/bundle/{chunk-GHJ6BH5U.js → chunk-LWH7IGI3.js} +8 -0
  20. package/bundle/{chunk-UQT2EQ4U.js → chunk-Q4VH72JI.js} +2 -2
  21. package/bundle/{chunk-443LPCRI.js → chunk-RHKIP45B.js} +6 -6
  22. package/bundle/{chunk-SWL2EITY.js → chunk-RHMU7SXN.js} +2 -2
  23. package/bundle/{chunk-WW6GQBBS.js → chunk-SRCMJY4F.js} +4 -4
  24. package/bundle/{chunk-KOLLMZ2X.js → chunk-SWGB2P5J.js} +1 -1
  25. package/bundle/{chunk-ZSCIHMUI.js → chunk-TXC7WIPL.js} +3 -2
  26. package/bundle/{chunk-6JD4XCA4.js → chunk-U753SUBC.js} +14 -6
  27. package/bundle/{chunk-A3INCQ6Z.js → chunk-UUW7P6KJ.js} +1 -1
  28. package/bundle/{chunk-MJHQIUU7.js → chunk-V4543APA.js} +33 -24
  29. package/bundle/{chunk-EPMRDKQT.js → chunk-VEEUXJDO.js} +1 -1
  30. package/bundle/{chunk-LEPIY76E.js → chunk-W7NDPDDJ.js} +8 -8
  31. package/bundle/{chunk-NONHDYXE.js → chunk-YJIU5WF4.js} +1 -1
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +4 -4
  37. package/docs/agents.md +2 -2
  38. package/docs/observability.md +3 -1
  39. package/docs/watchdog.md +3 -2
  40. package/package.json +2 -2
  41. package/src/api/preflight.d.ts +1 -0
  42. package/src/api/preflight.js +2 -1
  43. package/src/extension/herdr-pi-bridge.js +1 -1
  44. package/src/inspectors/herdr/project-panes.d.ts +2 -0
  45. package/src/inspectors/herdr/project-panes.js +7 -1
  46. package/src/inspectors/shell-command.d.ts +2 -1
  47. package/src/inspectors/shell-command.js +7 -5
  48. package/src/runs/background/active-async-capacity.js +2 -1
  49. package/src/runs/background/active-run-index.d.ts +1 -0
  50. package/src/runs/background/active-run-index.js +3 -0
  51. package/src/runs/background/async-execution.d.ts +2 -0
  52. package/src/runs/background/async-execution.js +3 -2
  53. package/src/runs/background/async-job-tracker.js +85 -9
  54. package/src/runs/background/async-status.d.ts +2 -0
  55. package/src/runs/background/async-status.js +8 -3
  56. package/src/runs/background/process-terminal.d.ts +6 -0
  57. package/src/runs/background/process-terminal.js +34 -2
  58. package/src/runs/background/run-status.js +2 -1
  59. package/src/runs/background/stale-run-reconciler.d.ts +8 -0
  60. package/src/runs/background/stale-run-reconciler.js +38 -8
  61. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  62. package/src/runs/background/workflow-terminal-proof.js +4 -4
  63. package/src/runs/foreground/execution.js +2 -2
  64. package/src/runs/foreground/subagent-executor.d.ts +2 -0
  65. package/src/runs/foreground/subagent-executor.js +10 -1
  66. package/src/runs/shared/herdr-machine.js +3 -1
  67. package/src/runs/shared/herdr-pane-host.js +10 -2
  68. package/src/runs/shared/mcp-config-sources.d.ts +1 -0
  69. package/src/runs/shared/mcp-config-sources.js +1 -1
  70. package/src/runs/shared/mcp-direct-tool-allowlist.js +1 -0
  71. package/src/runs/shared/subagent-prompt-runtime.js +6 -5
  72. package/src/shared/types.d.ts +2 -0
  73. package/src/shared/utils.d.ts +2 -0
  74. package/src/shared/utils.js +9 -0
  75. package/src/tui/fleet-transcript.js +21 -9
  76. package/src/watchdog/runtime.d.ts +4 -0
  77. package/src/watchdog/runtime.js +50 -12
  78. package/src/watchdog/turn-delta.d.ts +2 -0
  79. package/src/watchdog/turn-delta.js +21 -0
@@ -259,7 +259,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
259
259
  // Display name for the child session: applied inside the child through its
260
260
  // runtime config and echoed back on the result payload so hosts can label
261
261
  // this run without reading the child's session file.
262
- const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task });
262
+ const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task, label: options.label });
263
263
  const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
264
264
  const childWatchdog = watchdogConfig.ok
265
265
  ? resolveChildWatchdogConfig({
@@ -1695,7 +1695,7 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1695
1695
  ...options,
1696
1696
  capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), options.childRuntime?.capabilityCeiling),
1697
1697
  };
1698
- const childSessionName = deriveChildSessionName({ agent: agentName, task });
1698
+ const childSessionName = deriveChildSessionName({ agent: agentName, task, label: options.label });
1699
1699
  const agent = agents.find((a) => a.name === agentName);
1700
1700
  if (!agent) {
1701
1701
  const diagnosticContext = options.unknownAgentDiagnosticContext
@@ -78,6 +78,8 @@ export interface SubagentParamsLike {
78
78
  /** Internal workflow ownership metadata; not part of the public schema. */
79
79
  workflowParentRunId?: string;
80
80
  workflowKey?: string;
81
+ /** Workflow child's `runs.run` label, trimmed; names the child's own session instead of a task excerpt. */
82
+ label?: string;
81
83
  lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
82
84
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
83
85
  scheduleOrigin?: ScheduleOrigin;
@@ -3271,6 +3271,8 @@ async function runAsyncPath(data, deps) {
3271
3271
  runFanoutBudget: data.runFanoutBudget,
3272
3272
  parentWorkflowRunId: params.workflowParentRunId,
3273
3273
  workflowKey: params.workflowKey,
3274
+ // Top-level calls pass unknown keys through; only a workflow child's label is normalized.
3275
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3274
3276
  lane: params.lane,
3275
3277
  workflowAwaitAsync: params.workflowAwaitAsync,
3276
3278
  }));
@@ -3868,6 +3870,7 @@ async function runSinglePath(data, deps) {
3868
3870
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3869
3871
  cwd: singleCwd,
3870
3872
  requestedCwd: data.requestedCwd,
3873
+ label: params.workflowParentRunId !== undefined ? params.label : undefined,
3871
3874
  signal,
3872
3875
  abortedAsStopped: params.workflowParentRunId !== undefined,
3873
3876
  interruptSignal: interruptController.signal,
@@ -4651,6 +4654,12 @@ export function prepareWorkflowLaunchParams(workflowDefaults, childParams, paren
4651
4654
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4652
4655
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
4653
4656
  };
4657
+ // Scripts pass `label` unchecked; keep only a non-empty string so session naming can trust the field.
4658
+ const label = typeof childParams.label === "string" ? childParams.label.trim() : "";
4659
+ if (label)
4660
+ launchParams.label = label;
4661
+ else
4662
+ delete launchParams.label;
4654
4663
  if (launchParams.extensionBindings !== undefined)
4655
4664
  launchParams.extensionBindings = normalizeExtensionBindings(launchParams.extensionBindings).value;
4656
4665
  const normalizedGate = normalizeGateParams(launchParams);
@@ -7785,7 +7794,7 @@ export function createSubagentExecutor(deps) {
7785
7794
  if (workflowLaunchObserver) {
7786
7795
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
7787
7796
  const singleSessionName = hasSingle
7788
- ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task })
7797
+ ? deriveChildSessionName({ agent: effectiveParams.agent, task: effectiveParams.task, label: effectiveParams.label })
7789
7798
  : singleTask
7790
7799
  ? deriveChildSessionName({ agent: singleTask.agent, task: singleTask.task })
7791
7800
  : undefined;
@@ -251,7 +251,9 @@ export function resolveMachinePlacement(input) {
251
251
  return { machine: resolveHerdrLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, herdrBin: input.herdrBin }) };
252
252
  if (env.REX_SESSION?.trim())
253
253
  return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env }) };
254
- throw new Error("Machine 'local' opens the child in a new tab of the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID) nor Rex (REX_SESSION).");
254
+ // Herdr Core (`hc`, the Herdr app's terminal server) is a different product from the herdr multiplexer, with a different CLI and protocol.
255
+ const core = env.HC_TERMINAL_ID?.trim() ? " It runs in a Herdr Core terminal (HC_TERMINAL_ID), which machine 'local' does not support." : "";
256
+ throw new Error(`Machine 'local' opens the child in a new tab of the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID) nor Rex (REX_SESSION).${core}`);
255
257
  }
256
258
  if (settings?.rex)
257
259
  return { machine: { provider: "rex", id: requested, target: settings.rex.ssh, cwd: validateRemoteCwd(remoteMachineCwd(input.stepCwd, settings.cwd, requested), requested) } };
@@ -121,7 +121,7 @@ export const herdrPaneHost = {
121
121
  async launch(connection, machine, runId, runtimeDir, request, onPane, options) { const owned = await provisionHerdrOwnedPane(connection, asHerdrMachine(machine), runId, runtimeDir, request.environment); await onPane(owned); const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options); return { owned, terminalId }; },
122
122
  async prompt(connection, identity, text, options = {}) {
123
123
  // Herdr registers a started agent's name asynchronously, so a prompt right after start can be refused; a refused prompt was not delivered.
124
- const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 100;
124
+ const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 20_000), pollMs = options.pollMs ?? 100;
125
125
  for (;;) {
126
126
  try {
127
127
  await connection.client.call("agent.prompt", { target: identity.agentName, text });
@@ -130,7 +130,15 @@ export const herdrPaneHost = {
130
130
  catch (error) {
131
131
  if (!(error instanceof Error) || !error.message.includes("is not an active named agent") || clock.now() >= deadline)
132
132
  throw error;
133
- await clock.wait(Math.min(pollMs, deadline - clock.now()));
133
+ const remainingMs = deadline - clock.now();
134
+ // Over RPC, agent.start returns with launch_pending and Herdr refuses prompts until the agent is observed ready; agent.wait blocks until then.
135
+ // A failed wait (older Herdr, name not registered yet, wait timeout) falls back to polling; the refusal stays the error reported at the deadline.
136
+ try {
137
+ await connection.client.call("agent.wait", { target: identity.agentName, until: ["idle", "done"], timeout_ms: remainingMs }, remainingMs + 5_000);
138
+ }
139
+ catch { }
140
+ // agent.wait returns at once for an idle agent that Herdr still holds as launch-pending, so always pause before the next prompt.
141
+ await clock.wait(Math.min(pollMs, Math.max(0, deadline - clock.now())));
134
142
  if (options.stopped?.())
135
143
  throw new Error("Remote Pi prompt was not sent because the run was stopped.", { cause: error });
136
144
  }
@@ -28,6 +28,7 @@ export interface McpServerDefinition {
28
28
  pluginDataDir?: string;
29
29
  literalEnv?: boolean;
30
30
  inheritEnv?: boolean;
31
+ openUi?: boolean;
31
32
  /** Only literal true disables a server, matching pi-mcp-adapter. */
32
33
  disabled?: boolean;
33
34
  }
@@ -25,7 +25,7 @@ export function isMcpServerDefinition(value) {
25
25
  if (value[field] !== undefined && !isStringRecord(value[field]))
26
26
  return false;
27
27
  }
28
- for (const field of ["exposeResources", "literalEnv", "inheritEnv"]) {
28
+ for (const field of ["exposeResources", "literalEnv", "inheritEnv", "openUi"]) {
29
29
  if (value[field] !== undefined && typeof value[field] !== "boolean")
30
30
  return false;
31
31
  }
@@ -407,6 +407,7 @@ export function computeMcpServerHash(definition) {
407
407
  includeTools: definition.includeTools,
408
408
  excludeTools: definition.excludeTools,
409
409
  protocolVersion: definition.protocolVersion,
410
+ ...(definition.openUi === false ? { openUi: false } : {}),
410
411
  };
411
412
  return createHash("sha256").update(stableStringify(identity)).digest("hex");
412
413
  }
@@ -232,7 +232,7 @@ function rewritesChildPrompt(config) {
232
232
  /**
233
233
  * An extension can replace the tools a request declares (pi-fabric's code mode sends only its own
234
234
  * `fabric_exec`), and Pi only reports a throw from a request hook. This hook runs after every other
235
- * extension's, so a child whose registered allowlisted tools were left out records why and stops
235
+ * extension's, so a child whose active allowlisted tools were left out records why and stops
236
236
  * before the provider gets the request. A request that declares them all passes through unchanged.
237
237
  */
238
238
  function registerDeclaredToolCheck(pi, config, required) {
@@ -240,12 +240,13 @@ function registerDeclaredToolCheck(pi, config, required) {
240
240
  const declared = new Set(getCurrentTools(event.messages).map((tool) => tool.name));
241
241
  if (required.every((name) => declared.has(name)))
242
242
  return undefined;
243
- const registered = new Set(pi.getAllTools().map((tool) => tool.name));
244
- // A required tool that never registered is the agent_start diagnostic's case.
245
- const undeclared = required.filter((name) => registered.has(name) && !declared.has(name));
243
+ const active = new Set(pi.getActiveTools());
244
+ // Only an active tool must be declared: an extension may leave a registered tool inactive on
245
+ // purpose (pi-web-access's `web_enable`), and one that never registered is agent_start's case.
246
+ const undeclared = required.filter((name) => active.has(name) && !declared.has(name));
246
247
  if (undeclared.length === 0)
247
248
  return undefined;
248
- const active = new Set(pi.getActiveTools());
249
+ const registered = new Set(pi.getAllTools().map((tool) => tool.name));
249
250
  // A fork declares its parent's tools on purpose, to reuse the parent's prompt cache.
250
251
  const uncallable = config.forkCacheKey ? [] : [...declared].filter((name) => !active.has(name));
251
252
  config.toolDiagnostic?.({
@@ -2537,6 +2537,8 @@ export interface RunSyncOptions {
2537
2537
  remoteReads?: string[] | false;
2538
2538
  /** Original cwd input retained for launch diagnostics. */
2539
2539
  requestedCwd?: string;
2540
+ /** Workflow child label; names the child session instead of the task excerpt. */
2541
+ label?: string;
2540
2542
  signal?: AbortSignal;
2541
2543
  /** Report a child ended by `signal` as stopped; set for workflow children, whose signal is the workflow's. */
2542
2544
  abortedAsStopped?: boolean;
@@ -11,6 +11,8 @@ export declare function getProjectConfigDir(projectRoot: string): string;
11
11
  export declare function getAgentDir(): string;
12
12
  export declare function pruneStatusCacheForAsyncRoot(asyncDirRoot: string, runIds: Iterable<string>): number;
13
13
  export declare function resolveChildCwd(baseCwd: string, childCwd: string | undefined): string;
14
+ /** A `readStatus(asyncDir)` error caused by permissions on that run's own status file, which says nothing about whether its runner is alive. */
15
+ export declare function isStatusAccessError(error: unknown, asyncDir: string): boolean;
14
16
  export declare function readStatus(asyncDir: string): AsyncStatus | null;
15
17
  export declare function getLastActivity(outputFile: string | undefined): string;
16
18
  export declare function findLatestSessionFile(sessionDir: string): string | null;
@@ -119,6 +119,15 @@ function isNotFoundError(error) {
119
119
  && "code" in error
120
120
  && error.code === "ENOENT";
121
121
  }
122
+ /** A `readStatus(asyncDir)` error caused by permissions on that run's own status file, which says nothing about whether its runner is alive. */
123
+ export function isStatusAccessError(error, asyncDir) {
124
+ const code = error?.cause?.code;
125
+ if (code !== "EACCES" && code !== "EPERM")
126
+ return false;
127
+ const message = error instanceof Error ? error.message : "";
128
+ const quotedPath = `'${path.join(asyncDir, "status.json")}':`;
129
+ return message.startsWith(`Failed to inspect async status file ${quotedPath}`) || message.startsWith(`Failed to read async status file ${quotedPath}`);
130
+ }
122
131
  export function readStatus(asyncDir) {
123
132
  if (Buffer.byteLength(path.basename(asyncDir), "utf-8") > 255) {
124
133
  return null;
@@ -39,8 +39,17 @@ function renderExpandedTool(event, width, theme) {
39
39
  const output = event.output ?? event.error;
40
40
  const outputColor = event.status === "error" ? "error" : "toolOutput";
41
41
  if (event.name === "bash") {
42
- const command = jsonScalar(args?.command) ?? event.args ?? "(unknown command)";
43
- lines.push(railLine(`${glyph} ${theme.fg("toolTitle", theme.bold(`$ ${command}`))}`, width, theme));
42
+ const command = jsonScalar(args?.command);
43
+ let first = true;
44
+ for (const commandLine of (command ?? event.args ?? "(unknown command)").split(/\r?\n/)) {
45
+ for (const wrapped of renderWrapped(theme.fg("toolTitle", theme.bold(first ? `$ ${commandLine}` : commandLine)), Math.max(1, width - 4))) {
46
+ lines.push(railLine(`${first ? glyph : " "} ${wrapped}`, width, theme));
47
+ first = false;
48
+ }
49
+ }
50
+ // An unparseable payload was cut at the transcript size cap; show it raw so its truncation marker is visible.
51
+ if (command === undefined && !args && event.argsPayload)
52
+ lines.push(...renderArgsPayload(event.argsPayload, width, theme));
44
53
  if (output) {
45
54
  for (const outputLine of output.replace(/\s+$/, "").split(/\r?\n/)) {
46
55
  for (const wrapped of renderWrapped(theme.fg(outputColor, outputLine), Math.max(1, width - 4))) {
@@ -71,13 +80,8 @@ function renderExpandedTool(event, width, theme) {
71
80
  return lines;
72
81
  }
73
82
  lines.push(railLine(`${glyph} ${theme.fg("toolTitle", theme.bold(event.name))}`, width, theme));
74
- if (event.argsPayload) {
75
- lines.push(railLine(theme.fg("dim", " args"), width, theme));
76
- for (const argLine of event.argsPayload.split(/\r?\n/)) {
77
- for (const wrapped of renderWrapped(theme.fg("muted", argLine), Math.max(1, width - 4)))
78
- lines.push(railLine(` ${wrapped}`, width, theme));
79
- }
80
- }
83
+ if (event.argsPayload)
84
+ lines.push(...renderArgsPayload(event.argsPayload, width, theme));
81
85
  if (output) {
82
86
  lines.push(railLine(theme.fg(event.status === "error" ? "error" : "dim", event.status === "error" ? " error" : " output"), width, theme));
83
87
  for (const outputLine of output.split(/\r?\n/)) {
@@ -90,6 +94,14 @@ function renderExpandedTool(event, width, theme) {
90
94
  function bounded(text, width) {
91
95
  return truncateToWidth(text, Math.max(0, width));
92
96
  }
97
+ function renderArgsPayload(payload, width, theme) {
98
+ const lines = [railLine(theme.fg("dim", " args"), width, theme)];
99
+ for (const argLine of payload.split(/\r?\n/)) {
100
+ for (const wrapped of renderWrapped(theme.fg("muted", argLine), Math.max(1, width - 4)))
101
+ lines.push(railLine(` ${wrapped}`, width, theme));
102
+ }
103
+ return lines;
104
+ }
93
105
  function railLine(content, width, theme) {
94
106
  return bounded(`${theme.fg("borderMuted", "│")} ${content}`, width);
95
107
  }
@@ -92,6 +92,7 @@ export declare class MainWatchdogRuntime {
92
92
  private status;
93
93
  private pendingDeltas;
94
94
  private pendingDeltaChars;
95
+ private omittedDeltaChars;
95
96
  private guard;
96
97
  private guardMaxWarnings;
97
98
  private epoch;
@@ -130,6 +131,7 @@ export declare class MainWatchdogRuntime {
130
131
  private activityTail;
131
132
  private activityPending;
132
133
  private activityReviewUsed;
134
+ private supervisorReplies;
133
135
  constructor(options?: MainWatchdogRuntimeOptions);
134
136
  bindSession(ctx: ContextLike): void;
135
137
  refreshConfig(cwd?: string): WatchdogSettingsResult;
@@ -182,7 +184,9 @@ export declare class MainWatchdogRuntime {
182
184
  private collectLspDiagnostics;
183
185
  private lspSnapshot;
184
186
  private appendBoundedDelta;
187
+ private retainSupervisorReplies;
185
188
  private buildReviewInput;
189
+ private boundDeltaInput;
186
190
  private scopeBlock;
187
191
  private clearPendingDeltas;
188
192
  private clearActivity;
@@ -5,13 +5,15 @@ import { collectWatchdogLspDiagnostics, formatWatchdogLspDiagnosticsBlock, Watch
5
5
  import { ruleViolationWarning } from "./rules.js";
6
6
  import { WatchdogScopeArtifact } from "./scope.js";
7
7
  import { resolveWatchdogConfig } from "./settings.js";
8
- import { formatWatchdogOrchestrationActivity, formatWatchdogTurnDelta } from "./turn-delta.js";
8
+ import { formatWatchdogOrchestrationActivity, formatWatchdogSupervisorReplies, formatWatchdogTurnDelta } from "./turn-delta.js";
9
9
  import { WATCHDOG_WARNING_IMPORTANCES, } from "./types.js";
10
10
  import { normalizeWatchdogWarningDetails } from "./warning-format.js";
11
11
  const DEFAULT_REVIEW = () => ({ warnings: [] });
12
12
  const MAX_REVIEW_INPUT_CHARS = 24_000;
13
13
  const REVIEW_INPUT_HEAD_CHARS = 6_000;
14
14
  const REVIEW_DELTA_SEPARATOR = "\n\n---\n\n";
15
+ const MAX_SUPERVISOR_REPLY_CHARS = 3_000;
16
+ const MAX_SUPERVISOR_REPLIES_CHARS = 6_000;
15
17
  export function boundWatchdogReviewText(text, cap = MAX_REVIEW_INPUT_CHARS) {
16
18
  if (text.length <= cap)
17
19
  return text;
@@ -19,6 +21,13 @@ export function boundWatchdogReviewText(text, cap = MAX_REVIEW_INPUT_CHARS) {
19
21
  const marker = `\n\n[... about ${text.length - cap} characters omitted ...]\n\n`;
20
22
  return `${text.slice(0, head)}${marker}${text.slice(text.length - (cap - head - marker.length))}`;
21
23
  }
24
+ // The reviewer must not read missing text as proof that an instruction or authorization never happened.
25
+ function omittedDeltaNote(chars) {
26
+ return `[Parts of this run's turn delta omitted: about ${chars} characters are not shown, to fit the review input limit. Do not report an instruction, authorization, or action as absent unless the supplied evidence shows it; it may be in an omitted part.]`;
27
+ }
28
+ const OMITTED_NOTE_RESERVE = omittedDeltaNote(Number.MAX_SAFE_INTEGER).length + 2;
29
+ // Retained delta leaves room for the note, so a note never forces a second cut of the delta.
30
+ const MAX_RETAINED_DELTA_CHARS = MAX_REVIEW_INPUT_CHARS - OMITTED_NOTE_RESERVE;
22
31
  function errorMessage(error) {
23
32
  return error instanceof Error ? error.message : String(error);
24
33
  }
@@ -52,6 +61,7 @@ export class MainWatchdogRuntime {
52
61
  status = "idle";
53
62
  pendingDeltas = [];
54
63
  pendingDeltaChars = 0;
64
+ omittedDeltaChars = 0;
55
65
  guard = new WatchdogEmissionGuard();
56
66
  guardMaxWarnings = null;
57
67
  epoch = 0;
@@ -90,6 +100,7 @@ export class MainWatchdogRuntime {
90
100
  activityTail = "";
91
101
  activityPending = false;
92
102
  activityReviewUsed = false;
103
+ supervisorReplies = [];
93
104
  constructor(options = {}) {
94
105
  this.cwd = options.cwd ?? process.cwd();
95
106
  this.resolveConfig = options.resolveConfig ?? resolveWatchdogConfig;
@@ -201,8 +212,10 @@ export class MainWatchdogRuntime {
201
212
  this.lspLedger.reset();
202
213
  this.lastLspSnapshot = undefined;
203
214
  }
204
- if (options.clearScope)
215
+ if (options.clearScope) {
205
216
  this.scope.reset();
217
+ this.supervisorReplies = [];
218
+ }
206
219
  if (options.clearScope || options.clearActivity)
207
220
  this.clearActivity();
208
221
  if (options.clearReviewInputSignature)
@@ -229,6 +242,7 @@ export class MainWatchdogRuntime {
229
242
  this.lastLspSnapshot = undefined;
230
243
  this.lspLedger.reset();
231
244
  this.scope.reset();
245
+ this.supervisorReplies = [];
232
246
  this.observedRepoEditThisTurn = false;
233
247
  this.toolResultsThisRun = 0;
234
248
  this.midRunReviewing = false;
@@ -267,6 +281,7 @@ export class MainWatchdogRuntime {
267
281
  this.activityPending = true;
268
282
  }
269
283
  }
284
+ this.retainSupervisorReplies(event);
270
285
  this.observedRepoEditThisTurn ||= eventIndicatesRepoEdit(event);
271
286
  const delta = formatWatchdogTurnDelta({
272
287
  includeUserPrompt: this.includeUserPromptInNextDelta,
@@ -779,16 +794,28 @@ export class MainWatchdogRuntime {
779
794
  let entry = delta.trim();
780
795
  if (!entry)
781
796
  return;
782
- if (entry.length > MAX_REVIEW_INPUT_CHARS)
783
- entry = boundWatchdogReviewText(entry);
797
+ if (entry.length > MAX_RETAINED_DELTA_CHARS) {
798
+ this.omittedDeltaChars += entry.length - MAX_RETAINED_DELTA_CHARS;
799
+ entry = boundWatchdogReviewText(entry, MAX_RETAINED_DELTA_CHARS);
800
+ }
784
801
  this.pendingDeltas.push(entry);
785
802
  this.pendingDeltaChars += entry.length;
786
- while (this.pendingDeltas.length > 1 && this.pendingDeltaChars + (this.pendingDeltas.length - 1) * REVIEW_DELTA_SEPARATOR.length > MAX_REVIEW_INPUT_CHARS) {
803
+ while (this.pendingDeltas.length > 1 && this.pendingDeltaChars + (this.pendingDeltas.length - 1) * REVIEW_DELTA_SEPARATOR.length > MAX_RETAINED_DELTA_CHARS) {
787
804
  const removed = this.pendingDeltas.shift();
788
- if (removed)
805
+ if (removed) {
789
806
  this.pendingDeltaChars -= removed.length;
807
+ this.omittedDeltaChars += removed.length;
808
+ }
790
809
  }
791
810
  }
811
+ // Kept outside the rolling delta so a long run cannot push the supervisor's instruction out of the review input.
812
+ retainSupervisorReplies(event) {
813
+ for (const reply of formatWatchdogSupervisorReplies(event))
814
+ this.supervisorReplies.push(boundWatchdogReviewText(reply, MAX_SUPERVISOR_REPLY_CHARS));
815
+ let total = this.supervisorReplies.reduce((sum, reply) => sum + reply.length, 0);
816
+ while (this.supervisorReplies.length > 1 && total > MAX_SUPERVISOR_REPLIES_CHARS)
817
+ total -= this.supervisorReplies.shift().length;
818
+ }
792
819
  buildReviewInput(changeSignature, lspBlock = "") {
793
820
  const input = this.pendingDeltas.join(REVIEW_DELTA_SEPARATOR);
794
821
  const scopeBlock = this.scopeBlock();
@@ -796,25 +823,36 @@ export class MainWatchdogRuntime {
796
823
  ? ["Changed repo paths: every dirty path in the working tree. Authorship is not verified; a path may predate this session or come from another session.", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join("\n")
797
824
  : "";
798
825
  const activity = this.activityTail ? `Recent delivered orchestration activity (oldest first; bounded observations, not a task board; waits/holds are not evidence of neglect):\n${this.activityTail}` : "";
826
+ const supervisor = this.configResult.config.scope.enabled && this.supervisorReplies.length
827
+ ? `Supervisor replies this agent received through contact_supervisor (oldest first; the orchestrator's answers to this agent's questions, which can authorize or redirect its work):\n${this.supervisorReplies.join(REVIEW_DELTA_SEPARATOR)}`
828
+ : "";
799
829
  const contextPieces = [scopeBlock, changes, lspBlock, activity].filter(Boolean);
800
- if (!contextPieces.length)
801
- return boundWatchdogReviewText(input);
830
+ if (!contextPieces.length && !supervisor)
831
+ return this.boundDeltaInput(input, MAX_REVIEW_INPUT_CHARS);
802
832
  const maxContextLength = Math.floor(MAX_REVIEW_INPUT_CHARS / 2);
803
833
  const maxPieceLength = Math.max(1_000, Math.floor(maxContextLength / contextPieces.length));
804
- const boundedContext = contextPieces.map((piece) => piece.length > maxPieceLength
805
- ? piece === activity ? boundWatchdogReviewText(piece, maxPieceLength) : `${piece.slice(0, maxPieceLength - 6)}\n- ...`
806
- : piece).join(REVIEW_DELTA_SEPARATOR);
834
+ // Supervisor replies are already bounded to whole entries at retention; a second head+tail cut would drop whole replies.
835
+ const boundedContext = [...contextPieces.map((piece) => piece.length > maxPieceLength
836
+ ? piece === activity ? boundWatchdogReviewText(piece, maxPieceLength) : `${piece.slice(0, maxPieceLength - 6)}\n- ...`
837
+ : piece), supervisor].filter(Boolean).join(REVIEW_DELTA_SEPARATOR);
807
838
  const separatorLength = input ? REVIEW_DELTA_SEPARATOR.length : 0;
808
839
  const inputBudget = MAX_REVIEW_INPUT_CHARS - boundedContext.length - separatorLength;
809
- const boundedInput = inputBudget <= 0 ? "" : boundWatchdogReviewText(input, inputBudget);
840
+ const boundedInput = inputBudget <= 0 ? "" : this.boundDeltaInput(input, inputBudget);
810
841
  return [boundedContext, boundedInput].filter(Boolean).join(REVIEW_DELTA_SEPARATOR);
811
842
  }
843
+ boundDeltaInput(input, cap) {
844
+ if (!input || (this.omittedDeltaChars === 0 && input.length <= cap))
845
+ return input;
846
+ const bodyCap = cap - OMITTED_NOTE_RESERVE;
847
+ return `${omittedDeltaNote(this.omittedDeltaChars + Math.max(0, input.length - bodyCap))}\n\n${boundWatchdogReviewText(input, bodyCap)}`;
848
+ }
812
849
  scopeBlock() {
813
850
  return this.configResult.config.scope.enabled ? this.scope.render() : "";
814
851
  }
815
852
  clearPendingDeltas() {
816
853
  this.pendingDeltas = [];
817
854
  this.pendingDeltaChars = 0;
855
+ this.omittedDeltaChars = 0;
818
856
  }
819
857
  clearActivity() {
820
858
  if (!this.activityTail)
@@ -13,3 +13,5 @@ export declare function formatWatchdogReviewMessage(message: unknown, options?:
13
13
  export declare function formatWatchdogTurnDelta(input: WatchdogTurnDeltaInput): string;
14
14
  /** Only completed, exactly paired native orchestration calls are activity evidence. */
15
15
  export declare function formatWatchdogOrchestrationActivity(event: unknown): string;
16
+ /** A supervisor reply arrives as a tool result, never as a user prompt, so scope alone never records it. */
17
+ export declare function formatWatchdogSupervisorReplies(event: unknown): string[];
@@ -187,3 +187,24 @@ export function formatWatchdogOrchestrationActivity(event) {
187
187
  }
188
188
  return sections.join("\n\n");
189
189
  }
190
+ /** A supervisor reply arrives as a tool result, never as a user prompt, so scope alone never records it. */
191
+ export function formatWatchdogSupervisorReplies(event) {
192
+ const turn = event;
193
+ if (turn?.type !== "turn_end" || !Array.isArray(turn.message?.content) || !Array.isArray(turn.toolResults))
194
+ return [];
195
+ const entries = [];
196
+ for (const call of turn.message.content) {
197
+ if (call?.type !== "toolCall" || call.name !== "contact_supervisor" || typeof call.id !== "string")
198
+ continue;
199
+ const args = call.arguments;
200
+ if (!args || typeof args !== "object" || !["need_decision", "interview_request"].includes(args.reason))
201
+ continue;
202
+ const result = turn.toolResults.find((value) => {
203
+ const result = value;
204
+ return result?.role === "toolResult" && result.toolCallId === call.id && result.toolName === call.name && result.isError !== true && !result.error;
205
+ });
206
+ if (result)
207
+ entries.push([formatToolCall(call.name, args), formatWatchdogReviewMessage(result) ?? ""].join("\n\n"));
208
+ }
209
+ return entries;
210
+ }