@xzzpig/pi-subagents 0.25.0 → 0.25.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,74 @@
1
+ /** Input identities are retained so callers can attach domain-specific styling. */
2
+ export interface DiffLineLike {
3
+ kind: "line";
4
+ lineKind: "add" | "remove" | "context";
5
+ hunkIndex: number;
6
+ }
7
+ export interface DiffMetaLike {
8
+ kind: "meta" | "hunk" | "file";
9
+ hunkIndex: number;
10
+ }
11
+ export interface DiffPair<L, M> {
12
+ left?: L;
13
+ right?: L;
14
+ meta?: M;
15
+ hunkIndex: number | null;
16
+ }
17
+ export interface DiffRenderedRow {
18
+ text: string;
19
+ hunkIndex: number | null;
20
+ }
21
+ /** Pair consecutive removal/addition blocks without changing either side's order. */
22
+ export declare function pairDiffEntries<L extends DiffLineLike, M extends DiffMetaLike>(entries: readonly (L | M)[]): DiffPair<L, M>[];
23
+ export interface DiffColumns {
24
+ leftWidth: number;
25
+ rightWidth: number;
26
+ }
27
+ /** The separator may already be styled; visibleWidth ignores its ANSI SGR. */
28
+ export declare function measureDiffColumns(width: number, separator: string, minimumColumnWidth?: number): DiffColumns | undefined;
29
+ export interface DiffPairLayout<L, M> extends DiffColumns {
30
+ separator: string;
31
+ /** Callbacks return already bounded and styled visual cells. */
32
+ renderCell(line: L | undefined, side: "left" | "right", width: number): string[];
33
+ renderBlank(side: "left" | "right", width: number): string;
34
+ renderMeta(meta: M): DiffRenderedRow[];
35
+ }
36
+ /** Shared split-row compositor; caller owns gutters, theme, and metadata styling. */
37
+ export declare function renderPairedDiffRows<L, M>(rows: readonly DiffPair<L, M>[], layout: DiffPairLayout<L, M>): DiffRenderedRow[];
38
+ export interface DiffTextLine extends DiffLineLike {
39
+ content: string;
40
+ }
41
+ export interface DiffTextMeta extends DiffMetaLike {
42
+ content: string;
43
+ }
44
+ export type DiffTextEntry = DiffTextLine | DiffTextMeta;
45
+ export interface DiffTextTheme {
46
+ fg(color: string, text: string): string;
47
+ }
48
+ export interface DiffTextOptions {
49
+ width: number;
50
+ mode?: "auto" | "split" | "unified";
51
+ splitMinWidth?: number;
52
+ theme?: DiffTextTheme;
53
+ oldLabel?: string;
54
+ newLabel?: string;
55
+ }
56
+ /** Treat data as text, not terminal instructions. Styles supplied by a theme are applied later. */
57
+ export declare function sanitizeDiffText(value: string): string;
58
+ export interface AnchoredDiffRow {
59
+ text: string;
60
+ /** Source entry indexes represented by this row, including both sides of a pair. */
61
+ entryIndexes: readonly number[];
62
+ /** Wrapped visual row within the source entry or pair. */
63
+ part: number;
64
+ /** Start positions in sanitized source text for each visible entry. */
65
+ sourcePositions: readonly {
66
+ entryIndex: number;
67
+ offset: number;
68
+ fragment?: number;
69
+ }[];
70
+ }
71
+ /** Render text plus source anchors for a viewport that survives resize/reflow. */
72
+ export declare function renderAnchoredDiffEntries(entries: readonly DiffTextEntry[], options: DiffTextOptions): AnchoredDiffRow[];
73
+ /** Render sanitized semantic text entries in a standalone split/unified presentation. */
74
+ export declare function renderDiffEntries(entries: readonly DiffTextEntry[], options: DiffTextOptions): string[];
@@ -0,0 +1,355 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ /** Pair consecutive removal/addition blocks without changing either side's order. */
3
+ export function pairDiffEntries(entries) {
4
+ const rows = [];
5
+ for (let index = 0; index < entries.length;) {
6
+ const entry = entries[index];
7
+ if (!entry)
8
+ break;
9
+ if (entry.kind !== "line") {
10
+ rows.push({ meta: entry, hunkIndex: entry.hunkIndex || null });
11
+ index++;
12
+ continue;
13
+ }
14
+ if (entry.lineKind === "remove") {
15
+ const removed = [];
16
+ const added = [];
17
+ for (; index < entries.length;) {
18
+ const item = entries[index];
19
+ if (!item || item.kind !== "line" || item.lineKind !== "remove")
20
+ break;
21
+ removed.push(item);
22
+ index++;
23
+ }
24
+ for (; index < entries.length;) {
25
+ const item = entries[index];
26
+ if (!item || item.kind !== "line" || item.lineKind !== "add")
27
+ break;
28
+ added.push(item);
29
+ index++;
30
+ }
31
+ for (let i = 0; i < Math.max(removed.length, added.length); i++) {
32
+ const left = removed[i];
33
+ const right = added[i];
34
+ rows.push({
35
+ left,
36
+ right,
37
+ hunkIndex: left?.hunkIndex ?? right?.hunkIndex ?? null,
38
+ });
39
+ }
40
+ continue;
41
+ }
42
+ const line = entry;
43
+ rows.push(entry.lineKind === "add"
44
+ ? { right: line, hunkIndex: entry.hunkIndex || null }
45
+ : { left: line, right: line, hunkIndex: entry.hunkIndex || null });
46
+ index++;
47
+ }
48
+ return rows;
49
+ }
50
+ /** The separator may already be styled; visibleWidth ignores its ANSI SGR. */
51
+ export function measureDiffColumns(width, separator, minimumColumnWidth = 24) {
52
+ const available = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
53
+ const minimum = Math.max(1, Math.floor(minimumColumnWidth));
54
+ const separatorWidth = visibleWidth(separator);
55
+ if (available < minimum * 2 + separatorWidth)
56
+ return undefined;
57
+ const leftWidth = Math.floor((available - separatorWidth) / 2);
58
+ return { leftWidth, rightWidth: available - separatorWidth - leftWidth };
59
+ }
60
+ /** Shared split-row compositor; caller owns gutters, theme, and metadata styling. */
61
+ export function renderPairedDiffRows(rows, layout) {
62
+ const output = [];
63
+ for (const row of rows) {
64
+ if (row.meta !== undefined) {
65
+ for (const item of layout.renderMeta(row.meta))
66
+ output.push(item);
67
+ continue;
68
+ }
69
+ const left = layout.renderCell(row.left, "left", layout.leftWidth);
70
+ const right = layout.renderCell(row.right, "right", layout.rightWidth);
71
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
72
+ const leftCell = left[index] ?? layout.renderBlank("left", layout.leftWidth);
73
+ const rightCell = right[index] ?? layout.renderBlank("right", layout.rightWidth);
74
+ output.push({
75
+ text: `${leftCell}${layout.separator}${rightCell}`,
76
+ hunkIndex: row.hunkIndex,
77
+ });
78
+ }
79
+ }
80
+ return output;
81
+ }
82
+ /** Treat data as text, not terminal instructions. Styles supplied by a theme are applied later. */
83
+ export function sanitizeDiffText(value) {
84
+ return value
85
+ .replace(/\u001b[\]P_^X](?:[^\u001b\u0007]|\u001b(?!\\))*(?:\u0007|\u001b\\|$)/g, "")
86
+ .replace(/[\u0090\u009d\u009e\u009f][^\u009c\u0007]*(?:\u009c|\u0007|$)/g, "")
87
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "")
88
+ .replace(/\u009b[0-?]*[ -/]*[@-~]/g, "")
89
+ .replace(/\u001b[()][0-9A-Za-z]/g, "")
90
+ .replace(/\u001b[@-_]/g, "")
91
+ .replace(/\r\n?/g, "\n")
92
+ .replace(/\t/g, " ")
93
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "");
94
+ }
95
+ function safeWidth(width) {
96
+ return Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
97
+ }
98
+ function fitCell(text, width) {
99
+ const fitted = visibleWidth(text) > width ? truncateToWidth(text, width, "") : text;
100
+ return fitted + " ".repeat(Math.max(0, width - visibleWidth(fitted)));
101
+ }
102
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
103
+ /** A physical row's original spaces must not be mistaken for cell padding. */
104
+ function markBoundarySpaces(value) {
105
+ return value.replace(/ +$/g, (spaces) => "␠".repeat(spaces.length));
106
+ }
107
+ /** Detect each run once; repeated rescanning of a long "<<<<..." suffix is quadratic. */
108
+ function dangerousPrefixPositions(line, width) {
109
+ const result = new Set();
110
+ let run = -1;
111
+ for (const part of graphemes.segment(line)) {
112
+ if (part.segment === "<") {
113
+ if (run < 0)
114
+ run = part.index;
115
+ continue;
116
+ }
117
+ if (run >= 0) {
118
+ const next = part.segment;
119
+ const dangerous = line.startsWith("U+", part.index) ||
120
+ next === "␠" ||
121
+ (/\p{White_Space}/u.test(next) && next !== " ") ||
122
+ visibleWidth(next) > width;
123
+ if (dangerous)
124
+ for (let i = run; i < part.index; i++)
125
+ result.add(i);
126
+ run = -1;
127
+ }
128
+ }
129
+ return result;
130
+ }
131
+ /** Wrap plain text with source offsets; oversized graphemes use explicit,
132
+ * reversible Unicode notation rather than an indistinguishable ellipsis. */
133
+ function wrapDataWithOffsets(text, width) {
134
+ if (width <= 0)
135
+ return [{ text: "", offset: 0 }];
136
+ const result = [];
137
+ let base = 0;
138
+ for (const line of sanitizeDiffText(text).split("\n")) {
139
+ const ascii = /^[\x20-\x7e]*$/.test(line);
140
+ // ASCII can only require escaping when a literal U+ marker exists; this
141
+ // check avoids a grapheme pass on the common long-text fast path.
142
+ const dangerousPrefixes = ascii && !line.includes("U+")
143
+ ? new Set()
144
+ : dangerousPrefixPositions(line, width);
145
+ if (ascii && dangerousPrefixes.size === 0) {
146
+ if (!line)
147
+ result.push({ text: "", offset: base });
148
+ else
149
+ for (let i = 0; i < line.length; i += width)
150
+ result.push({
151
+ text: markBoundarySpaces(line.slice(i, i + width)),
152
+ offset: base + i,
153
+ });
154
+ base += line.length + 1;
155
+ continue;
156
+ }
157
+ let chunk = "", columns = 0, offset = 0;
158
+ const flush = () => {
159
+ if (chunk)
160
+ result.push({ text: markBoundarySpaces(chunk), offset: base + offset });
161
+ chunk = "";
162
+ columns = 0;
163
+ };
164
+ for (const part of graphemes.segment(line)) {
165
+ const size = visibleWidth(part.segment);
166
+ if (columns + size > width && chunk)
167
+ flush();
168
+ const literalPrefix = part.segment === "<" && dangerousPrefixes.has(part.index);
169
+ const literalSpaceMarker = part.segment === "␠";
170
+ const nonAsciiSpace = part.segment !== " " && /\p{White_Space}/u.test(part.segment);
171
+ if (size > width ||
172
+ literalPrefix ||
173
+ literalSpaceMarker ||
174
+ nonAsciiSpace) {
175
+ if (chunk)
176
+ flush();
177
+ const escaped = literalPrefix
178
+ ? "<<"
179
+ : literalSpaceMarker
180
+ ? "<U+2420>"
181
+ : "<" +
182
+ Array.from(part.segment, (c) => `U+${c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`).join(" ") +
183
+ ">";
184
+ for (let i = 0; i < escaped.length; i += width)
185
+ result.push({
186
+ text: escaped.slice(i, i + width),
187
+ offset: base + part.index,
188
+ fragment: i,
189
+ });
190
+ }
191
+ else {
192
+ if (!chunk)
193
+ offset = part.index;
194
+ chunk += part.segment;
195
+ columns += size;
196
+ }
197
+ }
198
+ flush();
199
+ if (!line)
200
+ result.push({ text: "", offset: base });
201
+ base += line.length + 1;
202
+ }
203
+ return result;
204
+ }
205
+ function wrapData(text, width) {
206
+ return wrapDataWithOffsets(text, width).map((row) => row.text);
207
+ }
208
+ function wrapOffsets(text, width) {
209
+ return wrapDataWithOffsets(text, width).map(({ offset, fragment }) => ({
210
+ offset,
211
+ fragment,
212
+ }));
213
+ }
214
+ function separateMarker(line, width) {
215
+ if (width < 4)
216
+ return true;
217
+ if (/^[\x20-\x7e]*$/.test(line.content))
218
+ return false;
219
+ for (const { segment } of graphemes.segment(sanitizeDiffText(line.content))) {
220
+ const columns = visibleWidth(segment);
221
+ if (columns > width - 2 && columns <= width)
222
+ return true;
223
+ }
224
+ return false;
225
+ }
226
+ function cellOffsets(line, width) {
227
+ const separate = separateMarker(line, width);
228
+ const marker = separate && line.lineKind !== "context"
229
+ ? [{ offset: 0, fragment: -1 }]
230
+ : [];
231
+ return [
232
+ ...marker,
233
+ ...wrapOffsets(line.content, separate ? width : width - 2),
234
+ ];
235
+ }
236
+ function color(theme, name, text) {
237
+ return theme ? theme.fg(name, text) : text;
238
+ }
239
+ function renderTextCell(line, width, theme) {
240
+ if (!line)
241
+ return [" ".repeat(width)];
242
+ let sign = " ";
243
+ let style = "muted";
244
+ if (line.lineKind === "remove") {
245
+ sign = "- ";
246
+ style = "error";
247
+ }
248
+ else if (line.lineKind === "add") {
249
+ sign = "+ ";
250
+ style = "success";
251
+ }
252
+ // Below four columns, put the marker on its own row so a two-cell
253
+ // grapheme can still be displayed rather than eaten by the prefix.
254
+ if (separateMarker(line, width)) {
255
+ const marker = sign.trim()
256
+ ? [fitCell(color(theme, style, sign.trim()), width)]
257
+ : [];
258
+ return [
259
+ ...marker,
260
+ ...wrapData(line.content, width).map((chunk) => fitCell(color(theme, style, chunk), width)),
261
+ ];
262
+ }
263
+ const bodyWidth = width - 2;
264
+ return wrapData(line.content, bodyWidth).map((chunk, index) => fitCell(color(theme, style, (index === 0 ? sign : " ") + chunk), width));
265
+ }
266
+ /** Render text plus source anchors for a viewport that survives resize/reflow. */
267
+ export function renderAnchoredDiffEntries(entries, options) {
268
+ const width = safeWidth(options.width);
269
+ if (width === 0)
270
+ return [];
271
+ const separator = color(options.theme, "dim", " │ ");
272
+ const columns = measureDiffColumns(width, separator);
273
+ const split = options.mode === "split"
274
+ ? columns !== undefined
275
+ : options.mode !== "unified" &&
276
+ width >= (options.splitMinWidth ?? 120) &&
277
+ columns !== undefined;
278
+ if (!split || !columns) {
279
+ return entries.flatMap((entry, entryIndex) => {
280
+ const lines = entry.kind === "line"
281
+ ? renderTextCell(entry, width, options.theme)
282
+ : wrapData(entry.content, width).map((line) => fitCell(color(options.theme, "dim", line), width));
283
+ const offsets = entry.kind === "line"
284
+ ? cellOffsets(entry, width)
285
+ : wrapOffsets(entry.content, width);
286
+ return lines.map((text, part) => ({
287
+ text,
288
+ entryIndexes: [entryIndex],
289
+ part,
290
+ sourcePositions: [{ entryIndex, ...(offsets[part] ?? { offset: 0 }) }],
291
+ }));
292
+ });
293
+ }
294
+ const indexed = entries.map((entry, entryIndex) => ({
295
+ ...entry,
296
+ entryIndex,
297
+ }));
298
+ const rows = pairDiffEntries(indexed);
299
+ const header = fitCell(color(options.theme, "muted", sanitizeDiffText(options.oldLabel ?? "旧值").replace(/\n/g, " ")), columns.leftWidth) +
300
+ separator +
301
+ fitCell(color(options.theme, "muted", sanitizeDiffText(options.newLabel ?? "新值").replace(/\n/g, " ")), columns.rightWidth);
302
+ const output = [
303
+ { text: header, entryIndexes: [], part: 0, sourcePositions: [] },
304
+ ];
305
+ for (const row of rows) {
306
+ const left = row.left
307
+ ? renderTextCell(row.left, columns.leftWidth, options.theme)
308
+ : [];
309
+ const right = row.right
310
+ ? renderTextCell(row.right, columns.rightWidth, options.theme)
311
+ : [];
312
+ const leftOffsets = row.left
313
+ ? cellOffsets(row.left, columns.leftWidth)
314
+ : [];
315
+ const rightOffsets = row.right
316
+ ? cellOffsets(row.right, columns.rightWidth)
317
+ : [];
318
+ const metaOffsets = row.meta ? wrapOffsets(row.meta.content, width) : [];
319
+ const rendered = renderPairedDiffRows([row], {
320
+ ...columns,
321
+ separator,
322
+ renderCell: (_line, side) => (side === "left" ? left : right),
323
+ renderBlank: (_side, cellWidth) => " ".repeat(cellWidth),
324
+ renderMeta: (meta) => wrapData(meta.content, width).map((text) => ({
325
+ text: fitCell(color(options.theme, "dim", text), width),
326
+ hunkIndex: meta.hunkIndex || null,
327
+ })),
328
+ });
329
+ for (const [part, item] of rendered.entries()) {
330
+ // A blank continuation does not represent that side: anchoring to it
331
+ // would jump to an unrelated short value after split/unified reflow.
332
+ const entryIndexes = [
333
+ row.meta?.entryIndex,
334
+ part < left.length ? row.left?.entryIndex : undefined,
335
+ part < right.length ? row.right?.entryIndex : undefined,
336
+ ]
337
+ .filter((index) => index !== undefined)
338
+ .filter((index, position, indexes) => indexes.indexOf(index) === position);
339
+ const sourcePositions = entryIndexes.map((entryIndex) => ({
340
+ entryIndex,
341
+ ...(entryIndex === row.meta?.entryIndex
342
+ ? (metaOffsets[part] ?? { offset: 0 })
343
+ : entryIndex === row.left?.entryIndex
344
+ ? (leftOffsets[part] ?? { offset: 0 })
345
+ : (rightOffsets[part] ?? { offset: 0 })),
346
+ }));
347
+ output.push({ text: item.text, entryIndexes, part, sourcePositions });
348
+ }
349
+ }
350
+ return output;
351
+ }
352
+ /** Render sanitized semantic text entries in a standalone split/unified presentation. */
353
+ export function renderDiffEntries(entries, options) {
354
+ return renderAnchoredDiffEntries(entries, options).map((row) => row.text);
355
+ }
@@ -18,6 +18,10 @@
18
18
  "LICENSE"
