@xzzpig/pi-subagents 0.20.0 → 0.21.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 (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -0,0 +1,305 @@
1
+ import { getMarkdownTheme, keyText, type Theme, type ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import { Box, Container, Markdown, MouseRegion, Spacer, truncateToWidth, type Component } from "@earendil-works/pi-tui";
3
+ import { SUBAGENT_CONTROL_MESSAGE_TYPE } from "../extension/control-notices.ts";
4
+ import { SUBAGENT_STEERING_MESSAGE_TYPE } from "../extension/steering-notices.ts";
5
+ import { parseSupervisorReplyData, parseSupervisorRequestDetails, SUPERVISOR_REPLY_ENTRY_TYPE, SUPERVISOR_REQUEST_MESSAGE_TYPE } from "../intercom/supervisor-ui.ts";
6
+ import { parseSubagentNotifyContent } from "../runs/background/notify.ts";
7
+ import { safeTerminalText } from "../shared/display-text.ts";
8
+ import { formatWatchdogWarningRenderText, stateLabels } from "../watchdog/render.ts";
9
+ import { SUBAGENT_WATCHDOG_WARNING_TYPE, WATCHDOG_WARNING_IMPORTANCES, WATCHDOG_WARNING_SEVERITIES, type WatchdogWarning } from "../watchdog/types.ts";
10
+ import { normalizeWatchdogWarningDetails } from "../watchdog/warning-format.ts";
11
+
12
+ interface SubagentMessage {
13
+ customType: string;
14
+ content: unknown;
15
+ details?: unknown;
16
+ }
17
+
18
+ interface SubagentEntry {
19
+ customType: string;
20
+ data?: unknown;
21
+ }
22
+
23
+ /** Plain text, plus status words that take the theme's status color. */
24
+ type Headline = ReadonlyArray<string | { status: string }>;
25
+
26
+ type MessageKind = "ask" | "reply" | "result" | "attention" | "watchdog";
27
+
28
+ /**
29
+ * Theme colors for the label. Pi's themes offer few non-status colors that read
30
+ * apart, so asks and attention notices, both a child needing the parent, share one,
31
+ * and replies, the parent's own words, take the quiet text color.
32
+ */
33
+ const KIND_LABEL_COLORS = {
34
+ ask: "customMessageLabel",
35
+ attention: "customMessageLabel",
36
+ reply: "customMessageText",
37
+ result: "mdLink",
38
+ watchdog: "toolTitle",
39
+ } as const satisfies Record<MessageKind, ThemeColor>;
40
+
41
+ interface BlockView {
42
+ kind: MessageKind;
43
+ headline: Headline;
44
+ /** Markdown shown when the block is expanded. */
45
+ body: string;
46
+ }
47
+
48
+ type StatusTone = "success" | "error" | "warning";
49
+
50
+ /** A Map, so a status word read from session data never resolves to an Object prototype key. */
51
+ const STATUS_TONES = new Map<string, StatusTone>([
52
+ ["completed", "success"],
53
+ ["failed", "error"],
54
+ ["partial", "error"],
55
+ ["blocked", "error"],
56
+ ["unhandled", "error"],
57
+ ["blocker", "error"],
58
+ ["save failed", "error"],
59
+ ["reconciliation failed", "error"],
60
+ ["could not be reconciled", "error"],
61
+ ["paused", "warning"],
62
+ ["stopped", "warning"],
63
+ ["recovered", "warning"],
64
+ ["unanswered", "warning"],
65
+ ["concern", "warning"],
66
+ ["timed out", "warning"],
67
+ ["needs attention", "warning"],
68
+ ["needs a decision", "warning"],
69
+ ["needs clarification", "warning"],
70
+ ["asks for structured answers", "warning"],
71
+ ]);
72
+
73
+ function isRecord(value: unknown): value is Record<string, unknown> {
74
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75
+ }
76
+
77
+ /** The text Pi sends to the model for a custom message. */
78
+ function contentText(content: unknown): string {
79
+ if (typeof content === "string") return content;
80
+ if (!Array.isArray(content)) return "";
81
+ return content.flatMap((part: unknown) => isRecord(part) && typeof part.text === "string" ? [part.text] : []).join("\n");
82
+ }
83
+
84
+ /** A message that expands to the text the main agent read. */
85
+ function readsContent(kind: MessageKind, headline: (message: SubagentMessage) => Headline): (message: SubagentMessage) => BlockView {
86
+ return (message) => ({ kind, headline: headline(message), body: contentText(message.content) });
87
+ }
88
+
89
+ function supervisorRequestHeadline(details: unknown): Headline {
90
+ const request = parseSupervisorRequestDetails(details);
91
+ if (!request?.agent) return ["supervisor request"];
92
+ if (request.reason === "interview_request") return [`${request.agent} `, { status: "asks for structured answers" }];
93
+ if (request.reason === "progress_update") return [`${request.agent} sent a progress update`];
94
+ return [`${request.agent} `, { status: "needs a decision" }];
95
+ }
96
+
97
+ function controlNoticeHeadline(details: unknown): Headline {
98
+ const event = isRecord(details) ? details.event : undefined;
99
+ if (!isRecord(event) || typeof event.agent !== "string" || typeof event.type !== "string") return ["subagent notice"];
100
+ if (event.type === "needs_attention") return [`${event.agent} `, { status: "needs attention" }];
101
+ return [`${event.agent} ${event.type.replaceAll("_", " ")}`];
102
+ }
103
+
104
+ function steeringNoticeHeadline(details: unknown): Headline {
105
+ if (!isRecord(details) || typeof details.runId !== "string") return ["steering notice"];
106
+ const { state } = details;
107
+ if (state !== "failed" && state !== "partial" && state !== "recovered") return ["steering notice"];
108
+ return [`steering for run ${details.runId} `, { status: state }];
109
+ }
110
+
111
+ const RUN_STATUSES = ["completed", "failed", "paused", "stopped"] as const;
112
+ type RunStatus = typeof RUN_STATUSES[number];
113
+
114
+ function isRunStatus(value: unknown): value is RunStatus {
115
+ return RUN_STATUSES.some((status) => status === value);
116
+ }
117
+
118
+ /** Agents and outcomes of a completion notice; notices saved before render details existed are read from their text. */
119
+ function completionRuns(message: SubagentMessage): Array<{ agent: string; status: RunStatus }> | undefined {
120
+ const runs = isRecord(message.details) ? message.details.runs : undefined;
121
+ if (Array.isArray(runs)) {
122
+ const parsed = runs.flatMap((run: unknown) => isRecord(run) && typeof run.agent === "string" && isRunStatus(run.status) ? [{ agent: run.agent, status: run.status }] : []);
123
+ if (parsed.length === runs.length && parsed.length > 0) return parsed;
124
+ }
125
+ const saved = parseSubagentNotifyContent(contentText(message.content));
126
+ return saved ? [{ agent: saved.agent, status: saved.status }] : undefined;
127
+ }
128
+
129
+ function completionHeadline(message: SubagentMessage): Headline {
130
+ const runs = completionRuns(message);
131
+ if (runs?.length === 1) return [`${runs[0]!.agent} `, { status: runs[0]!.status }];
132
+ if (runs) {
133
+ if (runs.every((run) => run.status === "completed")) return [`${runs.length} background runs `, { status: "completed" }];
134
+ const counts = (["failed", "paused", "stopped"] as const).flatMap((status) => {
135
+ const count = runs.filter((run) => run.status === status).length;
136
+ return count ? [` · ${count} `, { status }] : [];
137
+ });
138
+ return [`${runs.length} background runs finished`, ...counts];
139
+ }
140
+ const grouped = /^Background tasks completed \((\d+)\):/.exec(contentText(message.content));
141
+ return grouped ? [`${grouped[1]} background runs finished`] : ["background run finished"];
142
+ }
143
+
144
+ function supervisorReminderHeadline(details: unknown, status: "unanswered" | "blocked"): Headline {
145
+ const ids = isRecord(details) ? details.requestIds : undefined;
146
+ if (!Array.isArray(ids) || ids.length === 0) return ["supervisor requests ", { status }];
147
+ return [`${ids.length} supervisor ${ids.length === 1 ? "request" : "requests"} `, { status }];
148
+ }
149
+
150
+ function waitSubscriptionHeadline(details: unknown): Headline {
151
+ if (!isRecord(details) || typeof details.runId !== "string" || typeof details.outcome !== "string") return ["bg_wait fired"];
152
+ return [`bg_wait: run ${details.runId} `, { status: details.outcome }];
153
+ }
154
+
155
+ /** Workflow child notices saved before render details existed are read from their first line. */
156
+ function workflowChildHeadline(message: SubagentMessage): Headline {
157
+ const { details } = message;
158
+ if (isRecord(details) && typeof details.childKey === "string" && isRunStatus(details.outcome)) {
159
+ return [`workflow child ${details.childKey} `, { status: details.outcome }];
160
+ }
161
+ const saved = /^Workflow child (completed|failed|paused|stopped)(?: \(needs attention\))?: \*\*(.+)\*\*$/m.exec(contentText(message.content));
162
+ return saved ? [`workflow child ${saved[2]} `, { status: saved[1]! }] : ["workflow child update"];
163
+ }
164
+
165
+ function isWatchdogWarning(value: unknown): value is WatchdogWarning {
166
+ if (!isRecord(value)) return false;
167
+ return WATCHDOG_WARNING_SEVERITIES.some((known) => known === value.severity)
168
+ && WATCHDOG_WARNING_IMPORTANCES.some((known) => known === value.importance)
169
+ && (value.category === undefined || typeof value.category === "string")
170
+ && typeof value.summary === "string"
171
+ && typeof value.evidence === "string"
172
+ && typeof value.recommendedAction === "string";
173
+ }
174
+
175
+ /** The model reads watchdog warnings as XML; people get the watchdog's readable text. */
176
+ function watchdogWarningView(details: unknown, fallbackBody: string): BlockView {
177
+ if (!isWatchdogWarning(details)) return { kind: "watchdog", headline: ["watchdog warning"], body: fallbackBody };
178
+ // Every shown warning is "displayed"; the other labels say the run was held or the review went wrong.
179
+ const labels = stateLabels(details).filter((label) => label !== "displayed");
180
+ return {
181
+ kind: "watchdog",
182
+ headline: ["watchdog ", { status: details.severity }, ...(labels.length ? [` · ${labels.join(", ")}`] : [])],
183
+ body: formatWatchdogWarningRenderText(normalizeWatchdogWarningDetails(details)),
184
+ };
185
+ }
186
+
187
+ function supervisorReplyView(data: unknown): BlockView {
188
+ const reply = parseSupervisorReplyData(data);
189
+ if (!reply) return { kind: "reply", headline: ["supervisor reply"], body: "" };
190
+ return {
191
+ kind: "reply",
192
+ headline: [`reply sent to ${reply.agent}`],
193
+ body: [
194
+ `Request: ${reply.requestId}`,
195
+ `Run: ${reply.runId}`,
196
+ `Child index: ${reply.childIndex}`,
197
+ ...(reply.childTarget ? [`Child target: ${reply.childTarget}`] : []),
198
+ "",
199
+ reply.message,
200
+ ].join("\n"),
201
+ };
202
+ }
203
+
204
+ const MESSAGE_VIEWS = new Map<string, (message: SubagentMessage) => BlockView>([
205
+ [SUPERVISOR_REQUEST_MESSAGE_TYPE, readsContent("ask", (message) => supervisorRequestHeadline(message.details))],
206
+ ["subagent-supervisor-unanswered", readsContent("ask", (message) => supervisorReminderHeadline(message.details, "unanswered"))],
207
+ ["subagent-supervisor-blocked", readsContent("ask", (message) => supervisorReminderHeadline(message.details, "blocked"))],
208
+ ["subagent-notify", readsContent("result", completionHeadline)],
209
+ ["subagent-completion-unanswered", readsContent("result", () => ["completion results ", { status: "unanswered" }])],
210
+ ["subagent-completion-unhandled", readsContent("result", () => ["completion results ", { status: "unhandled" }])],
211
+ ["subagent-wait-subscription", readsContent("result", (message) => waitSubscriptionHeadline(message.details))],
212
+ ["subagent-incremental-child-notify", readsContent("result", workflowChildHeadline)],
213
+ ["subagent-workflow-result-write-failed", readsContent("result", () => ["workflow result ", { status: "save failed" }])],
214
+ [SUBAGENT_CONTROL_MESSAGE_TYPE, readsContent("attention", (message) => controlNoticeHeadline(message.details))],
215
+ [SUBAGENT_STEERING_MESSAGE_TYPE, readsContent("attention", (message) => steeringNoticeHeadline(message.details))],
216
+ [SUBAGENT_WATCHDOG_WARNING_TYPE, (message) => watchdogWarningView(message.details, contentText(message.content))],
217
+ ["subagent_watchdog_clarification", readsContent("watchdog", () => ["watchdog ", { status: "needs clarification" }])],
218
+ ]);
219
+
220
+ const ENTRY_VIEWS = new Map<string, (entry: SubagentEntry) => BlockView>([
221
+ [SUPERVISOR_REPLY_ENTRY_TYPE, (entry) => supervisorReplyView(entry.data)],
222
+ [SUBAGENT_WATCHDOG_WARNING_TYPE, (entry) => watchdogWarningView(entry.data, "")],
223
+ ]);
224
+
225
+ /** Every message type pi-subagents shows in the main chat. */
226
+ export const SUBAGENT_MESSAGE_TYPES: readonly string[] = [...MESSAGE_VIEWS.keys()];
227
+
228
+ /** Every session entry type pi-subagents shows in the main chat. */
229
+ export const SUBAGENT_ENTRY_TYPES: readonly string[] = [...ENTRY_VIEWS.keys()];
230
+
231
+ function headlineText(headline: Headline, theme: Theme): string {
232
+ let text = "";
233
+ let plain = "";
234
+ for (const part of headline) {
235
+ const word = typeof part === "string" ? part : part.status;
236
+ const tone = typeof part === "string" ? undefined : STATUS_TONES.get(part.status);
237
+ if (!tone) {
238
+ plain += word;
239
+ continue;
240
+ }
241
+ if (plain) text += theme.fg("customMessageText", safeTerminalText(plain));
242
+ plain = "";
243
+ text += theme.fg(tone, word);
244
+ }
245
+ return plain ? text + theme.fg("customMessageText", safeTerminalText(plain)) : text;
246
+ }
247
+
248
+ /**
249
+ * A click toggles one block until Pi's expand key changes the state of every
250
+ * block. Keyed by the message or entry object, which Pi keeps across rebuilds.
251
+ */
252
+ const clickedBlocks = new WeakMap<SubagentMessage | SubagentEntry, { expandedByPi: boolean; expanded: boolean }>();
253
+
254
+ /** The block Pi draws for its own [skill] and [compaction] messages. */
255
+ class SubagentMessageBlock extends Box {
256
+ private readonly source: SubagentMessage | SubagentEntry;
257
+ private readonly view: BlockView;
258
+ private readonly expandedByPi: boolean;
259
+ private readonly theme: Theme;
260
+
261
+ constructor(source: SubagentMessage | SubagentEntry, view: BlockView, expandedByPi: boolean, theme: Theme) {
262
+ super(1, 1, (text) => theme.bg("customMessageBg", text));
263
+ this.source = source;
264
+ this.view = view;
265
+ this.expandedByPi = expandedByPi;
266
+ this.theme = theme;
267
+ const clicked = clickedBlocks.get(source);
268
+ if (clicked && clicked.expandedByPi !== expandedByPi) clickedBlocks.delete(source);
269
+ this.rebuild();
270
+ }
271
+
272
+ private isExpanded(): boolean {
273
+ return clickedBlocks.get(this.source)?.expanded ?? this.expandedByPi;
274
+ }
275
+
276
+ private rebuild(): void {
277
+ const { theme, view } = this;
278
+ const content = new Container();
279
+ const title = `${theme.fg(KIND_LABEL_COLORS[view.kind], theme.bold("[subagent]"))} ${headlineText(view.headline, theme)}`;
280
+ const expanded = this.isExpanded();
281
+ const line = expanded ? title : `${title} ${theme.fg("dim", `(${keyText("app.tools.expand") || "click"} to expand)`)}`;
282
+ content.addChild({ render: (width) => [truncateToWidth(line, width, "…")], invalidate() {} });
283
+ if (expanded && view.body.trim()) {
284
+ content.addChild(new Spacer(1));
285
+ content.addChild(new Markdown(safeTerminalText(view.body), 0, 0, getMarkdownTheme(), { color: (text) => theme.fg("customMessageText", text) }));
286
+ }
287
+ this.clear();
288
+ this.addChild(new MouseRegion(content, (event) => {
289
+ if (event.type !== "click" || event.button !== "left") return undefined;
290
+ clickedBlocks.set(this.source, { expandedByPi: this.expandedByPi, expanded: !this.isExpanded() });
291
+ this.rebuild();
292
+ return { handled: true };
293
+ }));
294
+ }
295
+ }
296
+
297
+ export function renderSubagentMessage(message: SubagentMessage, options: { expanded: boolean }, theme: Theme): Component | undefined {
298
+ const view = MESSAGE_VIEWS.get(message.customType)?.(message);
299
+ return view ? new SubagentMessageBlock(message, view, options.expanded, theme) : undefined;
300
+ }
301
+
302
+ export function renderSubagentEntry(entry: SubagentEntry, options: { expanded: boolean }, theme: Theme): Component | undefined {
303
+ const view = ENTRY_VIEWS.get(entry.customType)?.(entry);
304
+ return view ? new SubagentMessageBlock(entry, view, options.expanded, theme) : undefined;
305
+ }
@@ -77,8 +77,8 @@ export function createWatchdogDiffTool(
77
77
  description: !baseline
78
78
  ? "Report that a Git HEAD diff baseline is unavailable in this cwd. No diff is generated."
79
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.",
80
+ ? "Show the current staged and unstaged working-tree delta against reviewer-launch HEAD, plus untracked file paths, including edits by other sessions in this checkout. 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, including edits by other sessions in this checkout. Optional path narrows it; stat:true returns per-file counts only.",
82
82
  parameters: WatchdogDiffParams,
83
83
  executionMode: "sequential",
84
84
  async execute(_toolCallId, params: WatchdogDiffParams) {
@@ -1,10 +1,8 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { Text } from "@earendil-works/pi-tui";
3
2
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, type ThinkingLevel } from "../shared/model-info.ts";
4
3
  import { SLASH_TEXT_RESULT_TYPE } from "../shared/types.ts";
5
4
  import { startWatchdogDiffBaselineCapture, type WatchdogDiffBaseline } from "./diff-tool.ts";
6
5
  import { formatWatchdogRecommendation, recommendWatchdogModel, resolveWatchdogModelInput, parseWatchdogThinkingInput } from "./model-selection.ts";
7
- import { renderWatchdogWarning } from "./render.ts";
8
6
  import { createMainWatchdogReview } from "./review.ts";
9
7
  import { MainWatchdogRuntime, type WatchdogReviewFunction } from "./runtime.ts";
10
8
  import { getWatchdogUserSettingsPath, writeUserWatchdogEnabled, writeWatchdogModelSettings } from "./settings.ts";
@@ -12,7 +10,6 @@ import {
12
10
  SUBAGENT_WATCHDOG_WARNING_TYPE,
13
11
  type WatchdogRuntimeStatus,
14
12
  type WatchdogWarning,
15
- type WatchdogWarningDetails,
16
13
  } from "./types.ts";
17
14
  import { createWatchdogWarningMessage } from "./warning-format.ts";
18
15
 
@@ -149,7 +146,7 @@ export function buildWatchdogStatus(snapshot: ReturnType<MainWatchdogRuntime["ge
149
146
  "- /subagents-watchdog model <provider/model[:thinking]>",
150
147
  "- /subagents-watchdog model inherit",
151
148
  "- /subagents-watchdog session model recommended",
152
- "Agent action: subagent({ action: \"watchdog.configure\", model: \"recommended\", scope: \"session\" })",
149
+ "Agent action: subagent({ action: \"watchdog.configure\", model: \"recommended\", options: { scope: \"session\" } })",
153
150
  );
154
151
  return lines.join("\n");
155
152
  }
@@ -385,23 +382,6 @@ export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatc
385
382
  displayClarification: (content) => pi.sendMessage({ customType: "subagent_watchdog_clarification", content, display: true }, { deliverAs: "steer", triggerTurn: true }),
386
383
  });
387
384
 
388
- pi.registerMessageRenderer<WatchdogWarningDetails>(SUBAGENT_WATCHDOG_WARNING_TYPE, (message, renderOptions, theme) => {
389
- const details = message.details as WatchdogWarningDetails | undefined;
390
- if (!details?.summary || !details.evidence || !details.recommendedAction) {
391
- const content = typeof message.content === "string"
392
- ? message.content
393
- : message.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join("\n");
394
- return new Text(content, 0, 0);
395
- }
396
- return renderWatchdogWarning(details, renderOptions, theme);
397
- });
398
- pi.registerEntryRenderer<WatchdogWarningDetails>(SUBAGENT_WATCHDOG_WARNING_TYPE, (entry, renderOptions, theme) => {
399
- const details = entry.data as WatchdogWarningDetails | undefined;
400
- return details?.summary && details.evidence && details.recommendedAction
401
- ? renderWatchdogWarning(details, renderOptions, theme)
402
- : undefined;
403
- });
404
-
405
385
  pi.registerCommand("subagents-watchdog", {
406
386
  description: "Show or toggle the default-off subagent watchdog",
407
387
  handler: (args, ctx) => {
@@ -423,7 +403,7 @@ export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatc
423
403
  rememberContext(ctx);
424
404
  runtime.handleTurnEnd(event, ctx);
425
405
  });
426
- pi.on("input", (event) => { if (event.source !== "extension") runtime.handleUserInput(); });
406
+ pi.on("input", (event) => runtime.handleUserInput(event));
427
407
  pi.on("model_select", () => runtime.handleModelChange());
428
408
  pi.on("tool_result", (_event, ctx) => {
429
409
  rememberContext(ctx);
@@ -1,16 +1,10 @@
1
- import { Container, Spacer, Text, type Component } from "@earendil-works/pi-tui";
2
- import type { WatchdogWarningDetails } from "./types.ts";
3
-
4
- type WatchdogTheme = {
5
- fg(name: string, value: string): string;
6
- bold?(value: string): string;
7
- };
1
+ import type { WatchdogWarning, WatchdogWarningDetails } from "./types.ts";
8
2
 
9
3
  function titleCase(value: string): string {
10
4
  return value.split("-").map((part) => part ? `${part[0]?.toUpperCase()}${part.slice(1)}` : part).join(" ");
11
5
  }
12
6
 
13
- function stateLabels(warning: WatchdogWarningDetails): string[] {
7
+ export function stateLabels(warning: WatchdogWarning): string[] {
14
8
  const labels: string[] = [];
15
9
  if (warning.state === "displayed") labels.push("displayed");
16
10
  if (warning.stale || warning.state === "stale") labels.push("stale");
@@ -35,19 +29,3 @@ export function formatWatchdogWarningRenderText(warning: WatchdogWarningDetails)
35
29
  if (warning.stale || warning.state === "stale") lines.push("This warning arrived after the watchdog catch-up timeout.");
36
30
  return lines.join("\n");
37
31
  }
38
-
39
- export function renderWatchdogWarning(warning: WatchdogWarningDetails, options: { expanded: boolean }, theme: WatchdogTheme): Component {
40
- const text = formatWatchdogWarningRenderText(warning);
41
- const lines = text.split("\n");
42
- const container = new Container();
43
- const color = warning.severity === "blocker" ? "error" : "warning";
44
- const bold = theme.bold ?? ((value: string) => value);
45
- container.addChild(new Text(theme.fg(color, bold(lines[0] ?? "Subagent watchdog warning")), 0, 0));
46
- if (options.expanded) {
47
- container.addChild(new Spacer(1));
48
- for (const line of lines.slice(1)) container.addChild(new Text(theme.fg("dim", line), 0, 0));
49
- } else if (lines[1]) {
50
- container.addChild(new Text(theme.fg("dim", ` ⎿ ${lines[1]}`), 0, 0));
51
- }
52
- return container;
53
- }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { ExtensionContext, InputEvent } from "@earendil-works/pi-coding-agent";
3
3
  import { computeWatchdogRepoChangeSignature, eventIndicatesRepoEdit, type WatchdogRepoChangeSignature } from "./change-signature.ts";
4
4
  import { WatchdogEmissionGuard } from "./emission-guard.ts";
5
5
  import {
@@ -509,9 +509,11 @@ export class MainWatchdogRuntime {
509
509
  };
510
510
  }
511
511
 
512
- /** A real mid-stream user input can steer without emitting before_agent_start. */
513
- handleUserInput(): void {
512
+ /** A real user input sent while the agent streams reaches the loop without before_agent_start, so record it in scope here. */
513
+ handleUserInput(event: Pick<InputEvent, "text" | "source" | "streamingBehavior">): void {
514
+ if (this.disposed || event.source === "extension") return;
514
515
  if (this.displayClarification && this.configResult.config.clarification && (this.reviewing || this.waitingAtAgentEnd)) this.reset("new user input");
516
+ if (event.streamingBehavior) this.scope.addPrompt(event.text);
515
517
  }
516
518
 
517
519
  handleModelChange(): void {
@@ -850,7 +852,7 @@ export class MainWatchdogRuntime {
850
852
  const input = this.pendingDeltas.join(REVIEW_DELTA_SEPARATOR);
851
853
  const scopeBlock = this.scopeBlock();
852
854
  const changes = changeSignature?.changedPaths.length
853
- ? ["Changed repo paths:", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join("\n")
855
+ ? ["Changed repo paths: every dirty path in the working tree. Authorship is not verified; a path may predate this session or come from another session.", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join("\n")
854
856
  : "";
855
857
  const activity = this.activityTail ? `Recent delivered orchestration activity (oldest first; bounded observations, not a task board; waits/holds are not evidence of neglect):\n${this.activityTail}` : "";
856
858
  const contextPieces = [scopeBlock, changes, lspBlock, activity].filter(Boolean);
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { THINKING_LEVELS, type ThinkingLevel } from "../shared/model-info.ts";
4
4
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
5
+ import { withSettingsFileLease } from "../shared/settings-file-lease.ts";
5
6
  import {
6
7
  WATCHDOG_WARNING_SEVERITIES,
7
8
  type ResolvedWatchdogConfig,
@@ -461,24 +462,28 @@ function writeSettingsFile(settingsPath: string, settings: Record<string, unknow
461
462
  export function writeUserWatchdogEnabled(enabled: boolean): string {
462
463
  const settingsPath = getUserSettingsPath();
463
464
  const meta: ParseMeta = { scope: "user", path: settingsPath };
464
- const settings = readSettingsFileStrict(settingsPath);
465
- const watchdog = ensureWatchdogSettings(settings, meta);
466
- watchdog.enabled = enabled;
467
- targetSettingsObject(watchdog, { kind: "main" }, meta).enabled = enabled;
468
- return writeSettingsFile(settingsPath, settings);
465
+ return withSettingsFileLease(settingsPath, () => {
466
+ const settings = readSettingsFileStrict(settingsPath);
467
+ const watchdog = ensureWatchdogSettings(settings, meta);
468
+ watchdog.enabled = enabled;
469
+ targetSettingsObject(watchdog, { kind: "main" }, meta).enabled = enabled;
470
+ return writeSettingsFile(settingsPath, settings);
471
+ });
469
472
  }
470
473
 
471
474
  export function writeWatchdogModelSettings(input: WatchdogModelSettingsWrite): string {
472
475
  const settingsPath = settingsPathForWrite(input.scope, input.cwd);
473
476
  const meta: ParseMeta = { scope: input.scope, path: settingsPath };
474
- const settings = readSettingsFileStrict(settingsPath);
475
- const watchdog = ensureWatchdogSettings(settings, meta);
476
- const target = targetSettingsObject(watchdog, input.target, meta);
477
- if (input.model === null) delete target.model;
478
- else if (input.model !== undefined) target.model = input.model;
479
- if (input.thinking === null) delete target.thinking;
480
- else if (input.thinking !== undefined) target.thinking = input.thinking;
481
- return writeSettingsFile(settingsPath, settings);
477
+ return withSettingsFileLease(settingsPath, () => {
478
+ const settings = readSettingsFileStrict(settingsPath);
479
+ const watchdog = ensureWatchdogSettings(settings, meta);
480
+ const target = targetSettingsObject(watchdog, input.target, meta);
481
+ if (input.model === null) delete target.model;
482
+ else if (input.model !== undefined) target.model = input.model;
483
+ if (input.thinking === null) delete target.thinking;
484
+ else if (input.thinking !== undefined) target.thinking = input.thinking;
485
+ return writeSettingsFile(settingsPath, settings);
486
+ });
482
487
  }
483
488
 
484
489
  export function resolveWatchdogConfig(cwd: string, options: { session?: Record<string, unknown> } = {}): WatchdogSettingsResult {
@@ -84,8 +84,8 @@ function buildRecommendationText(ctx: ExtensionContext, runtime?: MainWatchdogRu
84
84
  "Subagent watchdog recommended model",
85
85
  recommendation.source === "configured" ? formatWatchdogRecommendation(recommendation) : `Recommended: ${recommendation.model}:${recommendation.thinking}`,
86
86
  `Reason: ${recommendation.reason}`,
87
- "Apply temporarily with subagent({ action: \"watchdog.configure\", scope: \"session\", model: \"recommended\" }).",
88
- "Persist with scope: \"project\" or scope: \"user\" only when the user asks for that scope.",
87
+ "Apply temporarily with subagent({ action: \"watchdog.configure\", model: \"recommended\", options: { scope: \"session\" } }).",
88
+ "Persist with options.scope \"project\" or \"user\" only when the user asks for that scope.",
89
89
  ].join("\n");
90
90
  }
91
91
 
@@ -887,7 +887,18 @@ const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
887
887
 
888
888
  function assertPortableWorkflowScript(source) {
889
889
  const wrapped = "(async () => {\n" + source + "\n})()";
890
- const ast = parse(wrapped, { ecmaVersion: "latest", sourceType: "script" });
890
+ let ast;
891
+ try {
892
+ ast = parse(wrapped, { ecmaVersion: "latest", sourceType: "script" });
893
+ } catch (error) {
894
+ // The wrapper adds one line before the script; report the script's own line.
895
+ if (isSyntaxError(error) && typeof error.message === "string") {
896
+ const message = error.message.replace(/\((\d+):(\d+)\)$/, (_match, line, column) => "(" + Math.max(1, Number(line) - 1) + ":" + column + ")");
897
+ if (typeof error.stack === "string") error.stack = error.stack.replace(error.message, message);
898
+ error.message = message;
899
+ }
900
+ throw error;
901
+ }
891
902
  const wrapper = workflowWrapperFunction(ast);
892
903
  walkWorkflowAst(wrapper.body, wrapper);
893
904
  }
@@ -1005,7 +1016,7 @@ parentPort.on("message", async (message) => {
1005
1016
  }
1006
1017
  if (message.type !== "start") return;
1007
1018
  try {
1008
- const sandbox = { runs, Promise: workflowPromise, emit(value) { const emittedValue = unwrapRunsAllResults(value); assertJsonValue(emittedValue); parentPort.postMessage({ type: "emit", value: emittedValue }); }, console: capturedConsole };
1019
+ const sandbox = { runs, Promise: workflowPromise, emit(value) { const unwrapped = unwrapRunsAllResults(value); const emittedValue = unwrapped === undefined ? null : omitUndefinedWorkflowValues(unwrapped); assertJsonValue(emittedValue); parentPort.postMessage({ type: "emit", value: emittedValue }); }, console: capturedConsole };
1009
1020
  if (message.stateEnabled) sandbox.state = state;
1010
1021
  const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
1011
1022
  contextObjectPrototype = vm.runInContext("Object.prototype", context);
@@ -1015,7 +1026,7 @@ parentPort.on("message", async (message) => {
1015
1026
  let compiled;
1016
1027
  try {
1017
1028
  assertPortableWorkflowScript(message.script);
1018
- compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js" });
1029
+ compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js", lineOffset: -1 });
1019
1030
  } catch (error) {
1020
1031
  parentPort.postMessage({ type: "error", errorKind: "validation", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
1021
1032
  return;
@@ -1027,7 +1038,9 @@ parentPort.on("message", async (message) => {
1027
1038
  let stopWorkflowPromiseHook;
1028
1039
  let value;
1029
1040
  try {
1030
- Object.defineProperty(nativePromisePrototype, "then", {
1041
+ // Some hosts freeze built-ins in every realm, which makes then read-only. The promise hooks
1042
+ // below still track observation, so skip the wrapper rather than fail every workflow.
1043
+ if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", {
1031
1044
  ...nativeThenDescriptor,
1032
1045
  value: function workflowPromiseThen(...args) {
1033
1046
  if (isDirectWorkflowScriptPromiseHandlerCall() || suppressNativePromiseConsumption > 0) {
@@ -1067,7 +1080,7 @@ parentPort.on("message", async (message) => {
1067
1080
  stopWorkflowPromiseHook?.();
1068
1081
  } finally {
1069
1082
  try {
1070
- Object.defineProperty(nativePromisePrototype, "then", nativeThenDescriptor);
1083
+ if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", nativeThenDescriptor);
1071
1084
  } finally {
1072
1085
  topLevelWorkflowPromise = undefined;
1073
1086
  activeNativePromises.length = 0;
@@ -1967,7 +1980,8 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
1967
1980
  ? node.arguments[1]
1968
1981
  : undefined;
1969
1982
  if (boundaryValue) {
1970
- const message = definitelyNonJson(boundaryValue);
1983
+ // emit normalizes undefined like return; state.set values must already be JSON.
1984
+ const message = definitelyNonJson(boundaryValue, Array.isArray(node.arguments) && boundaryValue === node.arguments[0]);
1971
1985
  if (message) errors.push({ message: `workflowScript boundary value is invalid: ${message}.`, ...nodeLocation(boundaryValue) });
1972
1986
  }
1973
1987
  });
@@ -161,6 +161,16 @@ function resolveRunCi(args: Readonly<Record<string, unknown>>): ReturnType<Workf
161
161
  };
162
162
  }
163
163
 
164
+ function resolveParallel(args: Readonly<Record<string, unknown>>): ReturnType<WorkflowResourceDefinition["resolve"]> {
165
+ const unsupported = Object.keys(args).filter((key) => key !== "tasks");
166
+ if (unsupported.length > 0) return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task }, ...].` };
167
+ try {
168
+ return { script: buildStructuredWorkflowScript("tasks", args.tasks, undefined) };
169
+ } catch (error) {
170
+ return { error: `workflow 'parallel' args.${error instanceof Error ? error.message : String(error)}` };
171
+ }
172
+ }
173
+
164
174
  function resolveReview(args: Readonly<Record<string, unknown>>): ReturnType<WorkflowResourceDefinition["resolve"]> {
165
175
  const unsupported = Object.keys(args).filter((key) => key !== "task");
166
176
  if (unsupported.length > 0) return { error: `workflow 'review' args contain unsupported fields: ${unsupported.join(", ")}.` };
@@ -174,6 +184,7 @@ function resolveReview(args: Readonly<Record<string, unknown>>): ReturnType<Work
174
184
  const WORKFLOW_RESOURCES: readonly WorkflowResourceDefinition[] = [
175
185
  { name: "review", version: 1, resolve: resolveReview },
176
186
  { name: "run-ci", version: 1, resolve: resolveRunCi },
187
+ { name: "parallel", version: 1, resolve: resolveParallel },
177
188
  ];
178
189
 
179
190
  function findWorkflowResource(name: string): WorkflowResourceDefinition | undefined {