@xzzpig/pi-subagents 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +13 -4
  2. package/README.md +1 -1
  3. package/agents/reviewer.md +12 -2
  4. package/docs/agents.md +4 -4
  5. package/docs/configuration.md +6 -6
  6. package/docs/extension-api.md +14 -4
  7. package/docs/models.md +47 -6
  8. package/docs/observability.md +14 -3
  9. package/docs/tool-reference.md +21 -6
  10. package/docs/workflows.md +7 -1
  11. package/index.ts +10 -1
  12. package/package.json +3 -3
  13. package/prompts/council.md +19 -7
  14. package/prompts/parallel-review.md +5 -1
  15. package/prompts/review-loop.md +9 -5
  16. package/skills/council-mode/SKILL.md +50 -26
  17. package/skills/pi-subagents/SKILL.md +5 -1
  18. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  19. package/skills/pi-subagents/references/execution-controls.md +13 -4
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  21. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  22. package/src/agents/agent-management.ts +115 -14
  23. package/src/agents/agent-serializer.ts +4 -2
  24. package/src/agents/agents.ts +226 -48
  25. package/src/api/external-job-provider.ts +10 -1
  26. package/src/api/preflight.ts +52 -19
  27. package/src/api/project-panes.ts +2 -0
  28. package/src/extension/doctor.ts +10 -0
  29. package/src/extension/fanout-child.ts +3 -2
  30. package/src/extension/index.ts +24 -4
  31. package/src/extension/public-execution.ts +12 -9
  32. package/src/extension/rpc.ts +77 -3
  33. package/src/extension/schemas.ts +7 -1
  34. package/src/extension/tool-description.ts +9 -6
  35. package/src/extension/tool-result.ts +19 -0
  36. package/src/inspectors/herdr/client.ts +3 -3
  37. package/src/inspectors/herdr/focus.ts +55 -0
  38. package/src/inspectors/herdr/project-panes.ts +228 -44
  39. package/src/integrations/herdr-status.ts +26 -4
  40. package/src/runs/background/async-execution.ts +146 -17
  41. package/src/runs/background/async-job-tracker.ts +33 -14
  42. package/src/runs/background/async-resume.ts +23 -2
  43. package/src/runs/background/async-retention.ts +1 -1
  44. package/src/runs/background/async-status.ts +10 -0
  45. package/src/runs/background/chain-root-attachment.ts +5 -0
  46. package/src/runs/background/control-channel.ts +98 -10
  47. package/src/runs/background/notify.ts +62 -1
  48. package/src/runs/background/result-watcher.ts +4 -3
  49. package/src/runs/background/run-status.ts +15 -1
  50. package/src/runs/background/stale-run-reconciler.ts +3 -0
  51. package/src/runs/background/subagent-runner.ts +333 -48
  52. package/src/runs/background/wait-completions.ts +2 -0
  53. package/src/runs/background/wait-tool.ts +4 -3
  54. package/src/runs/foreground/async-stop-action.ts +23 -2
  55. package/src/runs/foreground/execution.ts +148 -13
  56. package/src/runs/foreground/foreground-history.ts +3 -2
  57. package/src/runs/foreground/subagent-executor.ts +417 -50
  58. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  59. package/src/runs/shared/acceptance.ts +11 -5
  60. package/src/runs/shared/agent-contract.ts +1 -1
  61. package/src/runs/shared/child-identity.ts +36 -0
  62. package/src/runs/shared/completion-guard.ts +52 -2
  63. package/src/runs/shared/dynamic-fanout.ts +1 -1
  64. package/src/runs/shared/extension-bindings.ts +78 -0
  65. package/src/runs/shared/external-cli-runner.ts +2 -0
  66. package/src/runs/shared/external-job-bridge.ts +53 -37
  67. package/src/runs/shared/external-job-runner.ts +126 -23
  68. package/src/runs/shared/fast-mode-extension.ts +10 -0
  69. package/src/runs/shared/model-exclusions.ts +2 -1
  70. package/src/runs/shared/model-fallback.ts +48 -22
  71. package/src/runs/shared/model-scope.ts +106 -39
  72. package/src/runs/shared/mutation-evidence.ts +145 -0
  73. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  74. package/src/runs/shared/parallel-utils.ts +15 -0
  75. package/src/runs/shared/pi-args.ts +78 -1
  76. package/src/runs/shared/structured-output.ts +18 -4
  77. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  78. package/src/runs/shared/tool-availability.ts +1 -3
  79. package/src/shared/launch-contract.ts +12 -5
  80. package/src/shared/settings.ts +6 -1
  81. package/src/shared/thinking-ceiling.ts +52 -0
  82. package/src/shared/types.ts +120 -5
  83. package/src/tui/fleet-status.ts +66 -13
  84. package/src/tui/render.ts +5 -4
  85. package/src/watchdog/permission-arbiter.ts +59 -52
  86. package/src/workflows/scripted-workflow.ts +156 -12