19
19
  ],
20
20
  "exports": {
21
+ "./diff": {
22
+ "types": "./dist/src/diff.d.ts",
23
+ "default": "./src/diff.ts"
24
+ },
21
25
  "./transcript": {
22
26
  "types": "./dist/src/transcript.d.ts",
23
27
  "default": "./dist/src/transcript.js"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@xzzpig/pi-subagents",
4
- "version": "0.25.0",
4
+ "version": "0.25.2",
5
5
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
6
6
  "author": "Nico Bailon",
7
7
  "license": "MIT",
@@ -137,6 +137,7 @@
137
137
  }
138
138
  },
139
139
  "pi": {
140
+ "changelogPath": "./FORK-CHANGELOG.md",
140
141
  "extensions": [
141
142
  "./bundle/index.js"
142
143
  ],
@@ -11,6 +11,7 @@ import { DEFAULT_CONTROL_CONFIG, buildControlEvent, claimControlNotification, de
11
11
  import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, getTerminalAssistantStopReason, TRUNCATED_RESPONSE_ERROR, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
12
12
  import { resolveSkillsWithFallback } from "../../agents/skills.js";
13
13
  import { createPartialOutputTracker, formatPartialOutput } from "../shared/partial-output.js";
14
+ import { createToolResultHandler } from "./fork-tool-result-handler.js";
14
15
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.js";
15
16
  import { preflightLaunchCwd } from "../shared/launch-cwd.js";
16
17
  import { createJsonlWriter } from "../../shared/jsonl-writer.js";
@@ -31,11 +32,11 @@ import { planAbortRecovery } from "../shared/abort-recovery.js";
31
32
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
32
33
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, isSettlementFatalOutputError, resolveSingleOutput, validateFileOnlyOutputMode } from "../shared/single-output.js";
33
34
  import { formatSubagentModelVerificationError, isContextOverflow, resolveModelSelection, } from "../shared/model-resolution.js";
34
- import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
35
+ import { createMutatingFailureState, isMutatingTool, nextLongRunningTrigger, resolveCurrentPath, } from "../shared/long-running-guard.js";
35
36
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, captureStagedIndexBaseline, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput, typedVerifyOutput } from "../shared/acceptance.js";
36
37
  import { PROMPT_REDACTED } from "../../shared/utils.js";
