@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -1,10 +1,11 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { execFile, spawnSync } from "node:child_process";
2
2
  import * as path from "node:path";
3
3
  import type { AgentTool } from "@earendil-works/pi-agent-core";
4
4
  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 {
@@ -24,17 +25,31 @@ function runGit(root: string, args: string[]): { ok: boolean; stdout: string; st
24
25
  return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: (result.stderr ?? "").trim() };
25
26
  }
26
27
 
27
- /** HEAD at session start, so later child commits still show in the diff. */
28
- export function captureWatchdogDiffBaseline(cwd: string): WatchdogDiffBaseline | undefined {
29
- const toplevel = runGit(cwd, ["rev-parse", "--show-toplevel"]);
30
- if (!toplevel.ok) return undefined;
31
- const head = runGit(cwd, ["rev-parse", "HEAD"]);
32
- if (!head.ok) return undefined;
33
- const root = toplevel.stdout.trim();
34
- const ref = head.stdout.trim();
28
+ const BASELINE_ARGS = ["rev-parse", "--show-toplevel", "HEAD"];
29
+
30
+ function parseBaseline(stdout: string): WatchdogDiffBaseline | undefined {
31
+ // HEAD is the last line; the repository path itself may contain newlines.
32
+ const lines = stdout.trim().split(/\r?\n/);
33
+ const ref = lines.pop();
34
+ const root = lines.join("\n");
35
35
  return root && ref ? { root, ref } : undefined;
36
36
  }
37
37
 
38
+ /** HEAD at reviewer launch, for tools that must be registered synchronously. */
39
+ export function captureWatchdogDiffBaseline(cwd: string): WatchdogDiffBaseline | undefined {
40
+ const result = runGit(cwd, BASELINE_ARGS);
41
+ return result.ok ? parseBaseline(result.stdout) : undefined;
42
+ }
43
+
44
+ /** HEAD at session start, so later child commits still show in the diff. Does not block the event loop. */
45
+ export function startWatchdogDiffBaselineCapture(cwd: string): Promise<WatchdogDiffBaseline | undefined> {
46
+ return new Promise((resolve) => {
47
+ execFile("git", ["-C", cwd, ...BASELINE_ARGS], { encoding: "utf-8", windowsHide: true }, (error, stdout) => {
48
+ resolve(error ? undefined : parseBaseline(stdout));
49
+ });
50
+ });
51
+ }
52
+
38
53
  function validatePath(value: string | undefined): string | undefined {
39
54
  const trimmed = value?.trim();
40
55
  if (!trimmed) return undefined;
@@ -51,18 +66,36 @@ function bound(text: string): string {
51
66
  }
52
67
 
53
68
  /** In a shared cwd, changes already pending when the session started also appear. */
54
- export function createWatchdogDiffTool(baseline: WatchdogDiffBaseline): AgentTool<typeof WatchdogDiffParams, { chars: number }> {
69
+ export function createWatchdogDiffTool(
70
+ baseline: WatchdogDiffBaseline | undefined,
71
+ options: { workingTreeAtLaunch?: boolean } = {},
72
+ ): AgentTool<typeof WatchdogDiffParams, { chars: number }> {
73
+ const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
55
74
  return {
56
75
  name: WATCHDOG_DIFF_TOOL_NAME,
57
76
  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.",
77
+ description: !baseline
78
+ ? "Report that a Git HEAD diff baseline is unavailable in this cwd. No diff is generated."
79
+ : workingTreeAtLaunch
80
+ ? "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."
81
+ : "Show the repository diff since the review baseline, plus untracked file paths. Optional path narrows it; stat:true returns per-file counts only.",
59
82
  parameters: WatchdogDiffParams,
60
83
  executionMode: "sequential",
61
84
  async execute(_toolCallId, params: WatchdogDiffParams) {
85
+ if (!baseline) {
86
+ return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
87
+ }
62
88
  const pathFilter = validatePath(params.path);
63
89
  const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...(params.stat === true ? ["--stat"] : []), baseline.ref, "--", ...(pathFilter ? [pathFilter] : [])]);
64
90
  if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
65
91
  const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...(pathFilter ? [pathFilter] : [])]);
92
+ if (workingTreeAtLaunch) {
93
+ const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
94
+ if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
95
+ const text = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
96
+ return { content: [{ type: "text", text }], details: { chars: text.length } };
97
+ }
98
+ }
66
99
  const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
67
100
  const sections = [diff.stdout.trimEnd()];
68
101
  if (untracked.length) {
@@ -70,7 +103,9 @@ export function createWatchdogDiffTool(baseline: WatchdogDiffBaseline): AgentToo
70
103
  sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
71
104
  if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
72
105
  }
73
- const text = bound(sections.filter(Boolean).join("\n\n")) || `No changes since baseline ${baseline.ref.slice(0, 12)}.`;
106
+ const text = bound(sections.filter(Boolean).join("\n\n")) || (workingTreeAtLaunch
107
+ ? `No working-tree changes against reviewer-launch HEAD ${baseline.ref.slice(0, 12)}. Committed changes are not included.`
108
+ : `No changes since baseline ${baseline.ref.slice(0, 12)}.`);
74
109
  return { content: [{ type: "text", text }], details: { chars: text.length } };
75
110
  },
76
111
  };
@@ -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),
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { captureWatchdogDiffBaseline, type WatchdogDiffBaseline } from "./diff-tool.ts";
2
+ import { startWatchdogDiffBaselineCapture, type WatchdogDiffBaseline } from "./diff-tool.ts";
3
3
  import { MainWatchdogRuntime } from "./runtime.ts";
4
4
  import { createMainWatchdogReview } from "./review.ts";
