pi-subagents 0.87.0 → 0.88.1

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 (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  6. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  7. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  8. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  9. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  10. package/bundle/{chunk-LFKMM3UH.js → chunk-6OWNDN7R.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  13. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  14. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  15. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  16. package/bundle/{chunk-DGTZKYIE.js → chunk-FLNDHNPE.js} +75 -44
  17. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  18. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  19. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  20. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  21. package/bundle/{chunk-AIL46SZU.js → chunk-N6TAAIB3.js} +6 -4
  22. package/bundle/{chunk-EYGBK6CE.js → chunk-PCZEQQAQ.js} +114 -49
  23. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  24. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  25. package/bundle/{chunk-OTLDAYEQ.js → chunk-VTUUOLM4.js} +14 -5
  26. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  27. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  28. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  29. package/bundle/chunk-YDZ7BZD5.js +523 -0
  30. package/bundle/{chunk-JLDQ6YUR.js → chunk-YQSTGPEU.js} +12 -12
  31. package/bundle/{chunk-OZCPYJEY.js → chunk-ZJ2BT5TI.js} +130 -49
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +7 -3
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +2 -2
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +1 -0
  50. package/src/extension/config.js +6 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -12,6 +12,9 @@ function steerTargetsAccepted(result) {
12
12
  const targets = result?.targets ?? [];
13
13
  return targets.length > 0 && targets.every((target) => target.state === "queued" || target.state === "delivered");
14
14
  }
15
+ function steerTargetsRejected(result) {
16
+ return result?.targets.some((target) => target.state === "failed" && target.failureKind === "rejected") === true;
17
+ }
15
18
  export function canQueueRetainedAsyncFollowUp(status, index) {
16
19
  const steps = status.steps ?? [];
17
20
  return status.state === "complete"
@@ -174,8 +177,10 @@ export async function steerAsyncRun(input) {
174
177
  if (input.signal?.aborted) {
175
178
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering pending for async run ${status.runId} (request ${requestId}); caller aborted before recovery.`) }], details: { mode: "management", results: [], steering: result } };
176
179
  }
180
+ const projected = (current) => current?.steering ? actionResultFromSteeringStatus(current.steering, status.runId, requestId) : undefined;
181
+ const rejected = () => new Error(`Child rejected the guidance; continue it with action "resume" and id "${status.runId}".`);
177
182
  const finalStatus = readStatus(asyncDir);
178
- const finalResult = finalStatus?.steering ? actionResultFromSteeringStatus(finalStatus.steering, status.runId, requestId) : undefined;
183
+ const finalResult = projected(finalStatus);
179
184
  const acceptedReply = (accepted) => {
180
185
  const acceptedState = accepted.state === "delivered" ? "delivered" : "queued";
181
186
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering ${acceptedState} for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: accepted } };
@@ -184,7 +189,7 @@ export async function steerAsyncRun(input) {
184
189
  return acceptedReply(finalResult);
185
190
  const running = (finalStatus?.steps ?? status.steps ?? []).filter((step) => step.status === "running");
186
191
  const recoveryAllowed = (input.mode ?? "steer") === "steer" && status.mode === "single" && status.isNested !== true && running.length === 1 && Boolean(finalStatus?.steering) && (input.index === undefined || input.index === 0);
187
- if (recoveryAllowed && finalResult?.state !== "scheduled" && input.recover) {
192
+ if (recoveryAllowed && finalResult?.state !== "scheduled" && !steerTargetsRejected(finalResult) && input.recover) {
188
193
  const appendSteeringNotice = (state, message) => {
189
194
  try {
190
195
  fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...(status.sessionId ? { currentSessionId: status.sessionId } : {}) })}\n`);
@@ -194,21 +199,23 @@ export async function steerAsyncRun(input) {
194
199
  }
195
200
  };
196
201
  try {
197
- const latest = readStatus(asyncDir);
198
- const latestResult = latest?.steering ? actionResultFromSteeringStatus(latest.steering, status.runId, requestId) : undefined;
202
+ const latestResult = projected(readStatus(asyncDir));
199
203
  if (latestResult && steerTargetsAccepted(latestResult))
200
204
  return acceptedReply(latestResult);
205
+ if (steerTargetsRejected(latestResult))
206
+ throw rejected();
201
207
  const committedAt = Date.now();
202
208
  input.onBeforeRecoveryClaim?.(requestId, committedAt);
203
209
  const { claimPath, markerPath } = claimSteeringRecovery(asyncDir, { requestId, sourceRunId: status.runId, committedAt });
204
210
  input.onRecoveryCommitted?.(requestId, committedAt);
205
- const preCommitStatus = readStatus(asyncDir);
206
- const preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : undefined;
211
+ const preCommitResult = projected(readStatus(asyncDir));
207
212
  if (preCommitResult
208
- && preCommitResult.targets.length > 0
209
- && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))) {
213
+ && (steerTargetsRejected(preCommitResult) || (preCommitResult.targets.length > 0
214
+ && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))))) {
210
215
  fs.rmSync(markerPath, { force: true });
211
216
  fs.rmSync(claimPath, { force: true });
217
+ if (steerTargetsRejected(preCommitResult))
218
+ throw rejected();
212
219
  return acceptedReply(preCommitResult);
213
220
  }
