@xzzpig/pi-subagents 0.6.0 → 0.8.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 (98) hide show
  1. package/CHANGELOG.md +45 -4
  2. package/README.md +1 -1
  3. package/agents/reviewer.md +12 -2
  4. package/docs/agents.md +4 -4
  5. package/docs/configuration.md +6 -6
  6. package/docs/extension-api.md +14 -4
  7. package/docs/models.md +47 -6
  8. package/docs/observability.md +14 -3
  9. package/docs/tool-reference.md +21 -6
  10. package/docs/workflows.md +7 -1
  11. package/index.ts +10 -1
  12. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +102 -0
  13. package/node_modules/@xzzpig/pi-components/LICENSE +21 -0
  14. package/node_modules/@xzzpig/pi-components/README.md +59 -0
  15. package/node_modules/@xzzpig/pi-components/dist/index.d.ts +1 -0
  16. package/node_modules/@xzzpig/pi-components/dist/index.js +1 -0
  17. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +345 -0
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +1169 -0
  19. package/node_modules/@xzzpig/pi-components/package.json +49 -0
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +1785 -0
  21. package/package.json +7 -3
  22. package/prompts/council.md +19 -7
  23. package/prompts/parallel-review.md +5 -1
  24. package/prompts/review-loop.md +9 -5
  25. package/skills/council-mode/SKILL.md +50 -26
  26. package/skills/pi-subagents/SKILL.md +5 -1
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  28. package/skills/pi-subagents/references/execution-controls.md +13 -4
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  30. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  31. package/src/agents/agent-management.ts +115 -14
  32. package/src/agents/agent-serializer.ts +4 -2
  33. package/src/agents/agents.ts +226 -48
  34. package/src/api/external-job-provider.ts +10 -1
  35. package/src/api/preflight.ts +52 -19
  36. package/src/api/project-panes.ts +2 -0
  37. package/src/extension/doctor.ts +10 -0
  38. package/src/extension/fanout-child.ts +3 -2
  39. package/src/extension/index.ts +24 -4
  40. package/src/extension/public-execution.ts +12 -9
  41. package/src/extension/rpc.ts +77 -3
  42. package/src/extension/schemas.ts +7 -1
  43. package/src/extension/tool-description.ts +9 -6
  44. package/src/extension/tool-result.ts +19 -0
  45. package/src/inspectors/herdr/client.ts +3 -3
  46. package/src/inspectors/herdr/focus.ts +55 -0
  47. package/src/inspectors/herdr/project-panes.ts +228 -44
  48. package/src/integrations/herdr-status.ts +26 -4
  49. package/src/runs/background/async-execution.ts +146 -17
  50. package/src/runs/background/async-job-tracker.ts +33 -14
  51. package/src/runs/background/async-resume.ts +23 -2
  52. package/src/runs/background/async-retention.ts +1 -1
  53. package/src/runs/background/async-status.ts +10 -0
  54. package/src/runs/background/chain-root-attachment.ts +5 -0
  55. package/src/runs/background/control-channel.ts +98 -10
  56. package/src/runs/background/notify.ts +62 -1
  57. package/src/runs/background/result-watcher.ts +4 -3
  58. package/src/runs/background/run-status.ts +15 -1
  59. package/src/runs/background/stale-run-reconciler.ts +3 -0
  60. package/src/runs/background/subagent-runner.ts +333 -48
  61. package/src/runs/background/wait-completions.ts +2 -0
  62. package/src/runs/background/wait-tool.ts +4 -3
  63. package/src/runs/foreground/async-stop-action.ts +23 -2
  64. package/src/runs/foreground/execution.ts +148 -13
  65. package/src/runs/foreground/foreground-history.ts +3 -2
  66. package/src/runs/foreground/subagent-executor.ts +417 -50
  67. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  68. package/src/runs/shared/acceptance.ts +11 -5
  69. package/src/runs/shared/agent-contract.ts +1 -1
  70. package/src/runs/shared/child-identity.ts +36 -0
  71. package/src/runs/shared/completion-guard.ts +52 -2
  72. package/src/runs/shared/dynamic-fanout.ts +1 -1
  73. package/src/runs/shared/extension-bindings.ts +78 -0
  74. package/src/runs/shared/external-cli-runner.ts +2 -0
  75. package/src/runs/shared/external-job-bridge.ts +53 -37
  76. package/src/runs/shared/external-job-runner.ts +126 -23
  77. package/src/runs/shared/fast-mode-extension.ts +10 -0
  78. package/src/runs/shared/model-exclusions.ts +2 -1
  79. package/src/runs/shared/model-fallback.ts +48 -22
  80. package/src/runs/shared/model-scope.ts +106 -39
  81. package/src/runs/shared/mutation-evidence.ts +145 -0
  82. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  83. package/src/runs/shared/parallel-utils.ts +15 -0
  84. package/src/runs/shared/pi-args.ts +78 -1
  85. package/src/runs/shared/structured-output.ts +18 -4
  86. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  87. package/src/runs/shared/tool-availability.ts +1 -3
  88. package/src/shared/launch-contract.ts +12 -5
  89. package/src/shared/settings.ts +6 -1
  90. package/src/shared/thinking-ceiling.ts +52 -0
  91. package/src/shared/types.ts +121 -5
  92. package/src/tui/fleet-native-transcript.ts +374 -0
  93. package/src/tui/fleet-status.ts +66 -13
  94. package/src/tui/fleet-transcript.ts +47 -1
  95. package/src/tui/fleet.ts +96 -24
  96. package/src/tui/render.ts +5 -4
  97. package/src/watchdog/permission-arbiter.ts +59 -52
  98. package/src/workflows/scripted-workflow.ts +156 -12