5
5
  import { DEFAULT_WATCHDOG_CONFIG } from "./settings.ts";
@@ -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
- let diffBaseline: WatchdogDiffBaseline | undefined;
60
+ let diffBaseline: Promise<WatchdogDiffBaseline | undefined> | 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);
@@ -94,17 +98,18 @@ export function registerChildWatchdog(
94
98
  const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx: ExtensionContext) => unknown) => void;
95
99
  onRuntimeEvent("session_start", (_event, ctx) => {
96
100
  rememberContext(ctx);
97
- diffBaseline = captureWatchdogDiffBaseline(ctx.cwd);
101
+ diffBaseline = startWatchdogDiffBaselineCapture(ctx.cwd);
98
102
  runtime.bindSession(ctx);
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();
@@ -2,7 +2,7 @@ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@e
2
2
  import { Text } from "@earendil-works/pi-tui";
3
3
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, type ThinkingLevel } from "../shared/model-info.ts";
4
4
  import { SLASH_TEXT_RESULT_TYPE } from "../shared/types.ts";
5
- import { captureWatchdogDiffBaseline, type WatchdogDiffBaseline } from "./diff-tool.ts";
5
+ import { startWatchdogDiffBaselineCapture, type WatchdogDiffBaseline } from "./diff-tool.ts";
6
6
  import { formatWatchdogRecommendation, recommendWatchdogModel, resolveWatchdogModelInput, parseWatchdogThinkingInput } from "./model-selection.ts";
7
7
  import { renderWatchdogWarning } from "./render.ts";
8
8
  import { createMainWatchdogReview } from "./review.ts";
@@ -372,7 +372,7 @@ async function handleWatchdogCommand(
372
372
 
373
373
  export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatchdogOptions = {}): MainWatchdogRuntime {
374
374
  let currentContext: ExtensionContext | undefined;
375
- let diffBaseline: WatchdogDiffBaseline | undefined;
375
+ let diffBaseline: Promise<WatchdogDiffBaseline | undefined> | undefined;
376
376
  const rememberContext = (ctx: ExtensionContext) => {
377
377
  currentContext = ctx;
378
378
  };
@@ -412,7 +412,7 @@ export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatc
412
412
 
413
413
  pi.on("session_start", (_event, ctx) => {
414
414
  rememberContext(ctx);
415
- diffBaseline = captureWatchdogDiffBaseline(ctx.cwd);
415
+ diffBaseline = startWatchdogDiffBaselineCapture(ctx.cwd);
416
416
  runtime.bindSession(ctx);
417
417
  });
418
418
  pi.on("before_agent_start", (event, ctx) => {
@@ -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";
@@ -57,7 +56,7 @@ export interface CreateMainWatchdogReviewOptions {
57
56
  streamFn?: StreamFn;
58
57
  createReadOnlyTools?: (cwd: string) => AgentTool[];
59
58
  getThinkingLevel?: () => ThinkingLevel | undefined;
60
- diffBaseline?: () => WatchdogDiffBaseline | undefined;
59
+ diffBaseline?: () => Promise<WatchdogDiffBaseline | undefined> | undefined;
61
60
  }
62
61
 
63
62
  function fullModelId(model: Pick<RegistryModel, "provider" | "id">): string {
@@ -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,25 +277,20 @@ 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,
291
290
  headers: { ...opencodeSessionHeaders(model, sessionId), ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
292
291
  });
293
292
  };
294
- const diffBaseline = options.diffBaseline?.();
293
+ const diffBaseline = await options.diffBaseline?.();
295
294
  let clarification: { question: string; evidence: string } | undefined;
296
295
  let warned = false;
297
296
  let toolCount = 0;
@@ -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
 
@@ -172,7 +178,7 @@ export function formatWatchdogOrchestrationActivity(event: unknown): string {
172
178
  const eligible = call.name === "bg_wait"
173
179
  || (call.name === "subagent_supervisor" && ["pending", "list", "reply"].includes(args.action))
174
180
  || (call.name === "subagent" && (["status", "resume", "interrupt", "steer", "stop"].includes(args.action)
175
- || (args.action === undefined && (typeof args.agent === "string" || typeof args.workflowScript === "string" || typeof args.workflowScriptPath === "string"))));
181
+ || (args.action === undefined && (typeof args.agent === "string" || args.workflow !== undefined))));
176
182
  if (!eligible) continue;
177
183
  const result = turn.toolResults.find((value) => {
178
184
  const result = value as { role?: string; toolCallId?: string; toolName?: string };
@@ -90,8 +90,8 @@ export function resolveWorkflowChatProgress(input: ResolveWorkflowChatProgressIn
90
90
  if (requestedMode === "auto") mode = sameRepo && !input.background ? "live-card" : "off";
91
91
  else mode = requestedMode;
92
92
 
93
- if (mode === "live-card" && !sameRepo) return { error: "chatProgress: 'live-card' is only available for workflowScript runs in the same Git repository." };
94
- if (mode === "live-card" && input.background) return { error: "chatProgress: 'live-card' is unavailable for async workflowScript. Async workflows have no inline live card; omit chatProgress or use auto/off. Use async:false only when the parent must block." };
93
+ if (mode === "live-card" && !sameRepo) return { error: "chatProgress: 'live-card' is only available for workflow script runs in the same Git repository." };
94
+ if (mode === "live-card" && input.background) return { error: "chatProgress: 'live-card' is unavailable for async workflow scripts. Async workflows have no inline live card; omit chatProgress or use auto/off. Use async:false only when the parent must block." };
95
95
  return { projection: { mode, repoRelation, ...(repoLabel ? { repoLabel } : {}) } };
96
96
  }
97
97