@xzzpig/pi-subagents 0.15.1 → 0.18.0

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 (135) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
package/src/tui/render.ts CHANGED
@@ -83,23 +83,24 @@ function capCompactMainWindowResult(component: Component, layout: MainWindowRend
83
83
  if (lines.length <= maxLines) return lines;
84
84
  const visibleRows = maxLines === 1 ? 1 : maxLines - 1;
85
85
  const hiddenCount = lines.length - visibleRows;
86
- const hint = theme.fg("accent", `… ${hiddenCount} rows hidden · ${liveDetailKeyText()} expands`);
86
+ const hint = theme.fg("accent", `… ${hiddenCount} rows hidden · ${expandKeyHint("to expand", "to view them")}`);
87
87
  if (maxLines === 1) return [truncLine(`${lines[0] ?? ""} ${hint}`, width)];
88
88
  return [...lines.slice(0, visibleRows), truncLine(hint, width)];
89
89
  };
90
90
  return capped;
91
91
  }
92
92
 
93
- function liveDetailKeyText(): string {
94
- return keyText("app.tools.expand");
93
+ function expandKeyHint(action: string, unconfiguredAction = action): string {
94
+ const shortcut = keyText("app.tools.expand");
95
+ return shortcut ? `Press ${shortcut} ${action}` : `Configure the expand key ${unconfiguredAction}`;
95
96
  }
96
97
 
97
98
  export function liveDetailHintText(): string {
98
- return `Press ${liveDetailKeyText()} for live detail`;
99
+ return expandKeyHint("for live detail");
99
100
  }
100
101
 
101
102
  function workflowDetailHintText(): string {
102
- return `Press ${liveDetailKeyText()} for details`;
103
+ return expandKeyHint("for details");
103
104
  }
104
105
 
105
106
  function foregroundSingleHintText(shortcut?: string): string {
@@ -2111,8 +2112,12 @@ function widgetStats(job: AsyncJobState, theme: Theme, projection = buildWorkflo
2111
2112
  return statJoin(theme, parts);
2112
2113
  }
2113
2114
 
2114
- function widgetStepStats(theme: Theme, step: NonNullable<AsyncJobState["steps"]>[number]): string {
2115
+ function widgetStepStats(theme: Theme, step: NonNullable<AsyncJobState["steps"]>[number], snapshotNow = Date.now()): string {
2116
+ const externalElapsed = step.runner?.type === "external-cli" && step.externalProcess
2117
+ ? step.externalProcess.durationMs ?? Math.max(0, (step.externalProcess.endedAt ?? snapshotNow) - step.externalProcess.startedAt)
2118
+ : undefined;
2115
2119
  return statJoin(theme, [
2120
+ step.runner?.type === "external-cli" ? "external-cli" : "",
2116
2121
  step.turnCount !== undefined ? `${step.turnCount} turns` : "",
2117
2122
  step.toolCount !== undefined ? formatToolUseStat(step.toolCount) : "",
2118
2123
  step.tokens
@@ -2120,7 +2125,7 @@ function widgetStepStats(theme: Theme, step: NonNullable<AsyncJobState["steps"]>
2120
2125
  ? formatContextUsage(step.tokens, step.contextLimit) ?? formatTokenUsage(step.tokens, "token")
2121
2126
  : step.tokens.total ? formatTokenUsage(step.tokens, "token") : ""
2122
2127
  : "",
2123
- step.durationMs !== undefined ? formatDuration(step.durationMs) : "",
2128
+ externalElapsed !== undefined ? formatDuration(externalElapsed) : step.durationMs !== undefined ? formatDuration(step.durationMs) : "",
2124
2129
  ]);
2125
2130
  }
2126
2131
 
@@ -2314,7 +2319,7 @@ function foregroundStyleWidgetStepLines(
2314
2319
  const rowIndent = options?.rowIndent ?? " ";
2315
2320
  const detailIndent = options?.detailIndent ?? " ";
2316
2321
  const status = widgetStepStatus(step.status, theme);
2317
- const stats = widgetStepStats(theme, step);
2322
+ const stats = widgetStepStats(theme, step, job.updatedAt);
2318
2323
  const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
2319
2324
  const collapseDetails = shouldCollapseSingleChildDetails(job, step);
2320
2325
  const displayName = collapseDetails ? singleChildAgentName(job, step) : childDisplayName(step);
@@ -2470,7 +2475,7 @@ function compactSingleWidgetLines(job: AsyncJobState, theme: Theme, width: numbe
2470
2475
  const step = row.step;
2471
2476
  const status = widgetStepStatus(step.status, theme);
2472
2477
  const activity = widgetStepActivityLine(step, width, false, job.updatedAt);
2473
- const stepStats = widgetStepStats(theme, step);
2478
+ const stepStats = widgetStepStats(theme, step, job.updatedAt);
2474
2479
  const activitySuffix = activity ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", activity)}` : "";
2475
2480
  const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
2476
2481
  const task = compactTaskText(step.description, step.label);
@@ -2703,7 +2708,7 @@ function fitWidgetLineBudget(lines: string[], theme: Theme, width: number, expan
2703
2708
  const hiddenCount = lines.length - visibleLines;
2704
2709
  const hint = expanded
2705
2710
  ? `… ${hiddenCount} live-detail lines hidden`
2706
- : `… ${hiddenCount} lines hidden · ${liveDetailKeyText()} expands`;
2711
+ : `… ${hiddenCount} lines hidden · ${expandKeyHint("to expand", "to view them")}`;
2707
2712
  return [...lines.slice(0, visibleLines), truncLine(theme.fg("dim", hint), width)];
2708
2713
  }
2709
2714
 
@@ -2753,13 +2758,38 @@ const asyncWidgetUpdates = new WeakMap<ExtensionContext["ui"], (jobs: AsyncJobSt
2753
2758
  const inlineWorkflowCoverage = new WeakMap<ExtensionContext["ui"], ReadonlyMap<string, string>>();
2754
2759
  const asyncWidgetInvalidations = new WeakMap<ExtensionContext["ui"], () => void>();
2755
2760
 
2756
- /** Include child identity and freshness in the roster's existing snapshot. */
2761
+ function inlineWorkflowDescendantShape(children: AsyncJobState["nestedChildren"]): unknown {
2762
+ return children?.map((child) => [child.id, child.agent, inlineWorkflowDescendantShape(child.children)]);
2763
+ }
2764
+
2765
+ function inlineWorkflowRowShape(job: AsyncJobState): unknown[] {
2766
+ return [
2767
+ job.asyncId,
2768
+ job.parentWorkflowRunId,
2769
+ job.workflowKey,
2770
+ job.mode,
2771
+ job.currentStep,
2772
+ job.activeParallelGroup,
2773
+ job.status,
2774
+ job.context,
2775
+ job.agents,
2776
+ job.steps?.map((step, index) => [
2777
+ step.index ?? index,
2778
+ step.workflowKey,
2779
+ step.agent,
2780
+ step.status,
2781
+ Boolean(step.runner),
2782
+ inlineWorkflowDescendantShape(step.children),
2783
+ ]),
2784
+ inlineWorkflowDescendantShape(job.nestedChildren),
2785
+ job.hostSteps?.map((row) => [row.id, row.monitorKind, row.label]),
2786
+ Boolean(job.workflowGraph),
2787
+ ];
2788
+ }
2789
+
2790
+ /** Structural identity of the workflow rows that Fleet can cover. */
2757
2791
  export function inlineWorkflowRenderKey(job: AsyncJobState, children: AsyncJobState[]): string {
2758
- if (!children.length) return widgetRenderKey(job);
2759
- return JSON.stringify([widgetRenderKey(job), children.map((child) => [
2760
- child.asyncId, widgetRenderKey(child, true), child.context,
2761
- child.steps?.map((step) => [Boolean(step.runner), step.tokens?.window]), Boolean(child.workflowGraph),
2762
- ])]);
2792
+ return JSON.stringify([inlineWorkflowRowShape(job), children.map(inlineWorkflowRowShape)]);
2763
2793
  }
2764
2794
 
2765
2795
  /** Presentation-only coverage from the mounted inline Fleet roster, never configuration. */
@@ -2827,7 +2857,11 @@ function buildWidgetComponent(jobs: AsyncJobState[], ui: ExtensionContext["ui"])
2827
2857
  resetWidgetLayoutSession();
2828
2858
  tui.requestRender();
2829
2859
  };
2830
- asyncWidgetInvalidations.set(ui, invalidate);
2860
+ const invalidateCoverage = (): void => {
2861
+ cachedLines = undefined;
2862
+ tui.requestRender();
2863
+ };
2864
+ asyncWidgetInvalidations.set(ui, invalidateCoverage);
2831
2865
  const update = (nextJobs: AsyncJobState[]): void => {
2832
2866
  jobs = nextJobs;
2833
2867
  cachedLines = undefined;
@@ -2845,7 +2879,7 @@ function buildWidgetComponent(jobs: AsyncJobState[], ui: ExtensionContext["ui"])
2845
2879
  },
2846
2880
  dispose(): void {
2847
2881
  if (asyncWidgetUpdates.get(ui) === update) asyncWidgetUpdates.delete(ui);
2848
- if (asyncWidgetInvalidations.get(ui) === invalidate) asyncWidgetInvalidations.delete(ui);
2882
+ if (asyncWidgetInvalidations.get(ui) === invalidateCoverage) asyncWidgetInvalidations.delete(ui);
2849
2883
  },
2850
2884
  });
2851
2885
  container.render = (renderWidth: number): string[] => {
@@ -3387,7 +3421,7 @@ export function renderSubagentResult(
3387
3421
  const c = new Container();
3388
3422
  const detailIndent = mainWindowIndent(layout, 1);
3389
3423
  c.addChild(new Text(truncLine(`${contextPrefix}${compactLine} · ${lines.length} lines`, width), 0, 0));
3390
- c.addChild(new Text(truncLine(theme.fg("accent", `${detailIndent}Press ${liveDetailKeyText()} for full output`), width), 0, 0));
3424
+ c.addChild(new Text(truncLine(theme.fg("accent", `${detailIndent}${expandKeyHint("for full output")}`), width), 0, 0));
3391
3425
  return compact(c);
3392
3426
  }
3393
3427
  const c = new Container();
@@ -5,6 +5,7 @@ import { Type, type Static } from "typebox";
5
5
 
6
6
  export const WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
7
7
  export const WATCHDOG_DIFF_MAX_CHARS = 24_000;
8
+ export const WATCHDOG_DIFF_UNAVAILABLE_BASELINE = "watchdog_diff unavailable: this cwd has no valid Git HEAD baseline. No diff can be shown; inspect files with independent read-only tools instead.";
8
9
  const MAX_UNTRACKED_FILES = 50;
9
10
 
10
11
  export interface WatchdogDiffBaseline {
@@ -51,18 +52,36 @@ function bound(text: string): string {
51
52
  }
52
53
 
53
54
  /** In a shared cwd, changes already pending when the session started also appear. */
54
- export function createWatchdogDiffTool(baseline: WatchdogDiffBaseline): AgentTool<typeof WatchdogDiffParams, { chars: number }> {
55
+ export function createWatchdogDiffTool(
56
+ baseline: WatchdogDiffBaseline | undefined,
57
+ options: { workingTreeAtLaunch?: boolean } = {},
58
+ ): AgentTool<typeof WatchdogDiffParams, { chars: number }> {
59
+ const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
55
60
  return {
56
61
  name: WATCHDOG_DIFF_TOOL_NAME,
57
62
  label: "Watchdog diff",
58
- description: "Show the repository diff since the review baseline, plus untracked file paths. Optional path narrows it; stat:true returns per-file counts only.",
63
+ description: !baseline
64
+ ? "Report that a Git HEAD diff baseline is unavailable in this cwd. No diff is generated."
65
+ : workingTreeAtLaunch
66
+ ? "Show the current staged and unstaged working-tree delta against reviewer-launch HEAD, plus untracked file paths. Committed ranges are not included. Optional path narrows it; stat:true returns per-file counts only."
67
+ : "Show the repository diff since the review baseline, plus untracked file paths. Optional path narrows it; stat:true returns per-file counts only.",
59
68
  parameters: WatchdogDiffParams,
60
69
  executionMode: "sequential",
61
70
  async execute(_toolCallId, params: WatchdogDiffParams) {
71
+ if (!baseline) {
72
+ return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
73
+ }
62
74
  const pathFilter = validatePath(params.path);
63
75
  const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...(params.stat === true ? ["--stat"] : []), baseline.ref, "--", ...(pathFilter ? [pathFilter] : [])]);
64
76
  if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
65
77
  const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...(pathFilter ? [pathFilter] : [])]);
78
+ if (workingTreeAtLaunch) {
79
+ const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
80
+ if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
81
+ const text = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
82
+ return { content: [{ type: "text", text }], details: { chars: text.length } };
83
+ }
84
+ }
66
85
  const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
67
86
  const sections = [diff.stdout.trimEnd()];
68
87
  if (untracked.length) {
@@ -70,7 +89,9 @@ export function createWatchdogDiffTool(baseline: WatchdogDiffBaseline): AgentToo
70
89
  sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
71
90
  if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
72
91
  }
73
- const text = bound(sections.filter(Boolean).join("\n\n")) || `No changes since baseline ${baseline.ref.slice(0, 12)}.`;
92
+ const text = bound(sections.filter(Boolean).join("\n\n")) || (workingTreeAtLaunch
93
+ ? `No working-tree changes against reviewer-launch HEAD ${baseline.ref.slice(0, 12)}. Committed changes are not included.`
94
+ : `No changes since baseline ${baseline.ref.slice(0, 12)}.`);
74
95
  return { content: [{ type: "text", text }], details: { chars: text.length } };
75
96
  },
76
97
  };
@@ -1,13 +1,12 @@
1
1
  import { Agent, type AgentTool, type StreamFn } from "@earendil-works/pi-agent-core";
2
2
  import { convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { streamSimple } from "@earendil-works/pi-ai/compat";
4
3
  import { Type, type Static } from "typebox";
5
4
  import { appendPermissionAudit, permissionArgsPreview } from "../runs/shared/permissions.ts";
6
5
  import { agentStreamOptions } from "../shared/agent-stream-options.ts";
7
6
  import { opencodeSessionHeaders } from "../shared/opencode-session-headers.ts";
8
7
  import { decodeChildWatchdogConfig } from "./child-status.ts";
9
8
  import { childResolvedConfig } from "./register-child.ts";
10
- import { resolveWatchdogReviewModel } from "./review.ts";
9
+ import { formatWatchdogCwdSection, resolveWatchdogReviewModel } from "./review.ts";
11
10
 
12
11
  const PermissionDecisionParams = Type.Object({
13
12
  decision: Type.String({ enum: ["approve", "deny"] }),
@@ -96,29 +95,28 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
96
95
  const selection = await resolveWatchdogReviewModel(request.ctx, config);
97
96
  const auth = selection.auth;
98
97
  const sessionId = request.ctx.sessionManager.getSessionId();
99
- const registeredProvider = (request.ctx.modelRegistry as {
100
- getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
101
- }).getRegisteredProviderConfig?.(selection.model.provider);
102
- const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
103
- ? registeredProvider.streamSimple
104
- : streamSimple);
98
+ const baseStreamFn: StreamFn = (options.streamFn ?? ((model, context, streamOptions) => request.ctx.modelRegistry.streamSimple(model, context, streamOptions))) as StreamFn;
105
99
  const streamFn: StreamFn = (model, context, streamOptions) => baseStreamFn(model, context, {
106
100
  ...streamOptions,
107
101
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
108
102
  env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
109
103
  headers: { ...opencodeSessionHeaders(model, sessionId), ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
110
104
  });
105
+ const systemPrompt = [
106
+ "You are the pi-subagents watchdog permission arbiter.",
107
+ "Decide only whether this exact non-bash child tool call should proceed.",
108
+ "Call watchdog_permission_decision exactly once with approve or deny and a concise reason.",
109
+ "Deny when uncertain. Do not produce freeform advice or ask the parent orchestrator.",
110
+ "",
111
+ formatWatchdogCwdSection(request.ctx.cwd),
112
+ ].join("\n");
113
+ const tools = [tool];
111
114
  agent = new Agent({
112
115
  initialState: {
113
- systemPrompt: [
114
- "You are the pi-subagents watchdog permission arbiter.",
115
- "Decide only whether this exact non-bash child tool call should proceed.",
116
- "Call watchdog_permission_decision exactly once with approve or deny and a concise reason.",
117
- "Deny when uncertain. Do not produce freeform advice or ask the parent orchestrator.",
118
- ].join("\n"),
116
+ systemPrompt,
119
117
  model: selection.model,
120
118
  thinkingLevel: selection.thinkingLevel,
121
- tools: [tool],
119
+ tools,
122
120
  },
123
121
  convertToLlm,
124
122
  ...agentStreamOptions(streamFn),
@@ -52,11 +52,13 @@ export function registerChildWatchdog(
52
52
  pi: ExtensionAPI,
53
53
  childConfig: ChildWatchdogConfig | undefined,
54
54
  writeStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined,
55
+ structuredTerminal?: { captured: boolean },
55
56
  ): MainWatchdogRuntime | undefined {
56
57
  if (!childConfig) return undefined;
57
58
  if (!writeStatus) throw new Error("Child watchdog status sink is missing; the host must pass ChildRuntimeConfig.watchdogStatus.");
58
59
  let currentContext: ExtensionContext | undefined;
59
60
  let diffBaseline: WatchdogDiffBaseline | undefined;
61
+ let agentSettled = false;
60
62
  let seq = 0;
61
63
  const emitStatus = (phase: ChildWatchdogPhase, reason?: string, warning?: ChildWatchdogWarningSummary): void => {
62
64
  writeStatus({
@@ -80,7 +82,9 @@ export function registerChildWatchdog(
80
82
  displayWarning: (details, options) => {
81
83
  const childDetails = childWarningDetails(details, childConfig);
82
84
  emitStatus("reviewing", undefined, { severity: childDetails.severity, importance: childDetails.importance, category: childDetails.category, summary: childDetails.summary, evidence: childDetails.evidence, recommendedAction: childDetails.recommendedAction, ...(childDetails.displayedAt ? { displayedAt: childDetails.displayedAt } : {}), addressed: false, stalemate: childDetails.state === "stalemate" });
83
- pi.sendMessage(createWatchdogWarningMessage(childDetails, { display: true, details: childDetails }), options);
85
+ const message = createWatchdogWarningMessage(childDetails, { display: true, details: childDetails });
86
+ if (agentSettled) pi.appendEntry(SUBAGENT_WATCHDOG_WARNING_TYPE, childDetails);
87
+ else pi.sendMessage(message, options);
84
88
  },
85
89
  displayUserWarning: (details) => {
86
90
  const childDetails = childWarningDetails(details, childConfig);
@@ -99,12 +103,13 @@ export function registerChildWatchdog(
99
103
  emitStatus("idle");
100
104
  });
101
105
  onRuntimeEvent("before_agent_start", (event, ctx) => {
106
+ agentSettled = false;
102
107
  rememberContext(ctx);
103
108
  runtime.handleBeforeAgentStart(event, ctx);
104
109
  });
105
110
  onRuntimeEvent("turn_end", (event, ctx) => {
106
111
  rememberContext(ctx);
107
- runtime.handleTurnEnd(event, ctx);
112
+ runtime.handleTurnEnd(event, ctx, structuredTerminal?.captured === true);
108
113
  });
109
114
  onRuntimeEvent("tool_result", (_event, ctx) => {
110
115
  rememberContext(ctx);
@@ -119,6 +124,9 @@ export function registerChildWatchdog(
119
124
  else if (snapshot.status === "stale") emitStatus("stale", "review stale");
120
125
  else emitStatus("idle");
121
126
  });
127
+ onRuntimeEvent("agent_settled", () => {
128
+ agentSettled = true;
129
+ });
122
130
  onRuntimeEvent("session_shutdown", () => {
123
131
  currentContext = undefined;
124
132
  runtime.dispose();
@@ -1,6 +1,5 @@
1
1
  import { Agent, type AgentTool, type StreamFn, type ThinkingLevel } from "@earendil-works/pi-agent-core";
2
2
  import { createReadOnlyTools, convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { streamSimple } from "@earendil-works/pi-ai/compat";
4
3
  import type { Model, ProviderHeaders } from "@earendil-works/pi-ai";
5
4
  import { Type, type Static } from "typebox";
6
5
  import { resolveModelCandidate } from "../runs/shared/model-resolution.ts";
@@ -218,11 +217,15 @@ function createWatchdogWarnTool(request: WatchdogReviewRequest): AgentTool<typeo
218
217
  };
219
218
  }
220
219
 
220
+ export function formatWatchdogCwdSection(cwd: string): string {
221
+ if (/[\p{Cc}\p{Zl}\p{Zp}<>]/u.test(cwd)) throw new Error("Watchdog cwd cannot contain control, line-separator, or angle-bracket characters.");
222
+ return `<cwd>\n${cwd}\n</cwd>`;
223
+ }
224
+
221
225
  export function buildWatchdogSystemPrompt(ctx: Pick<ExtensionContext, "cwd">, options: { hasScope?: boolean; guidance?: string; hasDiff?: boolean } = {}): string {
222
226
  const guidance = options.guidance?.trim();
223
227
  return [
224
228
  "You are the main-session subagent watchdog for Pi.",
225
- `Working directory: ${ctx.cwd}`,
226
229
  "Review only the supplied parent turn delta. Inspect repository files only when needed to verify a concrete concern.",
227
230
  options.hasScope ? "Use the Current scope record alongside supplied activity evidence; an unrelated user question does not cancel older authorized work." : undefined,
228
231
  `You are read-only. You may use ${options.hasDiff ? "read, grep, find, ls, and watchdog_diff (the full repo diff since the session baseline; pass a path to narrow it)" : "read, grep, find, and ls"}. Do not edit files, run shell commands, spawn agents, or mutate state.`,
@@ -232,6 +235,7 @@ export function buildWatchdogSystemPrompt(ctx: Pick<ExtensionContext, "cwd">, op
232
235
  "If the turn is clean, call no tools and end normally.",
233
236
  "Use severity='blocker' only when the issue should stop acceptance until addressed; otherwise use severity='concern'.",
234
237
  guidance ? `\nStanding instructions from WATCHDOG.md (project first, then user):\n${guidance}` : undefined,
238
+ `\n${formatWatchdogCwdSection(ctx.cwd)}`,
235
239
  ].filter((line): line is string => Boolean(line)).join("\n");
236
240
  }
237
241
 
@@ -273,18 +277,13 @@ async function runWatchdogAttempt(ctx: ExtensionContext, request: WatchdogReview
273
277
  });
274
278
  if (ctx.signal?.aborted || request.signal?.aborted) return { result: { stopReason: "aborted" } };
275
279
  const auth = selection.auth;
276
- const registeredProvider = (ctx.modelRegistry as {
277
- getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
278
- }).getRegisteredProviderConfig?.(selection.model.provider);
279
- const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
280
- ? registeredProvider.streamSimple
281
- : streamSimple);
280
+ const baseStreamFn: StreamFn = (options.streamFn ?? ((model, context, streamOptions) => ctx.modelRegistry.streamSimple(model, context, streamOptions))) as StreamFn;
282
281
  const sessionId = ctx.sessionManager.getSessionId();
283
282
  const streamFn: StreamFn = (model, context, streamOptions) => {
284
283
  // Agent may enter one final loop iteration after an aborted mixed tool batch.
285
284
  // Never send that iteration to the provider after an intentional yield.
286
285
  if (clarification) throw new Error("Watchdog review yielded for clarification.");
287
- return baseStreamFn(model, context, {
286
+ return (baseStreamFn as StreamFn)(model, context, {
288
287
  ...streamOptions,
289
288
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
290
289
  env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
@@ -321,13 +320,14 @@ async function runWatchdogAttempt(ctx: ExtensionContext, request: WatchdogReview
321
320
  return { content: [{ type: "text", text: "Review yielded for clarification." }], details: {} };
322
321
  },
323
322
  });
323
+ const systemPrompt = buildWatchdogSystemPrompt(ctx, {
324
+ hasScope: request.hasScope,
325
+ guidance: loadWatchdogGuidance(ctx.cwd, request.config.guidance.watchdogMd),
326
+ hasDiff: diffBaseline !== undefined,
327
+ });
324
328
  const agent = new Agent({
325
329
  initialState: {
326
- systemPrompt: buildWatchdogSystemPrompt(ctx, {
327
- hasScope: request.hasScope,
328
- guidance: loadWatchdogGuidance(ctx.cwd, request.config.guidance.watchdogMd),
329
- hasDiff: diffBaseline !== undefined,
330
- }),
330
+ systemPrompt,
331
331
  model: selection.model,
332
332
  thinkingLevel: selection.thinkingLevel,
333
333
  tools,
@@ -345,7 +345,7 @@ export class MainWatchdogRuntime {
345
345
  this.resetRepoChangeBaseline();
346
346
  }
347
347
 
348
- handleTurnEnd(event: unknown, ctx: ContextLike): void {
348
+ handleTurnEnd(event: unknown, ctx: ContextLike, structuredTerminal = false): void {
349
349
  if (this.disposed) return;
350
350
  this.refreshConfig(ctx.cwd);
351
351
  if (!this.isEnabled()) return;
@@ -362,6 +362,7 @@ export class MainWatchdogRuntime {
362
362
  includeUserPrompt: this.includeUserPromptInNextDelta,
363
363
  userPrompt: this.userPrompt,
364
364
  events: [event],
365
+ structuredTerminal,
365
366
  });
366
367
  this.includeUserPromptInNextDelta = false;
367
368
  this.enqueueDelta(delta);
@@ -21,6 +21,8 @@ export interface WatchdogTurnDeltaInput {
21
21
  messages?: unknown[];
22
22
  events?: unknown[];
23
23
  finalAssistantStop?: boolean;
24
+ /** A validated structured output is the authoritative terminal response. */
25
+ structuredTerminal?: boolean;
24
26
  }
25
27
 
26
28
  function textFromContent(content: unknown): string {
@@ -122,13 +124,15 @@ function messagesFromEvent(event: unknown): unknown[] {
122
124
  return [];
123
125
  }
124
126
 
125
- export function formatWatchdogReviewMessage(message: unknown): string | undefined {
127
+ export function formatWatchdogReviewMessage(message: unknown, options: { structuredTerminal?: boolean } = {}): string | undefined {
126
128
  if (!message || typeof message !== "object") return undefined;
127
129
  const input = message as MessageLike;
128
130
  if (input.role === "custom" && input.customType === SUBAGENT_WATCHDOG_WARNING_TYPE) return undefined;
129
131
  if (input.role === "assistant") {
130
132
  const text = textFromContent(input.content);
131
- const lines = text ? ["Assistant:", text] : ["Assistant: (no text)"];
133
+ const lines = text
134
+ ? ["Assistant:", text]
135
+ : [options.structuredTerminal ? "Assistant: (validated structured output is the terminal response; no prose is required)" : "Assistant: (no text)"];
132
136
  if (input.stopReason === "stop") lines.push("Assistant stop: stop");
133
137
  return lines.join("\n");
134
138
  }
@@ -147,16 +151,18 @@ export function formatWatchdogTurnDelta(input: WatchdogTurnDeltaInput): string {
147
151
  const sections: string[] = [];
148
152
  if (input.includeUserPrompt && input.userPrompt?.trim()) sections.push(["User prompt:", input.userPrompt].join("\n"));
149
153
  for (const message of input.messages ?? []) {
150
- const section = formatWatchdogReviewMessage(message);
154
+ const section = formatWatchdogReviewMessage(message, { structuredTerminal: input.structuredTerminal });
151
155
  if (section) sections.push(section);
152
156
  }
153
157
  for (const event of input.events ?? []) {
154
158
  for (const message of messagesFromEvent(event)) {
155
- const section = formatWatchdogReviewMessage(message);
159
+ const section = formatWatchdogReviewMessage(message, { structuredTerminal: input.structuredTerminal });
156
160
  if (section) sections.push(section);
157
161
  }
158
162
  }
159
- if (input.finalAssistantStop) sections.push("Final assistant stop: stop without tool call");
163
+ if (input.finalAssistantStop) sections.push(input.structuredTerminal
164
+ ? "Final assistant stop: validated structured output completed the response"
165
+ : "Final assistant stop: stop without tool call");
160
166
  return sections.join("\n\n---\n\n");
161
167
  }
162
168