37
38
  import { attachContractProjections, isAgentContract } from "../shared/agent-contract.js";
38
- import { initialToolBudgetState, isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.js";
39
+ import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.js";
39
40
  import { resolveWatchdogConfig } from "../../watchdog/settings.js";
40
41
  import { resolveLaunchBinding } from "../../shared/launch-contract.js";
41
42
  import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.js";
@@ -756,12 +757,11 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
756
757
  // Pi's parallel tool execution emits every tool_execution_start before the first result message,
757
758
  // so results are matched to their call by toolCallId; the last-started slot covers events without one.
758
759
  const pendingToolResultsByCallId = new Map();
759
- let pendingToolResult;
760
+ const pendingToolState = { current: undefined };
760
761
  // Pi host versions may represent one tool result as either a dedicated
761
762
  // tool_result_end event or a message_end whose message role is toolResult.
762
763
  // Remember correlated ids so normalizing both forms cannot duplicate output.
763
764
  const handledToolResultIds = new Set();
764
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
765
765
  let activeToolSequence = 0;
766
766
  const activeToolCalls = new Map();
767
767
  const activeToolKeysByName = new Map();
@@ -966,69 +966,21 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
966
966
  // deliver the same result either as a tool_result_end event or as a
967
967
  // message_end whose message role is toolResult; both funnel through here
968
968
  // so one result updates budget, output, and mutating-failure state once.
969
- const handleToolResult = (message, completion, now) => {
970
- const rawCallId = completion.toolCallId ?? message.toolCallId;
971
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
972
- if (callId) {
973
- if (handledToolResultIds.has(callId))
974
- return;
975
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
976
- const oldest = handledToolResultIds.values().next().value;
977
- if (typeof oldest === "string")
978
- handledToolResultIds.delete(oldest);
979
- }
980
- handledToolResultIds.add(callId);
981
- }
982
- result.messages.push(message);
983
- const resultText = extractTextFromContent(message.content);
984
- const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : undefined;
985
- if (callId && keyedSnapshot)
986
- pendingToolResultsByCallId.delete(callId);
987
- const toolSnapshot = keyedSnapshot ?? pendingToolResult;
988
- if (!keyedSnapshot || pendingToolResult === keyedSnapshot)
989
- pendingToolResult = undefined;
990
- // The result event's own tool name is authoritative; the snapshot is a fallback.
991
- const resultToolName = completion.toolName ?? message.toolName;
992
- const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
993
- ? resultToolName
994
- : undefined) ?? toolSnapshot?.tool;
995
- const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
996
- if (options.toolBudget && budgetBlocked) {
997
- result.toolBudgetBlocked = true;
998
- result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
999
- }
1000
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
1001
- // Pi 1.2+: a successful contact_supervisor progress_update call carries
1002
- // its text back through the result message. Publish the matching
1003
- // snapshot's text so the widget shows the latest successful update.
1004
- const messageToolName = message.toolName;
1005
- if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
1006
- progress.progressText = toolSnapshot.progressText;
1007
- progress.progressUpdatedAt = now;
1008
- }
1009
- if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
1010
- recordMutatingFailure(mutatingFailures, {
1011
- tool: toolSnapshot.tool,
1012
- path: toolSnapshot.path,
1013
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1014
- ts: now,
1015
- }, mutatingFailureWindowMs);
1016
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
1017
- emitNeedsAttention(now, {
1018
- message: `${agent.name} needs attention after repeated mutating tool failures`,
1019
- reason: "tool_failures",
1020
- currentTool: toolSnapshot.tool,
1021
- currentPath: toolSnapshot.path,
1022
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1023
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
1024
- });
1025
- }
1026
- }
1027
- else if (toolSnapshot?.mutates) {
1028
- resetMutatingFailureState(mutatingFailures);
1029
- }
1030
- fireUpdate();
1031
- };
969
+ const handleToolResult = createToolResultHandler({
970
+ result,
971
+ progress,
972
+ options,
973
+ agentName: agent.name,
974
+ handledToolResultIds,
975
+ pendingToolResultsByCallId,
976
+ pendingToolState,
977
+ mutatingFailures,
978
+ mutatingFailureWindowMs,
979
+ controlConfig,
980
+ appendRecentOutput,
981
+ fireUpdate,
982
+ emitNeedsAttention,
983
+ });
1032
984
  const processEvent = (evt) => {
1033
985
  if (lifecycleFinished)
1034
986
  return;
@@ -1136,9 +1088,9 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1136
1088
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result.toolBudget?.blockedTool);
1137
1089
  }