package/src/tui/fleet.ts CHANGED
@@ -18,7 +18,8 @@ import { stopAsyncRun } from "../runs/foreground/async-stop-action.ts";
18
18
  import { resolveWorkflowForegroundSteeringTarget, steerWorkflowForegroundTarget } from "../runs/foreground/workflow-foreground-steering.ts";
19
19
  import { contextModeBadge, contextModeLabel } from "../runs/shared/context-mode.ts";
20
20
  import { FLEET_STATUS_WIDGET_KEY } from "./fleet-status.ts";
21
- import { readFleetTranscript, renderFleetTranscript, type FleetTranscript } from "./fleet-transcript.ts";
21
+ import { readFleetTranscript, renderFleetTranscript } from "./fleet-transcript.ts";
22
+ import { buildNativeFleetTranscript, loadNativeTranscriptSupport, type NativeTranscriptModule } from "./fleet-native-transcript.ts";
22
23
  import { handleHerdrInspectorAction } from "../inspectors/herdr/actions.ts";
23
24
  import type { HerdrClient } from "../inspectors/herdr/client.ts";
24
25
  import { getLivePromptAudit, type LivePromptAudit, type PromptAuditView } from "../runs/foreground/prompt-audit.ts";
@@ -47,6 +48,7 @@ export const DEFAULT_FLEET_KEYBINDINGS: Record<FleetKeybindingAction, string[]>
47
48
  inspect: ["H"],
48
49
  stop: ["D"],
49
50
  toggleTools: ["x", "X", "ctrl+o"],
51
+ toggleRenderer: ["v", "V"],
50
52
  };
51
53
 
52
54
  type ResolvedFleetKeybindings = Record<FleetKeybindingAction, string[]>;
@@ -750,11 +752,14 @@ interface FleetDetailSections {
750
752
  }
751
753
 
752
754
  interface FleetTranscriptCache {
755
+ mode: "native" | "legacy";
753
756
  path: string;
754
757
  fingerprint: string;
755
758
  width: number;
756
759
  expandedTools: boolean;
757
- transcript: FleetTranscript;
760
+ conversationState: string;
761
+ hasContent: boolean;
762
+ warning?: string;
758
763
  body: string[];
759
764
  }
760
765
 