@@ -44,6 +44,7 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
44
44
  const childRunId = asNonEmptyString(child.runId);
45
45
  const error = asNonEmptyString(child.error);
46
46
  const model = asNonEmptyString(child.model);
47
+ const contextOverflow = child.contextOverflow === true;
47
48
  return [{
48
49
  ...(agent ? { agent } : {}),
49
50
  ...(childRunId ? { runId: childRunId } : {}),
@@ -51,6 +52,7 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
51
52
  ...(outputState ? { outputState } : {}),
52
53
  ...(error ? { error } : {}),
53
54
  ...(model ? { model } : {}),
55
+ ...(contextOverflow ? { contextOverflow: true } : {}),
54
56
  ...(artifactPaths ? { artifactPaths } : {}),
55
57
  }];
56
58
  })
@@ -3,6 +3,7 @@ import { SubagentWaitParams } from "../../extension/schemas.ts";
3
3
  import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
5
5
  import type { WaitSubscriptionManager } from "./wait-subscriptions.ts";
6
+ import { finalizeToolResult } from "../../extension/tool-result.ts";
6
7
 
7
8
  export function registerWaitTool(pi: ExtensionAPI, state: SubagentState, enabled = resolveWaitToolConfig().enabled, subscriptions?: Pick<WaitSubscriptionManager, "arm">): void {
8
9
  const tool: ToolDefinition<typeof SubagentWaitParams, Details> = {
@@ -21,14 +22,14 @@ In an interactive chat, do not call this merely to wait: return control to the u
21
22
 
22
23
  Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`subagent_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : "\n\nConfigured behavior: subagent_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`,
23
24
  parameters: SubagentWaitParams,
24
- execute(_id, params, signal, onUpdate, ctx) {
25
- return waitForSubagents(params, signal, {
25
+ async execute(_id, params, signal, onUpdate, ctx) {
26
+ return finalizeToolResult(await waitForSubagents(params, signal, {
26
27
  state,
27
28
  events: pi.events,
28
29
  enabled,
29
30
  onUpdate,
30
31
  ...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
31
- });
32
+ }));
32
33
  },
33
34
  };
34
35
  pi.registerTool(tool);
@@ -3,6 +3,7 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
3
  import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { deliverStopRequest } from "../background/control-channel.ts";
5
5
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
6
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
6
7
 
7
8
  function getAsyncStopTarget(
8
9
  state: SubagentState,
@@ -25,6 +26,7 @@ export function stopAsyncRun(
25
26
  runId: string | undefined,
26
27
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,
27
28
  location?: { asyncDir: string | null; resolvedId?: string },
29
+ childId?: string,
28
30
  ): AgentToolResult<Details> | null {
29
31
  const target = getAsyncStopTarget(state, runId, location);
30
32
  if (!target) return null;
@@ -43,15 +45,34 @@ export function stopAsyncRun(
43
45
  details: { mode: "management", results: [] },
44
46
  };
45
47
  }
48
+ let child: ResolvedAsyncStatusChild | undefined;
49
+ if (childId !== undefined) {
50
+ const resolution = resolveAsyncStatusChild(status, childId);
51
+ if (!resolution.ok) {
52
+ return {
53
+ content: [{ type: "text", text: resolution.message }],
54
+ isError: true,
55
+ details: { mode: "management", results: [] },
56
+ };
57
+ }
58
+ child = resolution.child;
59
+ if (!isStoppableAsyncStatusStep(child.step)) {
60
+ return {
61
+ content: [{ type: "text", text: `Child '${childId}' in async run '${status.runId}' is ${child.step.status}; stop only supports pending or running children.` }],
62
+ isError: true,
63
+ details: { mode: "management", results: [] },
64
+ };
65
+ }
66
+ }
46
67
  try {
47
- deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action" });
68
+ deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
48
69
  const tracked = state.asyncJobs.get(target.asyncId);
49
70
  if (tracked) {
50
71
  tracked.activityState = undefined;
51
72
  tracked.updatedAt = Date.now();
52
73
  }
53
74
  return {
54
- content: [{ type: "text", text: `Stop requested for async run ${target.asyncId}.` }],
75
+ content: [{ type: "text", text: child ? `Stop requested for child ${child.id} in async run ${target.asyncId}.` : `Stop requested for async run ${target.asyncId}.` }],
55
76
  details: { mode: "management", results: [] },
56
77
  };
57
78
  } catch (error) {
@@ -55,7 +55,7 @@ import {
55
55
  import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
56
56
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
57
57
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
58
- import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
58
+ import { evaluateCompletionMutationGuard, validateImplementationToolContract } from "../shared/completion-guard.ts";
59
59
  import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
60
60
  import { getPiSpawnCommand } from "../shared/pi-spawn.ts";
61
61
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
@@ -66,13 +66,17 @@ import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolved
66
66
  import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
67
67
  import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV } from "../shared/capability-ceiling.ts";
68
68
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
69
- import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
69
+ import { assertThinkingWithinCeiling, decodeThinkingCeiling, intersectThinkingCeilings, SUBAGENT_THINKING_CEILING_ENV } from "../../shared/thinking-ceiling.ts";
70
+ import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
70
71
  import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
71
72
  import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
73
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
72
74
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
73
75
  import {
74
76
  buildModelCandidates,
77
+ formatSubagentModelVerificationError,
75
78
  formatModelAttemptNote,
79
+ isContextOverflow,
76
80
  isRetryableModelFailure,
77
81
  recordRetryableModelFailure,
78
82
  } from "../shared/model-fallback.ts";
@@ -308,10 +312,14 @@ async function runSingleAttempt(
308
312
  originalTask?: string;
309
313
  taskDelivery?: SubagentTaskDelivery;
310
314
  orcaProgressTab?: OrcaProgressTab;
315
+ launchWarnings: { emitted: boolean };
316
+ verifyModel: boolean;
311
317
  },
312
318
  ): Promise<SingleResult> {
313
319
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
314
320
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
321
+ assertThinkingWithinCeiling({ model: modelArg, configThinking: effectiveThinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
322
+ const expectedModelForVerification = shared.verifyModel ? modelArg : undefined;
315
323
  const resolvedThinking = resolveEffectiveThinking(modelArg, effectiveThinking);
316
324
  const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
317
325
  const childWatchdog = watchdogConfig.ok
@@ -326,7 +334,7 @@ async function runSingleAttempt(
326
334
  const permissionAuditPath = permissionRules && options.artifactsDir
327
335
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
328
336
  : undefined;
329
- const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit } = buildPiArgs({
337
+ const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit, warnings } = buildPiArgs({
330
338
  baseArgs: ["--mode", "json", "-p"],
331
339
  task,
332
340
  taskDelivery: shared.taskDelivery,
@@ -361,6 +369,8 @@ async function runSingleAttempt(
361
369
  steerCapabilityPath: options.steerCapabilityPath,
362
370
  steerAckDir: options.steerAckDir,
363
371
  structuredOutput: options.structuredOutput,
372
+ fast: options.fast ?? agent.fast,
373
+ modelCandidates: shared.modelCandidates,
364
374
  toolBudget: options.toolBudget,
365
375
  allowZeroToolBudget: options.allowZeroToolBudget,
366
376
  permissionRules,
@@ -368,7 +378,13 @@ async function runSingleAttempt(
368
378
  childWatchdog,
369
379
  waitToolEnabled: options.waitToolEnabled,
370
380
  capabilityCeiling: options.capabilityCeiling,
381
+ thinkingCeiling: options.thinkingCeiling,
382
+ extensionBindings: options.extensionBindings,
371
383
  });
384
+ if (!shared.launchWarnings.emitted && warnings.length > 0) {
385
+ for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
386
+ shared.launchWarnings.emitted = true;
387
+ }
372
388
 
373
389
  const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(shared.systemPrompt, options.turnBudget);
374
390
  const toolPlan = resolvePiLaunchToolPlan({
@@ -379,17 +395,53 @@ async function runSingleAttempt(
379
395
  cwd: options.cwd ?? runtimeCwd,
380
396
  requireReadTool: Boolean(shared.resolvedSkillNames?.length),
381
397
  structuredOutput: Boolean(options.structuredOutput),
398
+ fast: options.fast ?? agent.fast,
399
+ model: modelArg,
400
+ modelCandidates: shared.modelCandidates,
382
401
  capabilityCeiling: options.capabilityCeiling,
383
402
  inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
384
403
  agentName: agent.name,
404
+ permissionRules,
405
+ });
406
+ const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
407
+ const contractError = validateImplementationToolContract({
408
+ agent: agent.name,
409
+ task: shared.originalTask ?? task,
410
+ tools: contractTools,
411
+ mcpDirectTools: toolPlan.effectiveMcpTools,
412
+ configuredExtensions: toolPlan.configuredExtensions,
413
+ requestedTools: toolPlan.requestedBuiltinTools,
414
+ acceptanceRole: agent.acceptanceRole,
415
+ completionGuard: agent.completionGuard,
385
416
  });
417
+ if (contractError) {
418
+ cleanupTempDir(tempDir);
419
+ return {
420
+ index: options.index ?? 0,
421
+ agent: agent.name,
422
+ task,
423
+ messages: [],
424
+ finalOutput: "",
425
+ exitCode: 1,
426
+ error: contractError,
427
+ usage: emptyUsage(),
428
+ model: modelArg,
429
+ modelAttempts: [],
430
+ attemptedModels: [],
431
+ progressSummary: { status: "failed", toolCount: 0, tokens: 0, durationMs: 0 },
432
+ ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
433
+ ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
434
+ };
435
+ }
386
436
  const launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
387
437
  const launchContractDigest = launchBindingDigest({
388
438
  definitionDigest: agentDefinitionDigest(agent),
389
439
  task: shared.originalTask ?? task,
390
440
  ...(modelArg ? { model: modelArg } : {}),
391
441
  modelCandidates: shared.modelCandidates,
442
+ ...((options.fast ?? agent.fast) !== undefined ? { fast: options.fast ?? agent.fast } : {}),
392
443
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
444
+ ...(options.thinkingCeiling ? { thinkingCeiling: options.thinkingCeiling } : {}),
393
445
  systemPrompt: effectiveSystemPrompt,
394
446
  systemPromptMode: agent.systemPromptMode,
395
447
  inheritProjectContext: agent.inheritProjectContext,
@@ -401,6 +453,7 @@ async function runSingleAttempt(
401
453
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
402
454
  outputMode: options.outputMode ?? "inline",
403
455
  ...(options.structuredOutput ? { structuredOutputSchema: options.structuredOutput.schema } : {}),
456
+ ...(options.extensionBindings ? { extensionBindings: options.extensionBindings } : {}),
404
457
  });
405
458
  const result: SingleResult = withRunContext({
406
459
  index: options.index ?? 0,
@@ -480,9 +533,11 @@ async function runSingleAttempt(
480
533
  return result;
481
534
  }
482
535
  const spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) };
536
+ const mutationSnapshot = snapshotTrackedMutations(options.cwd ?? runtimeCwd);
483
537
  let observedMutationAttempt = false;
484
538
  let structuredOutputToolInvoked = false;
485
539
  let structuredOutputMessageStartIndex: number | undefined;
540
+ let toolAvailabilityError: string | undefined;
486
541
 
487
542
  const exitCode = await new Promise<number>((resolve) => {
488
543
  const spawnSpec = getPiSpawnCommand(args);
@@ -1090,7 +1145,12 @@ async function runSingleAttempt(
1090
1145
  if (evt.message.model) {
1091
1146
  progress.model = evt.message.model;
1092
1147
  if (!result.model) result.model = evt.message.model;
1148
+ if (expectedModelForVerification && !hasToolCall) {
1149
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
1150
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1151
+ }
1093
1152
  }
1153
+
1094
1154
  if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1095
1155
  const assistantText = extractTextFromContent(evt.message.content);
1096
1156
  appendRecentOutput(progress, assistantText.split("\n").slice(-10));
@@ -1107,6 +1167,23 @@ async function runSingleAttempt(
1107
1167
  }
1108
1168
 
1109
1169
  if (evt.type === "tool_result_end" && evt.message) {
1170
+ const toolResultCompletion = {
1171
+ toolCallId: (evt.message as { toolCallId?: unknown }).toolCallId ?? (evt as { toolCallId?: unknown }).toolCallId,
1172
+ toolName: (evt.message as { toolName?: unknown }).toolName ?? (evt as { toolName?: unknown }).toolName,
1173
+ };
1174
+ clearActiveToolTimeout(toolResultCompletion);
1175
+ const endedTool = removeActiveToolCall(toolResultCompletion);
1176
+ if (endedTool) {
1177
+ progress.recentTools.push({
1178
+ tool: endedTool.tool,
1179
+ args: endedTool.args,
1180
+ endMs: now,
1181
+ });
1182
+ refreshCurrentTool();
1183
+ }
1184
+ // Fork: the shared, id-deduplicated tool-result tail (message push,
1185
+ // budget, mutating-failure tracking, output) lives in handleToolResult;
1186
+ // hosts may deliver the same result via message_end(role=toolResult).
1110
1187
  handleToolResult(evt.message, now);
1111
1188
  }
1112
1189
  };
@@ -1273,6 +1350,7 @@ async function runSingleAttempt(
1273
1350
  // JSONL artifact flush is best effort.
1274
1351
  });
1275
1352
  const toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
1353
+ toolAvailabilityError = toolDiagnosticError;
1276
1354
  result.runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1277
1355
  cleanupTempDir(tempDir);
1278
1356
  stdoutReader.end();
@@ -1411,6 +1489,9 @@ async function runSingleAttempt(
1411
1489
  result.structuredOutputFailed = true;
1412
1490
  } else {
1413
1491
  result.structuredOutput = structured.value;
1492
+ const acceptanceReport = readStructuredOutputAcceptanceReport(options.structuredOutput);
1493
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceReport.value;
1494
+ (result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReport.error;
1414
1495
  validatedStructuredOutput = true;
1415
1496
  }
1416
1497
  }
@@ -1448,6 +1529,7 @@ async function runSingleAttempt(
1448
1529
  tokens: progress.tokens,
1449
1530
  durationMs: progress.durationMs,
1450
1531
  };
1532
+ const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, options.cwd ?? runtimeCwd);
1451
1533
 
1452
1534
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1453
1535
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1455,9 +1537,19 @@ async function runSingleAttempt(
1455
1537
  result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
1456
1538
  if (result.timedOut) {
1457
1539
  const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
1540
+ result.timeoutRecovery = buildTimeoutRecoverySummary({
1541
+ termination: "timed-out",
1542
+ evidence: mutationEvidence,
1543
+ currentTool: progress.currentTool,
1544
+ currentToolArgs: progress.currentToolArgs,
1545
+ currentPath: progress.currentPath,
1546
+ sessionFile: options.sessionFile,
1547
+ transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
1548
+ artifactPaths: shared.artifactPaths,
1549
+ });
1458
1550
  fullOutput = fullOutput.trim()
1459
- ? `${timeoutMessage}\n\nPartial output before timeout:\n${fullOutput}`
1460
- : timeoutMessage;
1551
+ ? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
1552
+ : `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
1461
1553
  } else if (result.turnBudgetExceeded && result.turnBudget) {
1462
1554
  fullOutput = formatTurnBudgetOutput(turnBudgetExceededMessage(result.turnBudget, result.turnBudget.turnCount), fullOutput);
1463
1555
  } else if (result.turnBudget?.outcome === "termination-deferred") {
@@ -1468,16 +1560,20 @@ async function runSingleAttempt(
1468
1560
  fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
1469
1561
  }
1470
1562
  const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
1471
- const completionGuard = result.exitCode === 0 && !result.error && completionGuardEnabled
1563
+ const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
1472
1564
  ? evaluateCompletionMutationGuard({
1473
1565
  agent: agent.name,
1474
1566
  task: shared.originalTask ?? task,
1475
1567
  messages: result.messages ?? [],
1476
- tools: agent.tools,
1477
- mcpDirectTools: agent.mcpDirectTools,
1568
+ tools: contractTools,
1569
+ mcpDirectTools: toolPlan.effectiveMcpTools,
1570
+ toolAvailabilityError,
1571
+ mutationEvidence,
1478
1572
  })
1479
1573
  : undefined;
1480
- let completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1574
+ const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
1575
+ let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
1576
+ const completionGuardBlocked = completionGuard?.blocked === true;
1481
1577
  // The classifier is deliberately narrow, so a read-only review task can
1482
1578
  // still be misread as implementation. Arbitrate BEFORE any failure side
1483
1579
  // effect is published (effects, exit code, progress, notifications,
@@ -1498,7 +1594,9 @@ async function runSingleAttempt(
1498
1594
  result.effects = {
1499
1595
  ...(result.effects ?? {}),
1500
1596
  fileMutation: {
1501
- status: completionGuard.expectedMutation
1597
+ status: completionGuardBlocked
1598
+ ? "blocked"
1599
+ : completionGuard.expectedMutation
1502
1600
  ? completionGuardTriggered
1503
1601
  ? "missing"
1504
1602
  : arbiterRescued
@@ -1506,7 +1604,9 @@ async function runSingleAttempt(
1506
1604
  : "observed"
1507
1605
  : "not-applicable",
1508
1606
  expected: completionGuard.expectedMutation,
1509
- attempted: completionGuard.attemptedMutation || observedMutationAttempt,
1607
+ attempted: completionGuardBlocked ? false : completionGuard.attemptedMutation || mutationAttemptObserved,
1608
+ evidence: mutationEvidence,
1609
+ ...(completionGuardBlocked && completionGuard.message ? { message: completionGuard.message } : {}),
1510
1610
  ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1511
1611
  ...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
1512
1612
  },
@@ -1588,6 +1688,14 @@ async function runSyncCompletionInner(
1588
1688
  error: `Unknown agent: ${agentName}`,
1589
1689
  }, options.context));
1590
1690
  }
1691
+ options = {
1692
+ ...options,
1693
+ thinkingCeiling: intersectThinkingCeilings(
1694
+ options.thinkingCeiling,
1695
+ agent.maxThinking,
1696
+ decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
1697
+ ),
1698
+ };
1591
1699
  try {
1592
1700
  assertAgentAllowedByCapabilityCeiling(agent.name, options.capabilityCeiling);
1593
1701
  } catch (error) {
@@ -1658,7 +1766,7 @@ async function runSyncCompletionInner(
1658
1766
  dynamicGroup: options.acceptanceContext?.dynamicGroup,
1659
1767
  agentContract: options.agentContract,
1660
1768
  });
1661
- const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1769
+ const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract), structuredOutput: Boolean(options.structuredOutput?.acceptanceReportPath) });
1662
1770
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1663
1771
  options.onEffectivePrompt?.(taskWithAcceptance);
1664
1772
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
@@ -1701,13 +1809,30 @@ async function runSyncCompletionInner(
1701
1809
  options.modelOverride ?? agent.model,
1702
1810
  agent.fallbackModels,
1703
1811
  options.availableModels,
1704
- options.preferredModelProvider,
1812
+ agent.modelProvider ?? options.preferredModelProvider,
1705
1813
  { scope: options.modelScope, primaryModelFromParent: options.modelOverrideFromParent },
1706
1814
  );
1815
+ try {
1816
+ for (const candidate of candidates) {
1817
+ const model = applyThinkingSuffix(candidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
1818
+ assertThinkingWithinCeiling({ model, configThinking: options.thinkingOverride ?? agent.thinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
1819
+ }
1820
+ } catch (error) {
1821
+ return redactResultPrompt(withRunContext({
1822
+ index: options.index ?? 0,
1823
+ agent: agent.name,
1824
+ task,
1825
+ exitCode: 1,
1826
+ messages: [],
1827
+ usage: emptyUsage(),
1828
+ error: error instanceof Error ? error.message : String(error),
1829
+ }, options.context));
1830
+ }
1707
1831
  const attemptedModels: string[] = [];
1708
1832
  const modelAttempts: ModelAttempt[] = [];
1709
1833
  const aggregateUsage = emptyUsage();
1710
1834
  const attemptNotes: string[] = [];
1835
+ const launchWarnings = { emitted: false };
1711
1836
  let totalToolCount = 0;
1712
1837
  let totalDurationMs = 0;
1713
1838
 
@@ -1782,6 +1907,7 @@ async function runSyncCompletionInner(
1782
1907
  modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1783
1908
  const candidate = modelsToTry[modelIndex];
1784
1909
  for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
1910
+ const verifyModel = Boolean(candidate) && !(options.modelOverrideFromParent && modelIndex === 0);
1785
1911
  const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
1786
1912
  const result = await runSingleAttempt(runtimeCwd, agent, taskWithAcceptance, candidate, attemptOptions, {
1787
1913
  sessionEnabled,
@@ -1799,6 +1925,8 @@ async function runSyncCompletionInner(
1799
1925
  originalTask: task,
1800
1926
  taskDelivery: taskDeliveryOverride,
1801
1927
  orcaProgressTab,
1928
+ launchWarnings,
1929
+ verifyModel,
1802
1930
  });
1803
1931
  lastResult = result;
1804
1932
  if (startupAttemptIndex === 0) {
@@ -1891,6 +2019,11 @@ async function runSyncCompletionInner(
1891
2019
  }
1892
2020
  const retryableModelFailure = isRetryableModelFailure(result.error);
1893
2021
  if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
2022
+ if (isContextOverflow(result.error)) {
2023
+ result.contextOverflow = true;
2024
+ attemptNotes.push(`[fallback] ${attempt.model} failed: context overflow — the input exceeds this model's context window. Reduce the task input or use a model with a larger context window.`);
2025
+ break modelAttemptsLoop;
2026
+ }
1894
2027
  if (!retryableModelFailure || modelIndex === modelsToTry.length - 1) break modelAttemptsLoop;
1895
2028
  attemptNotes.push(formatModelAttemptNote(attempt, modelsToTry[modelIndex + 1]));
1896
2029
  break;
@@ -1970,6 +2103,8 @@ async function runSyncCompletionInner(
1970
2103
  result.acceptance = await evaluateAcceptance({
1971
2104
  acceptance: effectiveAcceptance,
1972
2105
  output: acceptanceOutputByResult.get(result) ?? result.finalOutput ?? "",
2106
+ report: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReport,
2107
+ reportError: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError,
1973
2108
  fileOutput: childWrittenOutput !== undefined && options.outputPath
1974
2109
  ? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only" }
1975
2110
  : undefined,
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ForegroundResumeChild, ForegroundResumeRun, SubagentState } from "../../shared/types.ts";
4
4
  import { DIRS } from "../../shared/types.ts";
5
- import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
6
6
  import { utf8Tail } from "../../shared/utf8.ts";
7
7
 
8
8
  export const MAX_REMEMBERED_FOREGROUND_RUNS = 50;
@@ -52,6 +52,7 @@ function compactChild(child: ForegroundResumeChild): ForegroundResumeChild {
52
52
  ...(child.transcriptError ? { transcriptError: child.transcriptError } : {}),
53
53
  ...(child.acceptance ? { acceptance: child.acceptance } : {}),
54
54
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
55
+ ...(child.extensionBindings ? { extensionBindings: child.extensionBindings } : {}),
55
56
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
56
57
  ...(child.updatedAt !== undefined ? { updatedAt: child.updatedAt } : {}),
57
58
  };
@@ -118,7 +119,7 @@ export function persistForegroundRunHistory(state: SubagentState, options: { res
118
119
  if (compact) merged.set(compact.runId, compact);
119
120
  }
120
121
  const runs = sortAndBound([...merged.values()], limit);
121
- writeAtomicJson(historyPath(resultsDir), { version: HISTORY_VERSION, runs });
122
+ writePrivateAtomicJson(historyPath(resultsDir), { version: HISTORY_VERSION, runs });
122
123
  }
123
124
 
124
125
  export function restoreForegroundRunHistory(state: SubagentState, options: { resultsDir?: string; sessionId?: string | null; limit?: number } = {}): number {