214
221
  try {
@@ -228,6 +235,10 @@ export async function steerAsyncRun(input) {
228
235
  break;
229
236
  const candidate = readStatus(asyncDir);
230
237
  lastObservedState = candidate?.state;
238
+ if (steerTargetsRejected(projected(candidate))) {
239
+ fs.rmSync(claimPath, { force: true });
240
+ throw rejected();
241
+ }
231
242
  if (candidate?.state === "paused" && candidate.endedAt !== undefined) {
232
243
  paused = candidate;
233
244
  break;
@@ -252,6 +263,10 @@ export async function steerAsyncRun(input) {
252
263
  if (!recoveryTarget.recoveryDescriptor)
253
264
  throw new Error("Source run has no private recovery descriptor; it remains paused and is not safely resumable.");
254
265
  const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
266
+ if (steerTargetsRejected(projected(readStatus(asyncDir)))) {
267
+ fs.rmSync(claimPath, { force: true });
268
+ throw rejected();
269
+ }
255
270
  const revived = await input.recover(limits);
256
271
  if (revived.isError || !revived.details.asyncId)
257
272
  throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
@@ -279,7 +294,7 @@ export async function steerAsyncRun(input) {
279
294
  failedStatus.activityState = "needs_attention";
280
295
  writeAtomicJson(path.join(asyncDir, "status.json"), failedStatus);
281
296
  }
282
- const failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : undefined;
297
+ const failed = projected(failedStatus);
283
298
  appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`);
284
299
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}`) }], isError: true, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, deliveryStatus: "queued", targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
285
300
  }
@@ -5,9 +5,10 @@ import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.js";
5
5
  import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.js";
6
6
  import { ensureArtifactsDir, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata, } from "../../shared/artifacts.js";
7
7
  import { createChildTranscriptWriter } from "../../shared/child-transcript.js";
8
+ import { extractReportedProgress } from "../../shared/reported-progress.js";
8
9
  import { DEFAULT_MAX_OUTPUT, INTERCOM_DETACH_REQUEST_EVENT, INTERCOM_DETACH_RESPONSE_EVENT, truncateOutput, } from "../../shared/types.js";
9
10
  import { DEFAULT_CONTROL_CONFIG, buildControlEvent, claimControlNotification, deriveActivityState, shouldEmitOpenToolAttention, shouldNotifyControlEvent, } from "../shared/subagent-control.js";
10
- import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
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";
11
12
  import { resolveSkillsWithFallback } from "../../agents/skills.js";
12
13
  import { createPartialOutputTracker, formatPartialOutput } from "../shared/partial-output.js";
