@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.
@@ -25,7 +25,7 @@ import {
25
25
  updateSteeringTarget,
26
26
  waitForSteeringAction,
27
27
  workflowAsyncChildSteeringGuidance
28
- } from "./chunk-IUDEI6FJ.js";
28
+ } from "./chunk-MMJQMPOK.js";
29
29
  import {
30
30
  PLACED_RESTORE_UNSUPPORTED,
31
31
  formatHerdrMachineRunnerUnsupported,
@@ -119,7 +119,7 @@ import {
119
119
  workflowScriptDigest,
120
120
  workflowStopCause,
121
121
  writeWorkflowReceipt
122
- } from "./chunk-IJWITCC6.js";
122
+ } from "./chunk-6FREVFTI.js";
123
123
  import {
124
124
  HERDR_PROJECT_PANE_ACTIONS,
125
125
  handleHerdrProjectPaneAction
@@ -4301,6 +4301,293 @@ function formatPartialOutput(text, cause) {
4301
4301
  ${text}`;
4302
4302
  }
4303
4303
 
4304
+ // src/runs/shared/long-running-guard.ts
4305
+ var MUTATING_BASH_PATTERNS = [
4306
+ /(^|[;&|()\s])rm\s+/,
4307
+ /(^|[;&|()\s])mv\s+/,
4308
+ /(^|[;&|()\s])cp\s+/,
4309
+ /(^|[;&|()\s])mkdir\s+/,
4310
+ /(^|[;&|()\s])touch\s+/,
4311
+ /(^|[;&|()\s])git\s+apply\b/,
4312
+ /(^|[;&|()\s])patch\s+/,
4313
+ /(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,
4314
+ /(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,
4315
+ /(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,
4316
+ /\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,
4317
+ /\bwrite_text\s*\(/,
4318
+ /\bopen\s*\([^)]*,\s*["'][wa]/
4319
+ ];
4320
+ function resolveCurrentPath(toolName, args) {
4321
+ if (!toolName || !args) return void 0;
4322
+ const direct = ["path", "file", "filename", "target", "cwd"];
4323
+ for (const key of direct) {
4324
+ const value = args[key];
4325
+ if (typeof value === "string" && value.trim()) return value.trim();
4326
+ }
4327
+ if (toolName === "bash") {
4328
+ const command = typeof args.command === "string" ? args.command : void 0;
4329
+ if (!command) return void 0;
4330
+ return firstWrittenFile(command);
4331
+ }
4332
+ return void 0;
4333
+ }
4334
+ function readShellWord(command, start) {
4335
+ let word = "";
4336
+ let quote;
4337
+ let i = start;
4338
+ for (; i < command.length; i++) {
4339
+ const char = command[i];
4340
+ if (quote) {
4341
+ if (char === quote) quote = void 0;
4342
+ else if (char === "\\" && quote === '"' && /[$`"\\\n]/.test(command[i + 1] ?? "")) word += command[++i];
4343
+ else word += char;
4344
+ continue;
4345
+ }
4346
+ if (char === "'" || char === '"') quote = char;
4347
+ else if (char === "\\" && i + 1 < command.length) word += command[++i];
4348
+ else if (/[\s;&|()<>]/.test(char)) break;
4349
+ else word += char;
4350
+ }
4351
+ return { word, end: i };
4352
+ }
4353
+ function firstWrittenFile(command) {
4354
+ let quote;
4355
+ for (let i = 0; i < command.length; i++) {
4356
+ const char = command[i];
4357
+ if (quote) {
4358
+ if (char === quote) quote = void 0;
4359
+ else if (char === "\\" && quote === '"') i++;
4360
+ continue;
4361
+ }
4362
+ if (char === "'" || char === '"') {
4363
+ quote = char;
4364
+ continue;
4365
+ }
4366
+ if (char === "\\") {
4367
+ i++;
4368
+ continue;
4369
+ }
4370
+ const isTee = command.startsWith("tee", i) && (i === 0 || /[\s|;&(]/.test(command[i - 1])) && /\s/.test(command[i + 3] ?? "");
4371
+ if (char !== ">" && !isTee) continue;
4372
+ let cursor = isTee ? i + 3 : command[i + 1] === ">" ? i + 2 : i + 1;
4373
+ for (; ; ) {
4374
+ while (cursor < command.length && /[ \t]/.test(command[cursor])) cursor++;
4375
+ if (command[cursor] === "&") break;
4376
+ const { word, end } = readShellWord(command, cursor);
4377
+ cursor = end;
4378
+ if (word && word !== "/dev/null" && !(isTee && word.startsWith("-"))) return word;
4379
+ if (!isTee || !word) break;
4380
+ }
4381
+ i = cursor - 1;
4382
+ }
4383
+ return void 0;
4384
+ }
4385
+ function hasUnquotedFileRedirection(command) {
4386
+ let inSingle = false;
4387
+ let inDouble = false;
4388
+ for (let i = 0; i < command.length; i++) {
4389
+ const char = command[i];
4390
+ if (char === "'" && !inDouble) {
4391
+ inSingle = !inSingle;
4392
+ continue;
4393
+ }
4394
+ if (char === '"' && !inSingle) {
4395
+ inDouble = !inDouble;
4396
+ continue;
4397
+ }
4398
+ if (inSingle || inDouble) continue;
4399
+ if (char !== ">") continue;
4400
+ if (command[i - 1] === "-") continue;
4401
+ const isDouble = command[i + 1] === ">";
4402
+ let cursor = i + (isDouble ? 2 : 1);
4403
+ while (cursor < command.length && /\s/.test(command[cursor])) cursor++;
4404
+ if (cursor >= command.length) continue;
4405
+ const targetStart = command[cursor];
4406
+ if (targetStart === "&" || targetStart === "|" || targetStart === ";") continue;
4407
+ if (targetStart === "(" || targetStart === ")") continue;
4408
+ if (/^\/dev\/null(?=$|[\s;&|()])/.test(command.slice(cursor))) continue;
4409
+ return true;
4410
+ }
4411
+ return false;
4412
+ }
4413
+ function unquotedShellText(command) {
4414
+ let inSingle = false;
4415
+ let inDouble = false;
4416
+ let escaped = false;
4417
+ let result2 = "";
4418
+ for (const char of command) {
4419
+ if (escaped) {
4420
+ result2 += inSingle || inDouble ? "_" : char;
4421
+ escaped = false;
4422
+ continue;
4423
+ }
4424
+ if (char === "\\" && !inSingle) {
4425
+ escaped = true;
4426
+ result2 += inDouble ? "_" : char;
4427
+ continue;
4428
+ }
4429
+ if (char === "'" && !inDouble) {
4430
+ inSingle = !inSingle;
4431
+ continue;
4432
+ }
4433
+ if (char === '"' && !inSingle) {
4434
+ inDouble = !inDouble;
4435
+ continue;
4436
+ }
4437
+ result2 += inSingle || inDouble ? "_" : char;
4438
+ }
4439
+ return result2;
4440
+ }
4441
+ function hasMutatingGitCommand(command) {
4442
+ const unquoted = unquotedShellText(command);
4443
+ for (const segment of unquoted.split(/(?:&&|\|\||[;|()\n])/)) {
4444
+ const trimmed = segment.trim();
4445
+ if (!trimmed || /^(?:echo|printf)\b/.test(trimmed)) continue;
4446
+ if (/^git\s+(?:(?:(?:-C|--git-dir|--work-tree)\s+\S+|(?:--git-dir|--work-tree)=\S+|--paginate)\s+)*(?:add|commit|push)\b/.test(trimmed)) return true;
4447
+ }
4448
+ return false;
4449
+ }
4450
+ function isMutatingBashCommand(command) {
4451
+ return hasUnquotedFileRedirection(command) || hasMutatingGitCommand(command) || MUTATING_BASH_PATTERNS.some((pattern) => pattern.test(command));
4452
+ }
4453
+ function isMutatingTool(toolName, args, mutationTools) {
4454
+ if (!toolName) return false;
4455
+ if (mutationTools?.includes(toolName)) return true;
4456
+ if (toolName === "edit" || toolName === "write") return true;
4457
+ if (toolName === "cursor") {
4458
+ const activityTitle = typeof args?.activityTitle === "string" ? args.activityTitle : "";
4459
+ return /^Cursor (?:edit|write)\b/i.test(activityTitle);
4460
+ }
4461
+ if (toolName !== "bash") return false;
4462
+ const command = typeof args?.command === "string" ? args.command : "";
4463
+ if (!command.trim()) return false;
4464
+ return isMutatingBashCommand(command);
4465
+ }
4466
+ function didMutatingToolFail(result2) {
4467
+ return result2.isError === true;
4468
+ }
4469
+ function nextLongRunningTrigger(config, metrics) {
4470
+ if (metrics.now - metrics.startedAt >= config.activeNoticeAfterMs) return "time_threshold";
4471
+ if (config.activeNoticeAfterTurns !== void 0 && metrics.turns >= config.activeNoticeAfterTurns) return "turn_threshold";
4472
+ if (config.activeNoticeAfterTokens !== void 0 && metrics.tokens >= config.activeNoticeAfterTokens) return "token_threshold";
4473
+ return void 0;
4474
+ }
4475
+ function resetMutatingFailureState(state) {
4476
+ state.consecutiveFailures = 0;
4477
+ state.lastFailureAt = void 0;
4478
+ state.recentFailures = [];
4479
+ state.lastMutatingPath = void 0;
4480
+ state.repeatedPathFailures = 0;
4481
+ }
4482
+ function createMutatingFailureState() {
4483
+ return {
4484
+ consecutiveFailures: 0,
4485
+ recentFailures: [],
4486
+ repeatedPathFailures: 0
4487
+ };
4488
+ }
4489
+ function recordMutatingFailure(state, input, windowMs) {
4490
+ if (state.lastFailureAt === void 0 || input.ts - state.lastFailureAt > windowMs) {
4491
+ state.consecutiveFailures = 0;
4492
+ state.recentFailures = [];
4493
+ state.repeatedPathFailures = 0;
4494
+ state.lastMutatingPath = void 0;
4495
+ }
4496
+ state.lastFailureAt = input.ts;
4497
+ state.consecutiveFailures += 1;
4498
+ if (input.path && state.lastMutatingPath === input.path) {
4499
+ state.repeatedPathFailures += 1;
4500
+ } else if (input.path) {
4501
+ state.lastMutatingPath = input.path;
4502
+ state.repeatedPathFailures = 1;
4503
+ }
4504
+ state.recentFailures.push(input);
4505
+ if (state.recentFailures.length > 3) state.recentFailures.shift();
4506
+ }
4507
+ function shouldEscalateMutatingFailures(state, threshold) {
4508
+ return state.consecutiveFailures >= threshold || state.repeatedPathFailures >= threshold;
4509
+ }
4510
+ function summarizeRecentMutatingFailures(state) {
4511
+ if (state.recentFailures.length === 0) return void 0;
4512
+ return state.recentFailures.map((entry) => `${entry.tool}${entry.path ? `(${entry.path})` : ""}: ${entry.error}`).join(" | ");
4513
+ }
4514
+
4515
+ // src/runs/foreground/fork-tool-result-handler.ts
4516
+ var MAX_HANDLED_TOOL_RESULT_IDS = 1024;
4517
+ function createToolResultHandler(deps) {
4518
+ const {
4519
+ result: result2,
4520
+ progress,
4521
+ options,
4522
+ agentName,
4523
+ handledToolResultIds,
4524
+ pendingToolResultsByCallId,
4525
+ pendingToolState,
4526
+ mutatingFailures,
4527
+ mutatingFailureWindowMs,
4528
+ controlConfig,
4529
+ appendRecentOutput: appendRecentOutput2,
4530
+ fireUpdate,
4531
+ emitNeedsAttention
4532
+ } = deps;
4533
+ return (message, completion, now) => {
4534
+ const rawCallId = completion.toolCallId ?? message.toolCallId;
4535
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : void 0;
4536
+ if (callId) {
4537
+ if (handledToolResultIds.has(callId)) return;
4538
+ if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
4539
+ const oldest = handledToolResultIds.values().next().value;
4540
+ if (typeof oldest === "string") handledToolResultIds.delete(oldest);
4541
+ }
4542
+ handledToolResultIds.add(callId);
4543
+ }
4544
+ result2.messages.push(message);
4545
+ const resultText = extractTextFromContent(message.content);
4546
+ const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : void 0;
4547
+ if (callId && keyedSnapshot) pendingToolResultsByCallId.delete(callId);
4548
+ const toolSnapshot = keyedSnapshot ?? pendingToolState.current;
4549
+ if (!keyedSnapshot || pendingToolState.current === keyedSnapshot) pendingToolState.current = void 0;
4550
+ const resultToolName = completion.toolName ?? message.toolName;
4551
+ const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0 ? resultToolName : void 0) ?? toolSnapshot?.tool;
4552
+ const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
4553
+ if (options.toolBudget && budgetBlocked) {
4554
+ result2.toolBudgetBlocked = true;
4555
+ result2.toolBudget = toolBudgetState(
4556
+ options.toolBudget,
4557
+ Math.max(progress.toolCount, options.toolBudget.hard + 1),
4558
+ blockedTool
4559
+ );
4560
+ }
4561
+ appendRecentOutput2(progress, resultText.split("\n").slice(-10));
4562
+ const messageToolName = message.toolName;
4563
+ if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
4564
+ progress.progressText = toolSnapshot.progressText;
4565
+ progress.progressUpdatedAt = now;
4566
+ }
4567
+ if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
4568
+ recordMutatingFailure(mutatingFailures, {
4569
+ tool: toolSnapshot.tool,
4570
+ path: toolSnapshot.path,
4571
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
4572
+ ts: now
4573
+ }, mutatingFailureWindowMs);
4574
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
4575
+ emitNeedsAttention(now, {
4576
+ message: `${agentName} needs attention after repeated mutating tool failures`,
4577
+ reason: "tool_failures",
4578
+ currentTool: toolSnapshot.tool,
4579
+ currentPath: toolSnapshot.path,
4580
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : void 0,
4581
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures)
4582
+ });
4583
+ }
4584
+ } else if (toolSnapshot?.mutates) {
4585
+ resetMutatingFailureState(mutatingFailures);
4586
+ }
4587
+ fireUpdate();
4588
+ };
4589
+ }
4590
+
4304
4591
  // src/shared/jsonl-writer.ts