@@ -778,6 +783,10 @@ export class SubagentFleetComponent implements Component {
778
783
  private bodyHeight = 8;
779
784
  private lastRosterWidth: number | undefined;
780
785
  private expandedTools = false;
786
+ /** Structured-view renderer selection; legacy is the always-available fallback. */
787
+ private rendererMode: "native" | "legacy" = "native";
788
+ /** undefined = still loading, null = unavailable (permanent for this inspector session). */
789
+ private nativeModule: NativeTranscriptModule | null | undefined;
781
790
  private promptAuditOpen = false;
782
791
  private promptAuditView: PromptAuditView = "authored";
783
792
  private actionNotice: FleetActionResult | undefined;
@@ -816,6 +825,52 @@ export class SubagentFleetComponent implements Component {
816
825
  this.selectedKey = options.initialKey;
817
826
  this.refresh();
818
827
  this.scheduleRefresh();
828
+ // Resolve native-renderer availability once; until it settles the
829
+ // inspector renders through the legacy path (see renderedTranscript).
830
+ void loadNativeTranscriptSupport().then((mod) => {
831
+ this.nativeModule = mod;
832
+ if (!this.disposed && this.rendererMode === "native") this.tui.requestRender();
833
+ });
834
+ }
835
+
836
+ private nativeRenderedOutcome(mod: NativeTranscriptModule, target: { path: string; trustedRoots: string[] }, width: number): { body: string[]; conversationState: string; hasContent: boolean; warning?: string } {
837
+ try {
838
+ const built = buildNativeFleetTranscript(mod, {
839
+ filePath: target.path,
840
+ trustedRoots: target.trustedRoots,
841
+ width,
842
+ expandedTools: this.expandedTools,
843
+ cwd: this.state.baseCwd,
844
+ theme: this.theme,
845
+ });
846
+ return { body: built.lines, conversationState: built.conversationState, hasContent: built.entryCount > 0, ...(built.warning ? { warning: built.warning } : {}) };
847
+ } catch {
848
+ // A native-render failure must never blank the inspector: degrade to
849
+ // the legacy renderer for the rest of this inspector session.
850
+ this.nativeModule = null;
851
+ return this.legacyRenderedOutcome(target, width);
852
+ }
853
+ }
854
+
855
+ private legacyRenderedOutcome(target: { path: string; trustedRoots: string[] }, width: number): { body: string[]; conversationState: string; hasContent: boolean; warning?: string } {
856
+ const transcript = readFleetTranscript(target.path, { trustedRoots: target.trustedRoots });
857
+ const body = transcript.events.length > 0
858
+ ? renderFleetTranscript(transcript, width, this.theme, this.markdownTheme, { expandedTools: this.expandedTools })
859
+ : [];
860
+ const latest = transcript.events.at(-1);
861
+ const conversationState = latest?.kind === "assistant"
862
+ ? "assistant response"
863
+ : latest?.kind === "user"
864
+ ? "supervisor message"
865
+ : latest?.kind === "tool"
866
+ ? `${latest.name} · ${latest.status}`
867
+ : "activity";
868
+ return {
869
+ body,
870
+ conversationState,
871
+ hasContent: transcript.events.length > 0,
872
+ ...(transcript.warning ? { warning: transcript.warning } : {}),
873
+ };
819
874
  }
820
875
 
821
876
  private scheduleRefresh(): void {
@@ -1202,6 +1257,22 @@ export class SubagentFleetComponent implements Component {
1202
1257
  this.expandedTools = !this.expandedTools;
1203
1258
  this.transcriptCache = undefined;
1204
1259
  this.tui.requestRender();
1260
+ return;
1261
+ }
1262
+ if (matchesFleetAction(data, this.keybindings, "toggleRenderer")) {
1263
+ if (this.rendererMode === "native" && this.nativeModule === null) {
1264
+ this.setActionNotice({ text: "Native transcript renderer unavailable in this host; staying on the text view.", isError: true });
1265
+ return;
1266
+ }
1267
+ if (this.rendererMode === "legacy" && this.nativeModule === undefined) {
1268
+ this.setActionNotice({ text: "Native transcript renderer is still loading." });
1269
+ return;
1270
+ }
1271
+ this.rendererMode = this.rendererMode === "native" ? "legacy" : "native";
1272
+ this.detailAutoFollow = true;
1273
+ this.transcriptCache = undefined;
1274
+ this.tui.requestRender();
1275
+ return;
1205
1276
  }
1206
1277
  }
1207
1278
 
@@ -1219,21 +1290,29 @@ export class SubagentFleetComponent implements Component {
1219
1290
  });