13
14
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.js";
@@ -44,6 +45,7 @@ import { childSessionFactory, childSessionHasQueuedMessages, projectChildSession
44
45
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.js";
45
46
  import { clearProviderRetry, observeProviderDiagnostics, snapshotProviderDiagnostics } from "../../shared/provider-diagnostics.js";
46
47
  import { isRexLocalMachine } from "../shared/rex-machine.js";
48
+ import { pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
47
49
  const artifactOutputByResult = new WeakMap();
48
50
  const acceptanceOutputByResult = new WeakMap();
49
51
  function emptyUsage() {
@@ -205,6 +207,8 @@ function captureStructuredDelegationProgressState(progress, result) {
205
207
  recentOutput: [...progress.recentOutput],
206
208
  recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
207
209
  activityState: progress.activityState,
210
+ progressText: progress.progressText,
211
+ progressUpdatedAt: progress.progressUpdatedAt,
208
212
  model: progress.model ?? result.model,
209
213
  toolCount: progress.toolCount,
210
214
  tokens: progress.tokens,
@@ -217,6 +221,8 @@ function structuredDelegationProgressChanged(previous, progress, result) {
217
221
  || previous.currentTool !== progress.currentTool
218
222
  || previous.currentToolArgs !== progress.currentToolArgs
219
223
  || previous.activityState !== progress.activityState
224
+ || previous.progressText !== progress.progressText
225
+ || previous.progressUpdatedAt !== progress.progressUpdatedAt
220
226
  || previous.model !== (progress.model ?? result.model)
221
227
  || previous.toolCount !== progress.toolCount
222
228
  || previous.tokens !== progress.tokens
@@ -243,6 +249,7 @@ function isCompleteUsageCounter(value) {
243
249
  }
244
250
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
245
251
  const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
252
+ const REMAINING_TIMEOUT_MS = Symbol("remainingTimeoutMs");
246
253
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
247
254
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
248
255
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
@@ -447,6 +454,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
447
454
  let toolAvailabilityError;
448
455
  let abortedBySignal = options.signal?.aborted === true;
449
456
  let afterCompactionSettlement = false;
457
+ let remainingTimeoutMs;
450
458
  if (options.workflowChildPermitLaunch) {
451
459
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
452
460
  workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
@@ -486,7 +494,8 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
486
494
  let timeoutHardFinishTimer;
487
495
  const clearTimeoutTimers = () => {
488
496
  if (timeoutTimer) {
489
- clearTimeout(timeoutTimer);
497
+ remainingTimeoutMs = timeoutTimer.remainingMs();
498
+ timeoutTimer.clear();
490
499
  timeoutTimer = undefined;
491
500
  }
492
501
  if (timeoutHardFinishTimer) {
@@ -1020,6 +1029,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1020
1029
  progress.durationMs = now - startTime;
1021
1030
  progress.lastActivityAt = now;
1022
1031
  updateActivityState(now);
1032
+ pauseForSupervisorWait(timeoutTimer, evt);
1023
1033
  if (evt.type === "tool_execution_start") {
1024
1034
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args)
1025
1035
  ? evt.args
@@ -1039,7 +1049,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1039
1049
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result.toolBudget?.blockedTool);
1040
1050
  }
1041
1051
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1042
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1052
+ pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
1043
1053
  if (typeof evt.toolCallId === "string" && evt.toolCallId)
1044
1054
  pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
1045
1055
  fireUpdate();
@@ -1140,6 +1150,10 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1140
1150
  result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
1141
1151
  }
1142
1152
  appendRecentOutput(progress, resultText.split("\n").slice(-10));
1153
+ if (evt.message.isError !== true && resultToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
1154
+ progress.progressText = toolSnapshot.progressText;
1155
+ progress.progressUpdatedAt = now;
1156
+ }
1143
1157
  // A budget block has its own signal; it is not a failing mutation.
1144
1158
  if (toolSnapshot?.mutates && !budgetBlocked && didMutatingToolFail(evt.message)) {
1145
1159
  recordMutatingFailure(mutatingFailures, {
@@ -1180,7 +1194,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1180
1194
  activityTimer.unref?.();
1181
1195
  }
1182
1196
  if (attemptTimeout) {
1183
- timeoutTimer = setTimeout(() => {
1197
+ timeoutTimer = startPausableTimer(attemptTimeout.remainingMs, () => {
1184
1198
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1185
1199
  return;
1186
1200
  result.timedOut = true;
@@ -1199,8 +1213,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1199
1213
  settle(undefined, true);
1200
1214
  }, 4000);
1201
1215
  timeoutHardFinishTimer.unref?.();
1202
- }, attemptTimeout.remainingMs);
1203
- timeoutTimer.unref?.();
1216
+ });
1204
1217
  }
1205
1218
  let toolTimeoutSequence = 0;
1206
1219
  const activeToolTimeouts = new Map();
@@ -1240,7 +1253,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1240
1253
  const terminateForToolTimeout = (message) => {
1241
1254
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1242
1255
  return;
1243
- clearTimeout(timeoutTimer);
1256
+ timeoutTimer?.clear();
1244
1257
  result.timedOut = true;
1245
1258
  timeoutCause = message;
1246
1259
  result.error = message;
@@ -1261,10 +1274,6 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1261
1274
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
1262
1275
  if (timeoutForTool === undefined)
1263
1276
  return;
1264
- const elapsed = Date.now() - startTime;
1265
- const runRemaining = attemptTimeout ? Math.max(0, attemptTimeout.remainingMs - elapsed) : undefined;
1266
- if (runRemaining !== undefined && timeoutForTool >= runRemaining)
1267
- return;
1268
1277
  const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
1269
1278
  const toolName = event.toolName;
1270
1279
  const timer = setTimeout(() => {
@@ -1413,14 +1422,14 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1413
1422
  const steer = created.steer.bind(created);
1414
1423
  const followUp = created.followUp.bind(created);
1415
1424
  created.steer = async (text) => {
1425
+ await steer(text);
1416
1426
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1417
1427
  queuedDrainHold = true;
1418
- return steer(text);
1419
1428
  };
1420
1429
  created.followUp = async (text) => {
1430
+ await followUp(text);
1421
1431
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1422
1432
  queuedDrainHold = true;
1423
- return followUp(text);
1424
1433
  };
1425
1434
  created.detached = detached;
1426
1435
  unsubscribe = created.subscribe((event) => processEvent(event));
@@ -1469,9 +1478,9 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1469
1478
  result.exitCode = exitCode;
1470
1479
  result.providerDiagnostics = clearProviderRetry(result.providerDiagnostics);
1471
1480
  progress.providerDiagnostics = result.providerDiagnostics;
1472
- if (afterCompactionSettlement) {
1481
+ if (afterCompactionSettlement)
1473
1482
  result[AFTER_COMPACTION_SETTLEMENT] = true;
1474
- }
1483
+ result[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
1475
1484
  if (interruptedByControl) {
1476
1485
  result.exitCode = 0;
1477
1486
  result.interrupted = true;
@@ -1546,6 +1555,10 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1546
1555
  ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}`
1547
1556
  : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
1548
1557
  }
1558
+ else if (!validatedStructuredOutput && getTerminalAssistantStopReason(messages) === "length") {
1559
+ result.exitCode = 1;
1560
+ result.error = TRUNCATED_RESPONSE_ERROR;
1561
+ }
1549
1562
  }
1550
1563
  progress.status = result.exitCode === 0 ? "completed" : "failed";
1551
1564
  progress.durationMs = Date.now() - startTime;
@@ -1945,6 +1958,10 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1945
1958
  });
1946
1959
  if (recovery.action === "resume") {
1947
1960
  recoveryPrompt = recovery.prompt;
1961
+ // The retry gets the budget the first attempt left, so that attempt's supervisor waits stay uncounted.
1962
+ const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
1963
+ if (remainingMs !== undefined)
1964
+ attemptOptions.deadlineAt = Date.now() + remainingMs;
1948
1965
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
1949
1966
  continue;
1950
1967
  }
@@ -49,6 +49,7 @@ export async function rewritePromptWithGuidance(input) {
49
49
  });
50
50
  const ctxThinking = input.ctx.getThinkingLevel?.();
51
51
  const agent = new Agent({
52
+ sessionId,
52
53
  initialState: {
53
54
  systemPrompt: [
54
55
  "Rewrite one subagent authored task from Prompt Audit context.",
@@ -59,6 +59,7 @@ export interface SubagentParamsLike {
59
59
  agent?: string;
60
60
  task?: string;
61
61
  capabilities?: boolean;
62
+ search?: string;
62
63
  extensionBindings?: ExtensionBindings;
63
64
  /** Retained async child run id. Valid only on workflow runs.run items. */
64
65
  resume?: string;
@@ -214,14 +215,6 @@ export declare function shouldSuppressRoutineResultIntercom(input: {
214
215
  }): boolean;
215
216
  export declare const DEFAULT_FOREGROUND_TIMEOUT_MS: number;
216
217
  export { DEFAULT_ASYNC_TIMEOUT_MS };
217
- /**
218
- * Resolve the optional global default runtime deadline from extension config
219
- * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
220
- * fall back to the built-in defaults. "Invalid" covers non-positive-integer
221
- * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
222
- * Node.js timer and expire the run almost immediately instead of running long.
223
- */
224
- export declare function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined;
225
218
  export declare function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): {
226
219
  timeoutMs?: number;
227
220
  error?: string;
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { discoverAgents, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext } from "../../agents/agents.js";
5
- import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.js";
5
+ import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir, missingForkCopyNote } from "../../shared/artifacts.js";
6
6
  import { writeAtomicJson } from "../../shared/atomic-json.js";
7
7
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.js";
8
8
  import { reportSessionWarning } from "../../shared/session-warnings.js";
@@ -44,6 +44,7 @@ import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.js";
44
44
  import { resolveCurrentSessionId } from "../../shared/session-identity.js";
45
45
  import { currentCompletionOwnerId } from "../../shared/completion-owner.js";
46
46
  import { SUBAGENT_ASYNC_COMPLETE_EVENT } from "../../shared/types.js";
47
+ import { resolveConfigDefaultTimeoutMs } from "../../extension/config.js";
47
48
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
48
49
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.js";
49
50
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.js";
@@ -702,7 +703,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
702
703
  throw new Error(`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`);
703
704
  const sessionFile = path.resolve(child.sessionFile);
704
705
  if (!fs.existsSync(sessionFile))
705
- throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);
706
+ throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}${missingForkCopyNote(sessionFile)}`);
706
707
  return {
707
708
  runId: run.runId,
708
709
  mode: run.mode,
@@ -1190,7 +1191,7 @@ function validateNestedSessionFile(run, trustedSessionRoots, resolveSource, visi
1190
1191
  if (!path.isAbsolute(sessionFile))
1191
1192
  throw new Error(`Nested run '${run.id}' session file must be absolute: ${sessionFile}`);
1192
1193
  if (!fs.existsSync(resolved))
1193
- throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}`);
1194
+ throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}${missingForkCopyNote(resolved)}`);
1194
1195
  const stat = fs.lstatSync(resolved);
1195
1196
  if (!stat.isFile() || stat.isSymbolicLink())
1196
1197
  throw new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);
@@ -2712,18 +2713,6 @@ function timerDelayOverflowError(name, value) {
2712
2713
  ? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.`
2713
2714
  : undefined;
2714
2715
  }
2715
- /**
2716
- * Resolve the optional global default runtime deadline from extension config
2717
- * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
2718
- * fall back to the built-in defaults. "Invalid" covers non-positive-integer
2719
- * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
2720
- * Node.js timer and expire the run almost immediately instead of running long.
2721
- */
2722
- export function resolveConfigDefaultTimeoutMs(raw) {
2723
- if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS)
2724
- return undefined;
2725
- return raw;
2726
- }
2727
2716
  export function resolveForegroundTimeout(params, defaultTimeoutMs) {
2728
2717
  const rawTimeout = params.timeoutMs;
2729
2718
  const rawMaxRuntime = params.maxRuntimeMs;
@@ -5974,9 +5963,12 @@ export function createSubagentExecutor(deps) {
5974
5963
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5975
5964
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
5976
5965
  preparedChildParams = childRequest;
5977
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5978
- if (launchRefusal)
5979
- return buildRequestedModeError(childRequest, launchRefusal);
5966
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5967
+ if ("refusal" in approval)
5968
+ return buildRequestedModeError(childRequest, approval.refusal);
5969
+ // Assigned in place: the WeakMaps below are keyed on this object. A resume's task is its message, which stays as sent.
5970
+ if (approval.task !== undefined && childRequest.action !== "resume")
5971
+ childRequest.task = approval.task;
5980
5972
  if (workflowUsageBudget.budget)
5981
5973
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5982
5974
  if (workflowRequiredExtensions)
@@ -6013,6 +6005,8 @@ export function createSubagentExecutor(deps) {
6013
6005
  step.currentToolArgs = progress.currentToolArgs;
6014
6006
  step.currentToolStartedAt = progress.currentToolStartedAt;
6015
6007
  step.currentPath = progress.currentPath;
6008
+ step.progressText = progress.progressText;
6009
+ step.progressUpdatedAt = progress.progressUpdatedAt;
6016
6010
  step.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
6017
6011
  step.recentOutput = [...progress.recentOutput];
6018
6012
  step.turnCount = progress.turnCount;
@@ -6303,9 +6297,11 @@ export function createSubagentExecutor(deps) {
6303
6297
  const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6304
6298
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
6305
6299
  preparedChildParams = childRequest;
6306
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6307
- if (launchRefusal)
6308
- return buildRequestedModeError(childRequest, launchRefusal);
6300
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6301
+ if ("refusal" in approval)
6302
+ return buildRequestedModeError(childRequest, approval.refusal);
6303
+ if (approval.task !== undefined && childRequest.action !== "resume")
6304
+ childRequest.task = approval.task;
6309
6305
  if (workflowUsageBudget.budget)
6310
6306
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6311
6307
  if (workflowRequiredExtensions)
@@ -33,6 +33,8 @@ export interface AsyncStatusSnapshotNode {
33
33
  updatedAt?: number;
34
34
  endedAt?: number;
35
35
  activity?: AsyncStatusSnapshotActivity;
36
+ progressText?: string;
37
+ progressUpdatedAt?: number;
36
38
  /** Step nodes only: the agent the child runs as, and the model and thinking level it reports. */
37
39
  agent?: string;
38
40
  model?: string;
@@ -137,6 +137,8 @@ function projectStep(step, index, depth, ctx) {
137
137
  const activity = activityFor(step, ctx);
138
138
  const { id, label } = stepIdentity(step, index, ctx);
139
139
  const agent = publicOptionalText(step.agent, ctx.caps.maxStringLength);
140
+ const progressText = publicOptionalText(step.progressText, ctx.caps.maxStringLength);
141
+ const progressUpdatedAt = publicTime(step.progressUpdatedAt);
140
142
  const node = {
141
143
  id,
142
144
  kind: "step",
@@ -146,6 +148,8 @@ function projectStep(step, index, depth, ctx) {
146
148
  ...(updatedAt !== undefined ? { updatedAt } : {}),
147
149
  ...(terminalState(state) && endedAt !== undefined ? { endedAt } : {}),
148
150
  ...(activity ? { activity } : {}),
151
+ ...(progressText ? { progressText } : {}),
152
+ ...(progressUpdatedAt !== undefined ? { progressUpdatedAt } : {}),
149
153
  };
150
154
  if (agent)
151
155
  node.agent = agent;
@@ -302,6 +306,12 @@ function projectMaterializedStep(step, index, child, depth, ctx, childrenByParen
302
306
  const selfActivity = selfStep ? activityFor(selfStep, ctx) : undefined;
303
307
  const activity = laneActivity || selfActivity || live.activity ? { ...laneActivity, ...selfActivity, ...live.activity } : undefined;
304
308
  const node = { ...live, id, kind: "step", label };
309
+ const progressText = publicOptionalText(selfStep?.progressText ?? step.progressText, ctx.caps.maxStringLength);
310
+ const progressUpdatedAt = publicTime(selfStep?.progressUpdatedAt ?? step.progressUpdatedAt);
311
+ if (progressText)
312
+ node.progressText = progressText;
313
+ if (progressUpdatedAt !== undefined)
314
+ node.progressUpdatedAt = progressUpdatedAt;
305
315
  const agent = publicOptionalText(selfStep?.agent || step.agent, ctx.caps.maxStringLength);
306
316
  if (agent)
307
317
  node.agent = agent;
@@ -13,7 +13,7 @@ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV } from "./e
13
13
  import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
14
14
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
15
15
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
16
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
16
+ import { createRequiredChildExtensionIdentity, resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
17
17
  import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
18
18
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
19
19
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
@@ -57,6 +57,8 @@ function childProcessEnv(input, toolPlan) {
57
57
  else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
58
58
  env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
59
59
  }
60
+ else if (input.tools === undefined && !toolPlan.capabilityCeiling)
61
+ env[MCP_DIRECT_TOOLS_ENV] = undefined;
60
62
  else
61
63
  env[MCP_DIRECT_TOOLS_ENV] = "__none__";
62
64
  return env;
@@ -106,10 +108,11 @@ export function buildInProcessChildLaunch(input) {
106
108
  permissionRules: input.permissionRules,
107
109
  runtimeSnapshotHost: input.runtimeSnapshotHost,
108
110
  });
109
- // Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
111
+ // Foreground children load no ambient extensions, so only their required extensions' registerMcpServer() runs in them.
110
112
  if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
113
+ const requiredExtensionIdentity = createRequiredChildExtensionIdentity(toolPlan.requiredExtensions.map(({ path }) => path));
111
114
  // Pi treats a session without a trust decision as trusted.
112
- const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
115
+ const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false, (extensionPath) => requiredExtensionIdentity(extensionPath) !== undefined);
113
116
  if (servers.length)
114
117
  throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
115
118
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
4
- import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
4
+ import { type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
5
5
  import type { PlacementMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
6
6
  export interface ChildSessionEvent {
7
7
  type: string;
@@ -22,9 +22,11 @@ import { cleanupSessionResources, registerSessionResourceCleanup } from "@earend
22
22
  import { CHILD_COMMAND_TOOL, createChildCommandRuntime } from "./child-commands.js";
23
23
  import { supervisorChannelDir } from "./child-tool-plan.js";
24
24
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.js";
25
+ import { parseAcceptanceReport } from "./acceptance.js";
25
26
  import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.js";
26
27
  import { resolvePackageSubpath } from "../background/runner-aliases.js";
27
28
  import { PI_CODING_AGENT_PACKAGE, resolveHostPiPackageRoot } from "./pi-spawn.js";
29
+ import { createRequiredChildExtensionIdentity } from "../../shared/required-child-extensions.js";
28
30
  /** Mirror pi's JSON event projection: `message_update` drops the partial message. */
29
31
  export function projectChildSessionEventForJson(event) {
30
32
  if (event.type !== "message_update")
@@ -79,32 +81,6 @@ const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime
79
81
  const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
80
82
  /** Same class as UNICODE_SPACES in pi-coding-agent dist/utils/paths.js, which resolvePath(..., { normalizeUnicodeSpaces: true }) replaces with a space. */
81
83
  const PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
82
- function childExtensionFileIdentity(extensionPath) {
83
- if (!path.isAbsolute(extensionPath))
84
- return undefined;
85
- try {
86
- const stat = fs.statSync(extensionPath, { bigint: true });
87
- return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
88
- }
89
- catch {
90
- return undefined;
91
- }
92
- }
93
- function createRequiredChildExtensionIdentity(requiredPaths) {
94
- const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
95
- const identities = new Set(aliases.values());
96
- return (extensionPath) => {
97
- const known = aliases.get(extensionPath);
98
- if (known !== undefined)
99
- return known;
100
- const identity = childExtensionFileIdentity(extensionPath);
101
- if (identity === undefined || !identities.has(identity))
102
- return undefined;
103
- // Retain the alias even if the extension removes its file before reporting a failure.
104
- aliases.set(extensionPath, identity);
105
- return identity;
106
- };
107
- }
108
84
  /** The prompt runtime filters parent-only context before ambient extensions inspect
109
85
  * the child prompt, and the boundary hook appends the child boundary after every
110
86
  * extension has added its prompt sections. Every other extension keeps its order. */
@@ -590,7 +566,8 @@ export function createDefaultChildSessionFactory(options = {}) {
590
566
  await session.bindExtensions({
591
567
  mode: "print",
592
568
  onError: (error) => {
593
- if (binding && isRequiredSource(error.extensionPath))
569
+ // Pi's unconnected-MCP-server report means the server's tools are outside this child's tool contract, which the child can run without.
570
+ if (binding && error.event !== "register_mcp_server" && isRequiredSource(error.extensionPath))
594
571
  requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
595
572
  launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
596
573
  },
@@ -655,12 +632,29 @@ export function createDefaultChildSessionFactory(options = {}) {
655
632
  mcpWaits.delete(cancel);
656
633
  }
657
634
  }
635
+ let reportCompleted = false;
636
+ const guidanceClosed = "Child completed its acceptance report; resume it for further guidance.";
637
+ const assertAcceptsGuidance = () => { if (reportCompleted)
638
+ throw new Error(guidanceClosed); };
639
+ const rejectQueuedGuidance = () => { session.clearQueue(); throw new Error(guidanceClosed); };
658
640
  const child = {
659
- subscribe: (listener) => session.subscribe((event) => listener(event)),
641
+ subscribe: (listener) => session.subscribe((event) => {
642
+ if (event.type === "message_end" && event.message.role === "assistant" && event.message.stopReason === "stop") {
643
+ const text = event.message.content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
644
+ const report = parseAcceptanceReport(text);
645
+ if (report.report || report.malformed) {
646
+ reportCompleted = true;
647
+ session.clearQueue();
648
+ session.agent.steer = rejectQueuedGuidance;
649
+ session.agent.followUp = rejectQueuedGuidance;
650
+ }
651
+ }
652
+ listener(event);
653
+ }),
660
654
  prompt: (text) => session.prompt(text),
661
655
  ...(commands ? { finishCommands: () => commands.finish() } : {}),
662
- steer: async (text) => { await session.steer(text); },
663
- followUp: async (text) => { await session.followUp(text); },
656
+ steer: async (text) => { assertAcceptsGuidance(); await session.steer(text); },
657
+ followUp: async (text) => { assertAcceptsGuidance(); await session.followUp(text); },
664
658
  abort: () => session.abort(),
665
659
  hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
666
660
  dispose: () => {
@@ -28,6 +28,8 @@ export interface McpServerDefinition {
28
28
  pluginDataDir?: string;
29
29
  literalEnv?: boolean;
30
30
  inheritEnv?: boolean;
31
+ /** Only literal true disables a server, matching pi-mcp-adapter. */
32
+ disabled?: boolean;
31
33
  }
32
34
  export declare function isMcpServerDefinition(value: unknown): value is McpServerDefinition;
33
35
  export declare function loadPackageMcpServers(cwd: string): Record<string, McpServerDefinition>;
@@ -53,6 +53,7 @@ export interface McpRuntimeSnapshotHost {
53
53
  /** Pi 0.99: servers extensions added with `pi.registerMcpServer()`. */
54
54
  getMcpServers?(): readonly {
55
55
  name: string;
56
+ extensionPath: string;
56
57
  }[];
57
58
  }
58
59
  /** A `pi.getAllTools()` entry; `exposure` and `namespace` exist only from Pi 0.99. */
@@ -73,13 +74,12 @@ export interface McpDirectToolResolution {
73
74
  builtin?: true;
74
75
  }
75
76
  export declare function resolveMcpDirectToolResolution(mcpDirectTools: string[] | undefined, cwd?: string, runtimeSnapshotHost?: McpRuntimeSnapshotHost, configOverride?: McpConfig): McpDirectToolResolution;
76
- export declare function resolveMcpDirectToolSelections(mcpDirectTools: string[] | undefined, cwd?: string, runtimeSnapshotHost?: McpRuntimeSnapshotHost): ResolvedMcpDirectToolSelection[];
77
77
  export declare function formatUnresolvedBuiltinMcpSelectors(agentName: string | undefined, selectors: readonly string[]): string;
78
78
  /**
79
79
  * Selected servers that only an extension registered, which a child without ambient extensions
80
- * never has. A server of the same name in an `mcp.json` the child reads takes precedence; like Pi,
81
- * the project file is read only when the project is trusted.
80
+ * never has unless the registering extension is one the child loads (`loadedByChild`). A server of
81
+ * the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
82
+ * only when the project is trusted.
82
83
  */
83
- export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean): string[];
84
- export declare function resolveMcpDirectToolNames(mcpDirectTools: string[] | undefined, cwd?: string): string[];
84
+ export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean, loadedByChild: (extensionPath: string) => boolean): string[];
85
85
  export declare function computeMcpServerHash(definition: ServerEntry): string;