4305
4592
  import * as fs11 from "node:fs";
4306
4593
  var DEFAULT_MAX_JSONL_BYTES = 50 * 1024 * 1024;
@@ -4979,217 +5266,6 @@ function planAbortRecovery(input) {
4979
5266
  return { action: "resume", prompt: ABORT_RECOVERY_PROMPT };
4980
5267
  }
4981
5268
 
4982
- // src/runs/shared/long-running-guard.ts
4983
- var MUTATING_BASH_PATTERNS = [
4984
- /(^|[;&|()\s])rm\s+/,
4985
- /(^|[;&|()\s])mv\s+/,
4986
- /(^|[;&|()\s])cp\s+/,
4987
- /(^|[;&|()\s])mkdir\s+/,
4988
- /(^|[;&|()\s])touch\s+/,
4989
- /(^|[;&|()\s])git\s+apply\b/,
4990
- /(^|[;&|()\s])patch\s+/,
4991
- /(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,
4992
- /(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,
4993
- /(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,
4994
- /\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,
4995
- /\bwrite_text\s*\(/,
4996
- /\bopen\s*\([^)]*,\s*["'][wa]/
4997
- ];
4998
- function resolveCurrentPath(toolName, args) {
4999
- if (!toolName || !args) return void 0;
5000
- const direct = ["path", "file", "filename", "target", "cwd"];
5001
- for (const key of direct) {
5002
- const value = args[key];
5003
- if (typeof value === "string" && value.trim()) return value.trim();
5004
- }
5005
- if (toolName === "bash") {
5006
- const command = typeof args.command === "string" ? args.command : void 0;
5007
- if (!command) return void 0;
5008
- return firstWrittenFile(command);
5009
- }
5010
- return void 0;
5011
- }
5012
- function readShellWord(command, start) {
5013
- let word = "";
5014
- let quote;
5015
- let i = start;
5016
- for (; i < command.length; i++) {
5017
- const char = command[i];
5018
- if (quote) {
5019
- if (char === quote) quote = void 0;
5020
- else if (char === "\\" && quote === '"' && /[$`"\\\n]/.test(command[i + 1] ?? "")) word += command[++i];
5021
- else word += char;
5022
- continue;
5023
- }
5024
- if (char === "'" || char === '"') quote = char;
5025
- else if (char === "\\" && i + 1 < command.length) word += command[++i];
5026
- else if (/[\s;&|()<>]/.test(char)) break;
5027
- else word += char;
5028
- }
5029
- return { word, end: i };
5030
- }
5031
- function firstWrittenFile(command) {
5032
- let quote;
5033
- for (let i = 0; i < command.length; i++) {
5034
- const char = command[i];
5035
- if (quote) {
5036
- if (char === quote) quote = void 0;
5037
- else if (char === "\\" && quote === '"') i++;
5038
- continue;
5039
- }
5040
- if (char === "'" || char === '"') {
5041
- quote = char;
5042
- continue;
5043
- }
5044
- if (char === "\\") {
5045
- i++;
5046
- continue;
5047
- }
5048
- const isTee = command.startsWith("tee", i) && (i === 0 || /[\s|;&(]/.test(command[i - 1])) && /\s/.test(command[i + 3] ?? "");
5049
- if (char !== ">" && !isTee) continue;
5050
- let cursor = isTee ? i + 3 : command[i + 1] === ">" ? i + 2 : i + 1;
5051
- for (; ; ) {
5052
- while (cursor < command.length && /[ \t]/.test(command[cursor])) cursor++;
5053
- if (command[cursor] === "&") break;
5054
- const { word, end } = readShellWord(command, cursor);
5055
- cursor = end;
5056
- if (word && word !== "/dev/null" && !(isTee && word.startsWith("-"))) return word;
5057
- if (!isTee || !word) break;
5058
- }
5059
- i = cursor - 1;
5060
- }
5061
- return void 0;
5062
- }
5063
- function hasUnquotedFileRedirection(command) {
5064
- let inSingle = false;
5065
- let inDouble = false;
5066
- for (let i = 0; i < command.length; i++) {
5067
- const char = command[i];
5068
- if (char === "'" && !inDouble) {
5069
- inSingle = !inSingle;
5070
- continue;
5071
- }
5072
- if (char === '"' && !inSingle) {
5073
- inDouble = !inDouble;
5074
- continue;
5075
- }
5076
- if (inSingle || inDouble) continue;
5077
- if (char !== ">") continue;
5078
- if (command[i - 1] === "-") continue;
5079
- const isDouble = command[i + 1] === ">";
5080
- let cursor = i + (isDouble ? 2 : 1);
5081
- while (cursor < command.length && /\s/.test(command[cursor])) cursor++;
5082
- if (cursor >= command.length) continue;
5083
- const targetStart = command[cursor];
5084
- if (targetStart === "&" || targetStart === "|" || targetStart === ";") continue;
5085
- if (targetStart === "(" || targetStart === ")") continue;
5086
- if (/^\/dev\/null(?=$|[\s;&|()])/.test(command.slice(cursor))) continue;
5087
- return true;
5088
- }
5089
- return false;
5090
- }
5091
- function unquotedShellText(command) {
5092
- let inSingle = false;
5093
- let inDouble = false;
5094
- let escaped = false;
5095
- let result2 = "";
5096
- for (const char of command) {
5097
- if (escaped) {
5098
- result2 += inSingle || inDouble ? "_" : char;
5099
- escaped = false;
5100
- continue;
5101
- }
5102
- if (char === "\\" && !inSingle) {
5103
- escaped = true;
5104
- result2 += inDouble ? "_" : char;
5105
- continue;
5106
- }
5107
- if (char === "'" && !inDouble) {
5108
- inSingle = !inSingle;
5109
- continue;
5110
- }
5111
- if (char === '"' && !inSingle) {
5112
- inDouble = !inDouble;
5113
- continue;
5114
- }
5115
- result2 += inSingle || inDouble ? "_" : char;
5116
- }
5117
- return result2;
5118
- }
5119
- function hasMutatingGitCommand(command) {
5120
- const unquoted = unquotedShellText(command);
5121
- for (const segment of unquoted.split(/(?:&&|\|\||[;|()\n])/)) {
5122
- const trimmed = segment.trim();
5123
- if (!trimmed || /^(?:echo|printf)\b/.test(trimmed)) continue;
5124
- if (/^git\s+(?:(?:(?:-C|--git-dir|--work-tree)\s+\S+|(?:--git-dir|--work-tree)=\S+|--paginate)\s+)*(?:add|commit|push)\b/.test(trimmed)) return true;
5125
- }
5126
- return false;
5127
- }
5128
- function isMutatingBashCommand(command) {
5129
- return hasUnquotedFileRedirection(command) || hasMutatingGitCommand(command) || MUTATING_BASH_PATTERNS.some((pattern) => pattern.test(command));
5130
- }
5131
- function isMutatingTool(toolName, args, mutationTools) {
5132
- if (!toolName) return false;
5133
- if (mutationTools?.includes(toolName)) return true;
5134
- if (toolName === "edit" || toolName === "write") return true;
5135
- if (toolName === "cursor") {
5136
- const activityTitle = typeof args?.activityTitle === "string" ? args.activityTitle : "";
5137
- return /^Cursor (?:edit|write)\b/i.test(activityTitle);
5138
- }
5139
- if (toolName !== "bash") return false;
5140
- const command = typeof args?.command === "string" ? args.command : "";
5141
- if (!command.trim()) return false;
5142
- return isMutatingBashCommand(command);
5143
- }
5144
- function didMutatingToolFail(result2) {
5145
- return result2.isError === true;
5146
- }
5147
- function nextLongRunningTrigger(config, metrics) {
5148
- if (metrics.now - metrics.startedAt >= config.activeNoticeAfterMs) return "time_threshold";
5149
- if (config.activeNoticeAfterTurns !== void 0 && metrics.turns >= config.activeNoticeAfterTurns) return "turn_threshold";
5150
- if (config.activeNoticeAfterTokens !== void 0 && metrics.tokens >= config.activeNoticeAfterTokens) return "token_threshold";
5151
- return void 0;
5152
- }
5153
- function resetMutatingFailureState(state) {
5154
- state.consecutiveFailures = 0;
5155
- state.lastFailureAt = void 0;
5156
- state.recentFailures = [];
5157
- state.lastMutatingPath = void 0;
5158
- state.repeatedPathFailures = 0;
5159
- }
5160
- function createMutatingFailureState() {
5161
- return {
5162
- consecutiveFailures: 0,
5163
- recentFailures: [],
5164
- repeatedPathFailures: 0
5165
- };
5166
- }
5167
- function recordMutatingFailure(state, input, windowMs) {
5168
- if (state.lastFailureAt === void 0 || input.ts - state.lastFailureAt > windowMs) {
5169
- state.consecutiveFailures = 0;
5170
- state.recentFailures = [];
5171
- state.repeatedPathFailures = 0;
5172
- state.lastMutatingPath = void 0;
5173
- }
5174
- state.lastFailureAt = input.ts;
5175
- state.consecutiveFailures += 1;
5176
- if (input.path && state.lastMutatingPath === input.path) {
5177
- state.repeatedPathFailures += 1;
5178
- } else if (input.path) {
5179
- state.lastMutatingPath = input.path;
5180
- state.repeatedPathFailures = 1;
5181
- }
5182
- state.recentFailures.push(input);
5183
- if (state.recentFailures.length > 3) state.recentFailures.shift();
5184
- }
5185
- function shouldEscalateMutatingFailures(state, threshold) {
5186
- return state.consecutiveFailures >= threshold || state.repeatedPathFailures >= threshold;
5187
- }
5188
- function summarizeRecentMutatingFailures(state) {
5189
- if (state.recentFailures.length === 0) return void 0;
5190
- return state.recentFailures.map((entry) => `${entry.tool}${entry.path ? `(${entry.path})` : ""}: ${entry.error}`).join(" | ");
5191
- }
5192
-
5193
5269
  // src/runs/shared/child-lifecycle.ts
5194
5270
  function projectChildLifecycle(event, terminalAssistantStop = false, state) {
5195
5271
  if (event.type === "compaction_end") {
@@ -5942,9 +6018,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5942
6018
  };
5943
6019
  let activeLongRunningNotified = false;
5944
6020
  const pendingToolResultsByCallId = /* @__PURE__ */ new Map();
5945
- let pendingToolResult;
6021
+ const pendingToolState = { current: void 0 };
5946
6022
  const handledToolResultIds = /* @__PURE__ */ new Set();
5947
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
5948
6023
  let activeToolSequence = 0;
5949
6024
  const activeToolCalls = /* @__PURE__ */ new Map();
5950
6025
  const activeToolKeysByName = /* @__PURE__ */ new Map();
@@ -6123,62 +6198,21 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6123
6198
  const output = result2.timedOut && result2.finalOutput ? result2.finalOutput : getFinalOutput(result2.messages ?? []);
6124
6199
  emitUpdateSnapshot(output || "(running...)");
6125
6200
  };
6126
- const handleToolResult = (message, completion, now) => {
6127
- const rawCallId = completion.toolCallId ?? message.toolCallId;
6128
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : void 0;
6129
- if (callId) {
6130
- if (handledToolResultIds.has(callId)) return;
6131
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
6132
- const oldest = handledToolResultIds.values().next().value;
6133
- if (typeof oldest === "string") handledToolResultIds.delete(oldest);
6134
- }
6135
- handledToolResultIds.add(callId);
6136
- }
6137
- result2.messages.push(message);
6138
- const resultText = extractTextFromContent(message.content);
6139
- const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : void 0;
6140
- if (callId && keyedSnapshot) pendingToolResultsByCallId.delete(callId);
6141
- const toolSnapshot = keyedSnapshot ?? pendingToolResult;
6142
- if (!keyedSnapshot || pendingToolResult === keyedSnapshot) pendingToolResult = void 0;
6143
- const resultToolName = completion.toolName ?? message.toolName;
6144
- const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0 ? resultToolName : void 0) ?? toolSnapshot?.tool;
6145
- const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
6146
- if (options.toolBudget && budgetBlocked) {
6147
- result2.toolBudgetBlocked = true;
6148
- result2.toolBudget = toolBudgetState(
6149
- options.toolBudget,
6150
- Math.max(progress.toolCount, options.toolBudget.hard + 1),
6151
- blockedTool
6152
- );
6153
- }
6154
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
6155
- const messageToolName = message.toolName;
6156
- if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
6157
- progress.progressText = toolSnapshot.progressText;
6158
- progress.progressUpdatedAt = now;
6159
- }
6160
- if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
6161
- recordMutatingFailure(mutatingFailures, {
6162
- tool: toolSnapshot.tool,
6163
- path: toolSnapshot.path,
6164
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
6165
- ts: now
6166
- }, mutatingFailureWindowMs);
6167
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
6168
- emitNeedsAttention(now, {
6169
- message: `${agent.name} needs attention after repeated mutating tool failures`,
6170
- reason: "tool_failures",
6171
- currentTool: toolSnapshot.tool,
6172
- currentPath: toolSnapshot.path,
6173
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : void 0,
6174
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures)
6175
- });
6176
- }
6177
- } else if (toolSnapshot?.mutates) {
6178
- resetMutatingFailureState(mutatingFailures);
6179
- }
6180
- fireUpdate();
6181
- };
6201
+ const handleToolResult = createToolResultHandler({
6202
+ result: result2,
6203
+ progress,
6204
+ options,
6205
+ agentName: agent.name,
6206
+ handledToolResultIds,
6207
+ pendingToolResultsByCallId,
6208
+ pendingToolState,
6209
+ mutatingFailures,
6210
+ mutatingFailureWindowMs,
6211
+ controlConfig,
6212
+ appendRecentOutput,
6213
+ fireUpdate,
6214
+ emitNeedsAttention
6215
+ });
6182
6216
  const processEvent = (evt) => {
6183
6217
  if (lifecycleFinished) return;
6184
6218
  partialOutput.observe(evt);
@@ -6274,8 +6308,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6274
6308
  result2.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result2.toolBudget?.blockedTool);
6275
6309
  }
6276
6310
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
6277
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
6278
- if (typeof evt.toolCallId === "string" && evt.toolCallId) pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
6311
+ pendingToolState.current = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
6312
+ if (typeof evt.toolCallId === "string" && evt.toolCallId) pendingToolResultsByCallId.set(evt.toolCallId, pendingToolState.current);
6279
6313
  fireUpdate();
6280
6314
  }
6281
6315
  if (evt.type === "tool_execution_end") {
package/bundle/index.js CHANGED
@@ -17,7 +17,7 @@ function readInstalledPackageVersion() {
17
17
  var loadedPackageVersion = readInstalledPackageVersion();
18
18
 
19
19
  // index.ts
20
- var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-6MNRKUHY.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-KCJFGKVK.js")).default;
20
+ var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-VRG6TEPW.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-MQ5X2OJ2.js")).default;
21
21
  function registerSubagentExtension(pi) {
22
22
  const installedVersion = readInstalledPackageVersion();
23
23
  if (installedVersion !== loadedPackageVersion) {
@@ -3,6 +3,10 @@
3
3
  All notable changes to the internal `@xzzpig/pi-components` shared library are
4
4
  documented here.
5
5
 
6
+ ## Unreleased
7
+
8
+ - 新增 `@xzzpig/pi-components/diff`,提供可复用的差异行配对、宽度自适应排版及安全文本展示;原 transcript 导出保持不变。
9
+
6
10
  ## 0.5.0
7
11
 
8
12
  ### Added
@@ -6,6 +6,28 @@ release tarballs instead of publishing it independently. Bundled artifacts
6
6
  expose compiled runtime JavaScript and declarations from `dist/`; the
7
7
  TypeScript source remains in this repository for development.
8
8
 
9
+ ## 共享 diff 排版
10
+
11
+ `@xzzpig/pi-components/diff` 接受调用方已经确定的旧值、新值、上下文及分组行,按可用列宽显示并排或上下差异。组件只排版,不解析业务数据、读取文件或执行工具:
12
+
13
+ ```ts
14
+ import {
15
+ renderDiffEntries,
16
+ type DiffTextEntry,
17
+ } from "@xzzpig/pi-components/diff";
18
+
19
+ const entries: DiffTextEntry[] = [
20
+ { kind: "meta", content: "目标", hunkIndex: 1 },
21
+ { kind: "line", lineKind: "remove", content: "旧目标", hunkIndex: 1 },
22
+ { kind: "line", lineKind: "add", content: "新目标", hunkIndex: 1 },
23
+ ];
24
+ const lines = renderDiffEntries(entries, { width: 120, mode: "auto" });
25
+ ```
26
+
27
+ `auto` 默认在内容区至少 120 列时并排,`splitMinWidth` 可由宿主调整;强制并排遇到无法容纳两列的窄屏仍回退上下布局。`renderDiffEntries` 把输入当不可信文本,清除终端控制指令,然后才应用传入的主题。`pairDiffEntries`、`measureDiffColumns` 和 `renderPairedDiffRows` 提供底层组合接口以保留宿主的行号与背景;这些接口的单元格回调是可信渲染器,调用方须先处理不可信数据、保证返回的 cell 按请求宽度绘制。视口滚动和鼠标命中由宿主负责。
28
+
29
+ `pi-components` 仍是 private 内部包:消费者必须在自己的安装产物中包含可运行的编译版本,不能依赖另一个插件或工作区软链接。原有 transcript 子路径不变。
30
+
9
31
  ## Transcript components
10
32
 
11
33
  `@xzzpig/pi-components/transcript` provides a bounded `SessionTranscript`