1138
1090
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1139
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
1091
+ pendingToolState.current = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
1140
1092
  if (typeof evt.toolCallId === "string" && evt.toolCallId)
1141
- pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
1093
+ pendingToolResultsByCallId.set(evt.toolCallId, pendingToolState.current);
1142
1094
  fireUpdate();
1143
1095
  }
1144
1096
  if (evt.type === "tool_execution_end") {
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Fork-only tool-result handler for a foreground subagent run.
3
+ *
4
+ * Why this file exists: upstream `execution.ts` has no `handleToolResult`; the
5
+ * fork added ~60 lines of tool-result bookkeeping (budget blocking, mutating
6
+ * failure escalation, supervisor progress publication) inside the run closure.
7
+ * It only reads/writes state the run already owns, so the handler lives here and
8
+ * the upstream run keeps one factory call.
9
+ *
10
+ * `handledToolResultIds` is bounded so a long run cannot grow it without limit;
11
+ * the oldest id is evicted first, which only risks re-processing results the
12
+ * child itself re-sends, never dropping a live one.
13
+ */
14
+ import type { Message } from "@earendil-works/pi-ai";
15
+ import type { AgentProgress, RunSyncOptions, SingleResult } from "../../shared/types.ts";
16
+ import { createMutatingFailureState } from "../shared/long-running-guard.ts";
17
+ import type { ControlEvent } from "../../shared/types.ts";
18
+ export type PendingToolResult = {
19
+ tool: string;
20
+ path?: string;
21
+ mutates: boolean;
22
+ startedAt?: number;
23
+ progressText?: string;
24
+ };
25
+ type MutatingFailureState = ReturnType<typeof createMutatingFailureState>;
26
+ export interface ToolResultHandlerDeps {
27
+ result: SingleResult;
28
+ progress: AgentProgress;
29
+ options: RunSyncOptions;
30
+ /** Name used in the needs-attention message. */
31
+ agentName: string;
32
+ handledToolResultIds: Set<string>;
33
+ pendingToolResultsByCallId: Map<string, PendingToolResult>;
34
+ /** Unkeyed snapshot taken at `tool_call`; the handler consumes it. */
35
+ pendingToolState: {
36
+ current: PendingToolResult | undefined;
37
+ };
38
+ mutatingFailures: MutatingFailureState;
39
+ mutatingFailureWindowMs: number;
40
+ controlConfig: {
41
+ failedToolAttemptsBeforeAttention: number;
42
+ };
43
+ appendRecentOutput(progress: AgentProgress, lines: string[]): void;
44
+ fireUpdate(): void;
45
+ emitNeedsAttention(now: number, input: {
46
+ message?: string;
47
+ reason?: ControlEvent["reason"];
48
+ recentFailureSummary?: string;
49
+ currentTool?: string;
50
+ toolCallId?: string;
51
+ hasCommandController?: boolean;
52
+ currentPath?: string;
53
+ currentToolDurationMs?: number;
54
+ }): boolean;
55
+ }
56
+ export declare function createToolResultHandler(deps: ToolResultHandlerDeps): (message: Message, completion: {
57
+ toolCallId?: unknown;
58
+ toolName?: unknown;
59
+ }, now: number) => void;
60
+ export {};