1220
1291
  }
1221
1292
 
1222
- private renderedTranscript(target: { path: string; trustedRoots: string[] }, width: number): { transcript: FleetTranscript; body: string[] } {
1223
- const fingerprint = `${target.trustedRoots.join("\0")}|${transcriptFingerprint(target.path)}`;
1293
+ private renderedTranscript(target: { path: string; trustedRoots: string[] }, width: number): { body: string[]; conversationState: string; hasContent: boolean; warning?: string } {
1294
+ const fingerprint = `${this.rendererMode}|${target.trustedRoots.join("\0")}|${transcriptFingerprint(target.path)}`;
1224
1295
  if (this.transcriptCache
1296
+ && this.transcriptCache.mode === this.rendererMode
1225
1297
  && this.transcriptCache.path === target.path
1226
1298
  && this.transcriptCache.fingerprint === fingerprint
1227
1299
  && this.transcriptCache.width === width
1228
1300
  && this.transcriptCache.expandedTools === this.expandedTools) {
1229
- return { transcript: this.transcriptCache.transcript, body: [...this.transcriptCache.body] };
1301
+ return {
1302
+ body: [...this.transcriptCache.body],
1303
+ conversationState: this.transcriptCache.conversationState,
1304
+ hasContent: this.transcriptCache.hasContent,
1305
+ ...(this.transcriptCache.warning ? { warning: this.transcriptCache.warning } : {}),
1306
+ };
1230
1307
  }
1231
- const transcript = readFleetTranscript(target.path, { trustedRoots: target.trustedRoots });
1232
- const body = transcript.events.length > 0
1233
- ? renderFleetTranscript(transcript, width, this.theme, this.markdownTheme, { expandedTools: this.expandedTools })
1234
- : [];
1235
- this.transcriptCache = { path: target.path, fingerprint, width, expandedTools: this.expandedTools, transcript, body };
1236
- return { transcript, body: [...body] };
1308
+ // While the native module is still resolving (undefined) or unavailable
1309
+ // (null) the legacy rail renderer serves the view; both paths share the
1310
+ // same trusted-root read and cache entry.
1311
+ const outcome = this.rendererMode === "native" && this.nativeModule
1312
+ ? this.nativeRenderedOutcome(this.nativeModule, target, width)
1313
+ : this.legacyRenderedOutcome(target, width);
1314
+ this.transcriptCache = { mode: this.rendererMode, path: target.path, fingerprint, width, expandedTools: this.expandedTools, ...outcome, body: [...outcome.body] };
1315
+ return outcome;
1237
1316
  }
1238
1317
 
1239
1318
  private promptAuditDetail(width: number): FleetDetailSections {
@@ -1270,20 +1349,13 @@ export class SubagentFleetComponent implements Component {
1270
1349
  if (selected) {
1271
1350
  const target = transcriptTarget(selected, this.state);
1272
1351
  if (target) {
1273
- const { transcript, body } = this.renderedTranscript(target, width);
1274
- transcriptWarning = transcript.warning;
1275
- if (transcript.events.length > 0) {
1352
+ const rendered = this.renderedTranscript(target, width);
1353
+ transcriptWarning = rendered.warning;
1354
+ if (rendered.hasContent) {
1355
+ const body = rendered.body;
1276
1356
  if (this.snapshot.error) body.unshift(this.theme.fg("warning", `Fleet scan warning: ${this.snapshot.error}`), "");
1277
- const latest = transcript.events.at(-1);
1278
- const conversationState = latest?.kind === "assistant"
1279
- ? "assistant response"
1280
- : latest?.kind === "user"
1281
- ? "supervisor message"
1282
- : latest?.kind === "tool"
1283
- ? `${latest.name} · ${latest.status}`
1284
- : "activity";
1285
1357
  const promptSummary = selected.kind === "foreground-active" ? foregroundAuthoredPromptSummary(selected, this.state) : undefined;
1286
- return { header: structuredHeader(selected, width, this.theme, conversationState, promptSummary), body: this.withActionLines(body) };
1358
+ return { header: structuredHeader(selected, width, this.theme, rendered.conversationState, promptSummary), body: this.withActionLines(body) };
1287
1359
  }
1288
1360
  }
1289
1361
  }
@@ -1352,7 +1424,7 @@ export class SubagentFleetComponent implements Component {
1352
1424
  ? ` j/k child · 1/2/3 view · g redo with guidance · c copy · wheel ↑↓ · Esc close Prompt Audit · ${position}`
1353
1425
  : selected?.kind === "external"
1354
1426
  ? ` ${bindingLabel(this.keybindings, "selectUp")}/${bindingLabel(this.keybindings, "selectDown")} job · display-only · ${bindingLabel(this.keybindings, "refresh")} refresh · wheel ↑↓ · ${bindingLabel(this.keybindings, "close")} close · ${position}`
1355
- : ` ${bindingLabel(this.keybindings, "selectUp")}/${bindingLabel(this.keybindings, "selectDown")} agent · p Prompt Audit · ${bindingLabel(this.keybindings, "inspect")} Herdr · ${bindingLabel(this.keybindings, "steer")} steer · ${bindingLabel(this.keybindings, "stop")} stop · ${bindingLabel(this.keybindings, "toggleTools")} tools · ${bindingLabel(this.keybindings, "refresh")} refresh · wheel ↑↓ · ${bindingLabel(this.keybindings, "close")} close · ${position}`;
1427
+ : ` ${bindingLabel(this.keybindings, "selectUp")}/${bindingLabel(this.keybindings, "selectDown")} agent · p Prompt Audit · ${bindingLabel(this.keybindings, "inspect")} Herdr · ${bindingLabel(this.keybindings, "steer")} steer · ${bindingLabel(this.keybindings, "stop")} stop · ${bindingLabel(this.keybindings, "toggleTools")} tools · ${bindingLabel(this.keybindings, "toggleRenderer")} view · ${bindingLabel(this.keybindings, "refresh")} refresh · wheel ↑↓ · ${bindingLabel(this.keybindings, "close")} close · ${position}`;
1356
1428
  lines.push(this.theme.fg("border", "│") + fit(this.theme.fg("dim", footer), innerWidth) + this.theme.fg("border", "│"));
1357
1429
  lines.push(this.theme.fg("border", `╰${"─".repeat(innerWidth)}╯`));
1358
1430
  return lines.map((line) => truncateToWidth(line, width));
package/src/tui/render.ts CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  type WorkflowNodeStatus,
19
19
  type MainWindowRendererConfig,
20
20
  MAX_WIDGET_JOBS,
21
- POLL_INTERVAL_MS,
21
+ WIDGET_ANIMATION_INTERVAL_MS,
22
22
  WIDGET_KEY,
23
23
  } from "../shared/types.ts";
24
24
  import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
@@ -1580,7 +1580,7 @@ function buildWidgetComponent(jobs: AsyncJobState[], expanded: boolean): (_tui:
1580
1580
  const container = new Container();
1581
1581
  container.render = (renderWidth: number): string[] => {
1582
1582
  const width = Math.max(0, renderWidth - 2);
1583
- const frame = Math.floor(Date.now() / POLL_INTERVAL_MS);
1583
+ const frame = Math.floor(Date.now() / WIDGET_ANIMATION_INTERVAL_MS);
1584
1584
  const buildLines = (): string[] => expanded
1585
1585
  ? buildWidgetLines(jobs, theme, width, true, frame)
1586
1586
  : jobs.length === 1
@@ -1746,8 +1746,9 @@ function workflowRowStateLabel(row: WorkflowChatProgressRow, theme: Theme): stri
1746
1746
  }
1747
1747
 
1748
1748
  function workflowOverallState(rows: WorkflowChatProgressRow[], hasTerminalValue: boolean, isError?: boolean): "running" | "complete" | "failed" | "paused" {
1749
- if (isError || rows.some((row) => row.state === "failed")) return "failed";
1749
+ if (rows.some((row) => row.state === "failed")) return "failed";
1750
1750
  if (rows.some((row) => row.state === "detached")) return "paused";
1751
+ if (isError) return "failed";
1751
1752
  if ((rows.length > 0 && rows.every((row) => row.state === "complete")) || hasTerminalValue) return "complete";
1752
1753
  return "running";
1753
1754
  }
@@ -1948,7 +1949,7 @@ export function renderSubagentResult(
1948
1949
  const layout = resolveMainWindowRenderLayout(rendererConfig);
1949
1950
  const compact = (component: Component): Component => capCompactMainWindowResult(component, layout, theme, !options.expanded);
1950
1951
  const d = result.details;
1951
- if (d?.mode === "workflow" && d.chatProgress?.mode === "live-card" && !result.isError && d.workflow?.value === undefined) {
1952
+ if (d?.mode === "workflow" && d.chatProgress?.mode === "live-card" && d.workflow?.value === undefined && (!result.isError || (d.workflow?.trace.length ?? 0) > 0)) {
1952
1953
  return compact(renderWorkflowChatProgress(d, result, theme, options.expanded ? resolveMainWindowRenderLayout() : layout, frame));
1953
1954
  }
1954
1955
  if (!d || !d.results.length) {
@@ -3,7 +3,6 @@ import { convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import { streamSimple } from "@earendil-works/pi-ai/compat";
4
4
  import { Type, type Static } from "typebox";
5
5
  import { appendPermissionAudit, permissionArgsPreview } from "../runs/shared/permissions.ts";
6
- import { agentStreamOptions } from "../shared/agent-stream-options.ts";
7
6
  import { decodeChildWatchdogConfig } from "./child-status.ts";
8
7
  import { childResolvedConfig } from "./register-child.ts";
9
8
  import { resolveWatchdogReviewModel } from "./review.ts";
@@ -45,7 +44,11 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
45
44
  const createdAt = Date.now();
46
45
  const auditBase = { type: "permission.request", createdAt, toolName: request.toolName, preview, matchedRule: "ask", decisionSource: "watchdog" };
47
46
  appendPermissionAudit(request.auditPath, auditBase);
47
+ let completed = false;
48
48
  const finish = (approved: boolean, reason: string, decision: string): WatchdogPermissionResult => {
49
+ const concise = conciseReason(reason);
50
+ if (completed) return { approved, reason: concise, source: "watchdog" };
51
+ completed = true;
49
52
  appendPermissionAudit(request.auditPath, {
50
53
  type: "permission.decision",
51
54
  createdAt: Date.now(),
@@ -54,9 +57,9 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
54
57
  decision,
55
58
  approved,
56
59
  decisionSource: "watchdog",
57
- reason: conciseReason(reason),
60
+ reason: concise,
58
61
  });
59
- return { approved, reason: conciseReason(reason), source: "watchdog" };
62
+ return { approved, reason: concise, source: "watchdog" };
60
63
  };
61
64
 
62
65
  let childConfig;
@@ -84,61 +87,65 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
84
87
 
85
88
  let timeout: ReturnType<typeof setTimeout> | undefined;
86
89
  let agent: Agent | undefined;
90
+ let abort: (() => void) | undefined;
87
91
  try {
88
- const config = childResolvedConfig(childConfig);
89
- const selection = await resolveWatchdogReviewModel(request.ctx, config);
90
- const auth = selection.auth;
91
- const registeredProvider = (request.ctx.modelRegistry as {
92
- getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
93
- }).getRegisteredProviderConfig?.(selection.model.provider);
94
- const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
95
- ? registeredProvider.streamSimple
96
- : streamSimple);
97
- const streamFn: StreamFn = (model, context, streamOptions) => baseStreamFn(model, context, {
98
- ...streamOptions,
99
- ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
100
- env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
101
- headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
102
- });
103
- agent = new Agent({
104
- initialState: {
105
- 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
- ].join("\n"),
111
- model: selection.model,
112
- thinkingLevel: selection.thinkingLevel,
113
- tools: [tool],
114
- },
115
- convertToLlm,
116
- streamFn: streamFn,
117
- getApiKey: (providerName) => providerName === selection.model.provider ? auth.apiKey : undefined,
118
- beforeToolCall: async ({ toolCall }) => toolCall.name === tool.name ? undefined : { block: true, reason: `Permission arbiter tool '${toolCall.name}' is not allowed.` },
119
- toolExecution: "sequential",
120
- });
121
- const abort = () => agent?.abort();
122
- request.signal?.addEventListener("abort", abort, { once: true });
123
- request.ctx.signal?.addEventListener("abort", abort, { once: true });
124
- try {
125
- const prompt = `Tool: ${request.toolName}\nRedacted arguments: ${preview}`;
126
- await Promise.race([
127
- agent.prompt(prompt),
128
- new Promise<never>((_, reject) => { timeout = setTimeout(() => { agent?.abort(); reject(new Error("Watchdog permission decision timed out.")); }, childConfig.agentEndTimeoutMs); }),
129
- ]);
130
- } finally {
131
- request.signal?.removeEventListener("abort", abort);
132
- request.ctx.signal?.removeEventListener("abort", abort);
133
- }
134
- if (!decision) return finish(false, "Watchdog permission arbiter returned no decision.", "malformed");
135
- const approved = decision.decision === "approve";
136
- return finish(approved, decision.reason, decision.decision);
92
+ const run = async (): Promise<WatchdogPermissionResult> => {
93
+ const config = childResolvedConfig(childConfig);
94
+ const selection = await resolveWatchdogReviewModel(request.ctx, config);
95
+ const auth = selection.auth;
96
+ const registeredProvider = (request.ctx.modelRegistry as {
97
+ getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
98
+ }).getRegisteredProviderConfig?.(selection.model.provider);
99
+ const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
100
+ ? registeredProvider.streamSimple
101
+ : streamSimple);
102
+ const streamFn: StreamFn = (model, context, streamOptions) => baseStreamFn(model, context, {
103
+ ...streamOptions,
104
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
105
+ env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
106
+ headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
107
+ });
108
+ agent = new Agent({
109
+ initialState: {
110
+ systemPrompt: [
111
+ "You are the pi-subagents watchdog permission arbiter.",
112
+ "Decide only whether this exact non-bash child tool call should proceed.",
113
+ "Call watchdog_permission_decision exactly once with approve or deny and a concise reason.",
114
+ "Deny when uncertain. Do not produce freeform advice or ask the parent orchestrator.",
115
+ ].join("\n"),
116
+ model: selection.model,
117
+ thinkingLevel: selection.thinkingLevel,
118
+ tools: [tool],
119
+ },
120
+ convertToLlm,
121
+ streamFn: streamFn,
122
+ getApiKey: (providerName) => providerName === selection.model.provider ? auth.apiKey : undefined,
123
+ beforeToolCall: async ({ toolCall }) => toolCall.name === tool.name ? undefined : { block: true, reason: `Permission arbiter tool '${toolCall.name}' is not allowed.` },
124
+ toolExecution: "sequential",
125
+ });
126
+ await agent.prompt(`Tool: ${request.toolName}\nRedacted arguments: ${preview}`);
127
+ if (!decision) return finish(false, "Watchdog permission arbiter returned no decision.", "malformed");
128
+ const approved = decision.decision === "approve";
129
+ return finish(approved, decision.reason, decision.decision);
130
+ };
131
+ return await Promise.race([
132
+ run(),
133
+ new Promise<WatchdogPermissionResult>((resolve) => { timeout = setTimeout(() => { agent?.abort(); resolve(finish(false, "Watchdog permission decision timed out.", "timeout")); }, childConfig.agentEndTimeoutMs); }),
134
+ new Promise<WatchdogPermissionResult>((resolve) => {
135
+ abort = () => { agent?.abort(); resolve(finish(false, "Watchdog permission decision was cancelled.", "cancelled")); };
136
+ request.signal?.addEventListener("abort", abort, { once: true });
137
+ request.ctx.signal?.addEventListener("abort", abort, { once: true });
138
+ }),
139
+ ]);
137
140
  } catch (error) {
138
141
  const reason = error instanceof Error ? error.message : String(error);
139
142
  return finish(false, `Watchdog permission arbiter failed closed: ${reason}`, reason.includes("timed out") ? "timeout" : "error");
140
143
  } finally {
141
144
  if (timeout) clearTimeout(timeout);
145
+ if (abort) {
146
+ request.signal?.removeEventListener("abort", abort);
147
+ request.ctx.signal?.removeEventListener("abort", abort);
148
+ }
142
149
  }
143
150
  };
144
151
  }