@xzzpig/pi-subagents 0.18.0 → 0.20.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 (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -17,6 +17,7 @@ import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
17
17
  import { planChildLaunch, projectChainOutputSchemas, resolveStepBehavior, suppressProgressForReadOnlyTask, type ResolvedStepBehavior } from "../shared/child-launch-plan.ts";
18
18
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
19
19
  import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
20
+ import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride, type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
20
21
  import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
21
22
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
22
23
  import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
@@ -89,7 +90,7 @@ import { resolvePermissionRules, type PermissionConfig } from "../shared/permiss
89
90
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
90
91
  import { omitGitRoutingEnv } from "../shared/git-environment.ts";
91
92
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
92
- import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
93
+ import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions, writeRetainedRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
93
94
 
94
95
  const require = nodeModule.createRequire(import.meta.url);
95
96
  const piPackageRoot = resolveAsyncPiPackageRoot();
@@ -112,14 +113,14 @@ function resolveAsyncPiPackageRoot(env: NodeJS.ProcessEnv = process.env): string
112
113
  function resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {
113
114
  if (!fs.existsSync(packageJsonPath)) return undefined;
114
115
  const packageRoot = path.dirname(packageJsonPath);
115
- let parsed: unknown;
116
- try {
117
- parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
118
- } catch {
119
- return undefined;
120
- }
121
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
122
- const pkg = parsed as { bin?: string | Record<string, string> };
116
+ let parsed: unknown;
117
+ try {
118
+ parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
123
+ const pkg = parsed as { bin?: string | Record<string, string> };
123
124
  const binField = pkg.bin;
124
125
  const binPath = typeof binField === "string"
125
126
  ? binField
@@ -181,13 +182,14 @@ interface AsyncExecutionContext {
181
182
  permissions?: PermissionConfig;
182
183
  currentModelProvider?: string;
183
184
  currentModel?: ParentModel;
185
+ scopedModelIds?: string[];
184
186
  /** Optional model-scope enforcement resolved from subagent settings. */
185
187
  modelScope?: ModelScopeConfig;
186
188
  /** Parent-authoritative trust state for profile-aware project config merging. */
187
189
  projectTrusted?: boolean;
188
190
  /** Exact trusted parent cwd; project config applies only when it matches the child cwd. */
189
191
  trustedProjectCwd?: string;
190
- modelResponseAliases?: Record<string, string[]>;
192
+ modelResponseAliases?: Record<string, string[]>;
191
193
  /** Whether the parent session has an interactive UI. */
192
194
  interactive?: boolean;
193
195
  /** The executor's own child runtime when the launch comes from an in-process child. */
@@ -252,6 +254,7 @@ interface AsyncChainParams {
252
254
  /** Global cap on simultaneously-running subagent tasks within the async run. */
253
255
  globalConcurrencyLimit?: number;
254
256
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
257
+ requiredExtensions?: RequiredChildExtensionSnapshot;
255
258
  thinkingCeiling?: ThinkingLevel;
256
259
  runFanoutBudget?: RunFanoutBudgetDescriptor;
257
260
  parentWorkflowRunId?: string;
@@ -270,7 +273,7 @@ interface AsyncSingleParams {
270
273
  recoveryAgentConfig?: AgentConfig;
271
274
  /** Selected global sandbox profile carried across revival. */
272
275
  sandbox?: string;
273
- requiredExtensions?: RequiredChildExtensionSnapshot;
276
+ requiredExtensions?: RequiredChildExtensionSnapshot;
274
277
  ctx: AsyncExecutionContext;
275
278
  cwd?: string;
276
279
  requestedCwd?: string;
@@ -393,6 +396,8 @@ export interface AsyncRunnerStepBuildParams {
393
396
  /** PI_SUBAGENT_TOOL_TIMEOUT_MS override (lowest precedence). */
394
397
  toolTimeoutMsEnv?: string | undefined;
395
398
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
399
+ /** Retained snapshot from the launch being continued; takes precedence over the live registry, as in single launches. */
400
+ requiredExtensions?: RequiredChildExtensionSnapshot;
396
401
  thinkingCeiling?: ThinkingLevel;
397
402
  }
398
403
 
@@ -429,8 +434,8 @@ export function isAsyncAvailable(): boolean {
429
434
  }
430
435
 
431
436
  export function resolveAsyncRunnerLogPaths(cfg: Record<string, unknown>): { stdoutPath: string; stderrPath: string } | undefined {
432
- const asyncDir = typeof cfg.asyncDir === "string"
433
- ? cfg.asyncDir
437
+ const asyncDir = typeof cfg.asyncDir === "string"
438
+ ? cfg.asyncDir
434
439
  : undefined;
435
440
  if (!asyncDir) return undefined;
436
441
  return {
@@ -738,8 +743,8 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
738
743
  ? [...preload, "--experimental-strip-types", runner, cfgPath]
739
744
  : [...preload, jitiCliPath!, runner, cfgPath];
740
745
  const runnerEnv: NodeJS.ProcessEnv = {
741
- // Fork: profile env inherited from the parent must not leak into children.
742
- ...omitGitRoutingEnv(omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env))),
746
+ // Fork: profile env inherited from the parent must not leak into children.
747
+ ...omitGitRoutingEnv(omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env))),
743
748
  ...childCacheRetentionEnv(),
744
749
  [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: binaryHost ? undefined : piPackageRoot,
745
750
  // npm must override inherited bundled layouts (#2071); binaries retain release assets.
@@ -883,6 +888,23 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
883
888
  }
884
889
  }
885
890
 
891
+ /**
892
+ * An explicit `thinking: false` clears the level, so only `undefined` falls
893
+ * through to the agent's own value. Treating `false` as absent would silently
894
+ * apply the agent default the caller just cleared.
895
+ */
896
+ export function resolveClaudeCodeThinking(source: string | false | undefined, fallback: string | false | undefined): string | undefined {
897
+ const value = source === undefined ? fallback : source;
898
+ return typeof value === "string" ? value : undefined;
899
+ }
900
+
901
+ /** A pinned Claude Code model cannot survive pane-native saved-machine placement, which
902
+ * owns the remote model registry, so the combination fails instead of losing both flags. */
903
+ export function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void {
904
+ if (!machine || !override) return;
905
+ throw new Error(`Agent '${agent}' requested machine '${machine}', but a Claude Code model or thinking level cannot be honored on a saved machine. Remove the model or thinking request, or run the agent locally.`);
906
+ }
907
+
886
908
  function formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {
887
909
  return {
888
910
  content: [{ type: "text", text: message }],
@@ -897,16 +919,16 @@ class UnavailableSubagentSkillError extends Error {}
897
919
  class AsyncStartValidationError extends Error {}
898
920
 
899
921
  function profileProjectTrustedForCwd(ctx: AsyncExecutionContext, cwd: string): boolean {
900
- return ctx.projectTrusted === true
901
- && ctx.trustedProjectCwd !== undefined
902
- && path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
922
+ return ctx.projectTrusted === true
923
+ && ctx.trustedProjectCwd !== undefined
924
+ && path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
903
925
  }
904
926
 
905
927
  function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext): string {
906
- if (ctx.projectTrusted !== true) {
907
- return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
908
- }
909
- return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the child cwd is not an exact trusted project root. Launch from that trusted cwd and retry.`;
928
+ if (ctx.projectTrusted !== true) {
929
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
930
+ }
931
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the child cwd is not an exact trusted project root. Launch from that trusted cwd and retry.`;
910
932
  }
911
933
 
912
934
  export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult {
@@ -1000,6 +1022,12 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1000
1022
  const externalRunnerType = a.runner?.type;
1001
1023
  const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: a.name, runnerType: a.runner?.type, adapter: a.runner?.type === "external-cli" ? a.runner.adapter : undefined, worktree: s.worktree });
1002
1024
  if (machineUnsupported) throw new AsyncStartValidationError(machineUnsupported);
1025
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1026
+ try {
1027
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: a.name, runnerType: a.runner?.type, machine: requestedMachine });
1028
+ } catch (error) {
1029
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1030
+ }
1003
1031
  let machine: HerdrMachineReference | undefined;
1004
1032
  let machineEnv: Record<string, string> | undefined;
1005
1033
  if (requestedMachine) {
@@ -1011,13 +1039,16 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1011
1039
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1012
1040
  }
1013
1041
  }
1042
+ // A code-owned Claude Code adapter owns its argv, but it does accept an explicit
1043
+ // model/thinking request; those become --model/--effort on the launch below.
1044
+ const claudeCodeAdapter = a.runner?.type === "external-cli" && isClaudeCodeAdapterId(a.runner.adapter);
1014
1045
  if (externalRunner) {
1015
1046
  const unsupported: string[] = [];
1016
- if (s.model !== undefined) unsupported.push("model override");
1047
+ if (s.model !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1017
1048
  if (effectiveBehavior.outputSchema !== undefined) unsupported.push("structured output");
1018
1049
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1019
1050
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
1020
- if (a.sandbox !== undefined) unsupported.push("sandbox profile");
1051
+ if (a.sandbox !== undefined) unsupported.push("sandbox profile");
1021
1052
  if ((s.fast ?? params.fast ?? a.fast) === true) unsupported.push("fast mode");
1022
1053
  if (params.contextForAgent?.(s.agent) === "fork") unsupported.push("fork context");
1023
1054
  if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
@@ -1053,10 +1084,10 @@ if (a.sandbox !== undefined) unsupported.push("sandbox profile");
1053
1084
  resolvedBehavior: effectiveBehavior,
1054
1085
  });
1055
1086
  const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
1056
- const profileChildCwd = behaviorCwd ?? stepCwd;
1057
- if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
1058
- throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
1059
- }
1087
+ const profileChildCwd = behaviorCwd ?? stepCwd;
1088
+ if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
1089
+ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
1090
+ }
1060
1091
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
1061
1092
  skillNames,
1062
1093
  stepCwd,
@@ -1081,7 +1112,7 @@ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
1081
1112
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
1082
1113
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
1083
1114
 
1084
- const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel);
1115
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
1085
1116
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
1086
1117
  const primaryModelFromParent = modelOrigin === "inherited";
1087
1118
  const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
@@ -1093,6 +1124,23 @@ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
1093
1124
  { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
1094
1125
  );
1095
1126
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
1127
+ let claudeCodeOverride: ClaudeCodeOverride | undefined;
1128
+ if (claudeCodeAdapter) {
1129
+ try {
1130
+ claudeCodeOverride = resolveClaudeCodeOverride({
1131
+ model: typeof s.model === "string" ? s.model : undefined,
1132
+ agent: a,
1133
+ thinking: resolveClaudeCodeThinking(thinkingOverride, a.thinking),
1134
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, a.maxThinking, ctx.childRuntime?.thinkingCeiling),
1135
+ agentName: a.name,
1136
+ runId: id,
1137
+ });
1138
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: claudeCodeOverride?.model, agent: a.name, runId: id });
1139
+ assertClaudeCodeOverrideIsLocal(a.name, machine ? requestedMachine : undefined, claudeCodeOverride);
1140
+ } catch (error) {
1141
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1142
+ }
1143
+ }
1096
1144
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
1097
1145
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
1098
1146
  const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1129,8 +1177,8 @@ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
1129
1177
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
1130
1178
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
1131
1179
  const fast = s.fast ?? params.fast ?? a.fast;
1132
- const requiredExtensions = externalRunner ? [] : ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1133
- const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1180
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1181
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1134
1182
  const toolPlan = resolvePiLaunchToolPlan({
1135
1183
  tools: a.tools,
1136
1184
  excludeTools: a.excludeTools,
@@ -1149,8 +1197,8 @@ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1149
1197
  agentName: a.name,
1150
1198
  permissionRules,
1151
1199
  runtimeSnapshotHost: ctx.pi,
1152
- sandbox: a.sandbox,
1153
- hostAvailableBuiltins,
1200
+ sandbox: a.sandbox,
1201
+ hostAvailableBuiltins,
1154
1202
  });
1155
1203
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1156
1204
  if (externalRunner && permissionRules) {
@@ -1159,13 +1207,14 @@ hostAvailableBuiltins,
1159
1207
  return {
1160
1208
  parentSessionId: launchParentSessionId,
1161
1209
  permissionRules,
1162
- ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1163
- ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
1210
+ ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1211
+ ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
1164
1212
  ...(params.capabilityCeiling ? { capabilityCeiling: params.capabilityCeiling } : {}),
1165
1213
  ...(runFanoutPath ? { runFanoutPath } : {}),
1166
1214
  agent: s.agent,
1167
1215
  task,
1168
1216
  ...(a.runner ? { runner: a.runner } : {}),
1217
+ ...(claudeCodeOverride ? { claudeCodeOverrideArgs: claudeCodeOverride.args } : {}),
1169
1218
  ...(machine ? { machine } : {}),
1170
1219
  ...(machineEnv ? { machineEnv } : {}),
1171
1220
  ...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
@@ -1194,8 +1243,9 @@ hostAvailableBuiltins,
1194
1243
  subagentOnlyExtensions: a.subagentOnlyExtensions,
1195
1244
  ...(!externalRunner ? { requiredExtensions } : {}),
1196
1245
  mcpDirectTools: a.mcpDirectTools,
1246
+ ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
1197
1247
  mutationTools: a.mutationTools,
1198
- ...(a.sandbox ? { sandbox: a.sandbox } : {}),
1248
+ ...(a.sandbox ? { sandbox: a.sandbox } : {}),
1199
1249
  systemPrompt,
1200
1250
  systemPromptMode: a.systemPromptMode,
1201
1251
  inheritProjectContext: a.inheritProjectContext,
@@ -1459,6 +1509,7 @@ export function executeAsyncChain(
1459
1509
  toolTimeoutMsEnv: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
1460
1510
  capabilityCeiling,
1461
1511
  thinkingCeiling: params.thinkingCeiling,
1512
+ requiredExtensions: params.requiredExtensions,
1462
1513
  });
1463
1514
  if ("error" in built) {
1464
1515
  try {
@@ -1502,6 +1553,12 @@ export function executeAsyncChain(
1502
1553
  const initialStatusAt = Date.now();
1503
1554
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1504
1555
  const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
1556
+ try {
1557
+ writeRetainedRequiredChildExtensions(asyncDir, params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(launchParentSessionId ?? undefined));
1558
+ } catch (error) {
1559
+ fs.rmSync(asyncDir, { recursive: true, force: true });
1560
+ return formatAsyncStartError(resultMode, `Failed to record required child extensions: ${error instanceof Error ? error.message : String(error)}`);
1561
+ }
1505
1562
 
1506
1563
  let spawnResult: SpawnRunnerResult = {};
1507
1564
  try {
@@ -1524,6 +1581,7 @@ export function executeAsyncChain(
1524
1581
  piPackageRoot,
1525
1582
  childSessionFactoryModule: childSessionFactoryModule(),
1526
1583
  inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1584
+ projectTrusted: ctx.projectTrusted,
1527
1585
  worktreeSetupHook,
1528
1586
  worktreeSetupHookTimeoutMs,
1529
1587
  worktreeBaseDir,
@@ -1755,16 +1813,19 @@ export function executeAsyncSingle(
1755
1813
  const externalRunner = agentConfig.runner?.type === "external-cli" || agentConfig.runner?.type === "external-job";
1756
1814
  const externalRunnerType = agentConfig.runner?.type;
1757
1815
  const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1758
- const sandbox = params.sandbox ?? agentConfig.sandbox;
1816
+ const sandbox = params.sandbox ?? agentConfig.sandbox;
1817
+ // See the chain path: the Claude Code adapter accepts an explicit model/thinking
1818
+ // request even though no other external runner does.
1819
+ const claudeCodeAdapter = agentConfig.runner?.type === "external-cli" && isClaudeCodeAdapterId(agentConfig.runner.adapter);
1759
1820
  if (externalRunner) {
1760
1821
  const unsupported: string[] = [];
1761
- if (params.modelOverride !== undefined) unsupported.push("model override");
1822
+ if (params.modelOverride !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1762
1823
  if ((params.fast ?? agentConfig.fast) === true) unsupported.push("fast mode");
1763
- if (params.thinkingOverride !== undefined) unsupported.push("thinking override");
1824
+ if (params.thinkingOverride !== undefined && !claudeCodeAdapter) unsupported.push("thinking override");
1764
1825
  if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1765
1826
  if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1766
1827
  if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
1767
- if (sandbox !== undefined) unsupported.push("sandbox profile");
1828
+ if (sandbox !== undefined) unsupported.push("sandbox profile");
1768
1829
  if (params.context === "fork") unsupported.push("fork context");
1769
1830
  if ((params.skills?.length ?? 0) > 0) unsupported.push("skills");
1770
1831
  if (permissionRules) unsupported.push("native Pi child permissions");
@@ -1781,6 +1842,12 @@ if (sandbox !== undefined) unsupported.push("sandbox profile");
1781
1842
  const requestedMachine = params.machine ?? agentConfig.machine;
1782
1843
  const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: agentConfig.name, runnerType: agentConfig.runner?.type, adapter: agentConfig.runner?.type === "external-cli" ? agentConfig.runner.adapter : undefined, worktree: params.worktree });
1783
1844
  if (machineUnsupported) return formatAsyncStartError("single", machineUnsupported);
1845
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1846
+ try {
1847
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
1848
+ } catch (error) {
1849
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1850
+ }
1784
1851
  let machine: HerdrMachineReference | undefined;
1785
1852
  let machineEnv: Record<string, string> | undefined;
1786
1853
  if (requestedMachine) {
@@ -1806,9 +1873,9 @@ if (sandbox !== undefined) unsupported.push("sandbox profile");
1806
1873
  : params.worktree === true && managedWorktreeProvider === "native"
1807
1874
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1808
1875
  : machine?.cwd ?? runnerCwd;
1809
- if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1810
- return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
1811
- }
1876
+ if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1877
+ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
1878
+ }
1812
1879
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
1813
1880
  const skillNames = params.skills ?? agentConfig.skills ?? [];
1814
1881
  const availableModels = params.availableModels;
@@ -1863,7 +1930,7 @@ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx
1863
1930
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1864
1931
  : "";
1865
1932
  const taskText = readsInstruction + taskWithOutputInstruction;
1866
- const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel);
1933
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel, ctx.scopedModelIds);
1867
1934
  const modelOrigin = resolveModelOrigin({
1868
1935
  fromParent: params.modelOverrideFromParent,
1869
1936
  storedOrigin: params.modelOrigin,
@@ -1885,6 +1952,23 @@ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx
1885
1952
  } catch (error) {
1886
1953
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1887
1954
  }
1955
+ let singleClaudeCodeOverride: ClaudeCodeOverride | undefined;
1956
+ if (claudeCodeAdapter) {
1957
+ try {
1958
+ singleClaudeCodeOverride = resolveClaudeCodeOverride({
1959
+ model: typeof params.modelOverride === "string" ? params.modelOverride : undefined,
1960
+ agent: agentConfig,
1961
+ thinking: resolveClaudeCodeThinking(params.thinkingOverride, agentConfig.thinking),
1962
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, agentConfig.maxThinking, ctx.childRuntime?.thinkingCeiling),
1963
+ agentName: agentConfig.name,
1964
+ runId: id,
1965
+ });
1966
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: singleClaudeCodeOverride?.model, agent: agentConfig.name, runId: id });
1967
+ assertClaudeCodeOverrideIsLocal(agentConfig.name, machine ? requestedMachine : undefined, singleClaudeCodeOverride);
1968
+ } catch (error) {
1969
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1970
+ }
1971
+ }
1888
1972
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1889
1973
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1890
1974
  const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1937,8 +2021,8 @@ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx
1937
2021
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1938
2022
  }
1939
2023
  }
1940
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1941
- const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
2024
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2025
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1942
2026
  const toolPlan = resolvePiLaunchToolPlan({
1943
2027
  tools: agentConfig.tools,
1944
2028
  excludeTools: agentConfig.excludeTools,
@@ -1957,8 +2041,8 @@ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1957
2041
  agentName: agentConfig.name,
1958
2042
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1959
2043
  runtimeSnapshotHost: ctx.pi,
1960
- sandbox,
1961
- hostAvailableBuiltins,
2044
+ sandbox,
2045
+ hostAvailableBuiltins,
1962
2046
  });
1963
2047
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1964
2048
  const fast = params.fast ?? agentConfig.fast;
@@ -1970,11 +2054,11 @@ hostAvailableBuiltins,
1970
2054
  ...(fast !== undefined ? { fast } : {}),
1971
2055
  ...(launchThinking ? { thinking: launchThinking } : {}),
1972
2056
  systemPrompt,
1973
- systemPromptMode: agentConfig.systemPromptMode,
1974
- inheritProjectContext: agentConfig.inheritProjectContext,
1975
- inheritGlobalContext: agentConfig.inheritGlobalContext,
1976
- inheritSkills: agentConfig.inheritSkills,
1977
- sandbox,
2057
+ systemPromptMode: agentConfig.systemPromptMode,
2058
+ inheritProjectContext: agentConfig.inheritProjectContext,
2059
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
2060
+ inheritSkills: agentConfig.inheritSkills,
2061
+ sandbox,
1978
2062
  skills: resolvedSkills.map((skill) => skill.name),
1979
2063
  toolPlan,
1980
2064
  ...(outputPath ? { outputPath } : {}),
@@ -2003,7 +2087,7 @@ sandbox,
2003
2087
  sourceRunId: id,
2004
2088
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
2005
2089
  agent,
2006
- ...(sandbox ? { sandbox } : {}),
2090
+ ...(sandbox ? { sandbox } : {}),
2007
2091
  launchResolvedExtensions,
2008
2092
  ...(sessionFile ? { sessionFile } : {}),
2009
2093
  cwd: runnerCwd,
@@ -2068,12 +2152,13 @@ sandbox,
2068
2152
  {
2069
2153
  parentSessionId: launchParentSessionId,
2070
2154
  permissionRules,
2071
- ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
2072
- ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
2155
+ ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
2156
+ ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
2073
2157
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
2074
2158
  agent,
2075
2159
  task: taskText,
2076
2160
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
2161
+ ...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
2077
2162
  ...(machine ? { machine } : {}),
2078
2163
  ...(!externalRunner && machine && params.reads !== undefined ? { remoteReads: params.reads } : {}),
2079
2164
  ...(machineEnv ? { machineEnv } : {}),
@@ -2098,8 +2183,9 @@ sandbox,
2098
2183
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
2099
2184
  ...(!externalRunner ? { requiredExtensions } : {}),
2100
2185
  mcpDirectTools: agentConfig.mcpDirectTools,
2186
+ ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
2101
2187
  mutationTools: agentConfig.mutationTools,
2102
- ...(sandbox ? { sandbox } : {}),
2188
+ ...(sandbox ? { sandbox } : {}),
2103
2189
  systemPrompt,
2104
2190
  systemPromptMode: agentConfig.systemPromptMode,
2105
2191
  inheritProjectContext: agentConfig.inheritProjectContext,
@@ -2144,6 +2230,7 @@ sandbox,
2144
2230
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
2145
2231
  piPackageRoot,
2146
2232
  childSessionFactoryModule: childSessionFactoryModule(),
2233
+ projectTrusted: ctx.projectTrusted,
2147
2234
  inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
2148
2235
  worktreeSetupHook,
2149
2236
  worktreeSetupHookTimeoutMs,
@@ -2240,7 +2327,7 @@ sandbox,
2240
2327
  mode: "single",
2241
2328
  state: "running",
2242
2329
  agent,
2243
- ...(sandbox ? { sandbox } : {}),
2330
+ ...(sandbox ? { sandbox } : {}),
2244
2331
  agents: [agent],
2245
2332
  chainStepCount: 1,
2246
2333
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
@@ -2261,7 +2348,7 @@ sandbox,
2261
2348
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
2262
2349
  mode: "single",
2263
2350
  agent,
2264
- ...(sandbox ? { sandbox } : {}),
2351
+ ...(sandbox ? { sandbox } : {}),
2265
2352
  task: task?.trim() ? PROMPT_REDACTED : undefined,
2266
2353
  goal: (params.goal ?? task).trim() ? PROMPT_REDACTED : undefined,
2267
2354
  cwd: runnerCwd,
@@ -35,6 +35,7 @@ interface AsyncJobTrackerOptions {
35
35
  pollIntervalMs?: number;
36
36
  resultsDir?: string;
37
37
  widgetEnabled?: boolean;
38
+ widgetCollapsed?: boolean;
38
39
  platform?: NodeJS.Platform;
39
40
  onJobTerminal?: () => void;
40
41
  watch?: typeof fs.watch;
@@ -51,6 +52,11 @@ const MAX_RECENT_FLEET_JOBS = 20;
51
52
  const DEFAULT_LIVENESS_INTERVAL_MS = 5000;
52
53
  const EVENT_REFRESH_DEBOUNCE_MS = 25;
53
54
  const WATCH_ATTACHMENT_RETRY_MS = 100;
55
+ /** A native supervisor request is already its own parent turn; its attention notice only escalates an unanswered one. */
56
+ const SUPERVISOR_NOTICE_GRACE_MS = 60_000;
57
+
58
+ type ControlRecord = { event: ControlEvent; channels: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
59
+ type ControlPayload = { event: ControlEvent; source: "async"; asyncDir: string; childIntercomTarget?: string; noticeText: string };
54
60
 
55
61
  const isTerminalJobStatus = (status: AsyncJobState["status"]): boolean =>
56
62
  status === "complete" || status === "failed" || status === "partial" || status === "paused" || status === "rejected" || status === "stopped";
@@ -85,6 +91,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
85
91
  // Early native failure is visible before its publisher finishes. Retain only
86
92
  // that scoped observation, using the existing liveness sweep to renew delivery.
87
93
  const terminalPublications = new Map<string, { instanceId: string; pending: true } | { pending: false }>();
94
+ const supervisorNoticeTimers = new Map<string, { asyncId: string; timer: ReturnType<typeof setTimeout> }>();
88
95
  let rootWatcher: fs.FSWatcher | undefined;
89
96
  let nextLivenessAt = Date.now() + livenessIntervalMs;
90
97
  let nextWidgetAnimationAt = Date.now() + WIDGET_ANIMATION_INTERVAL_MS;
@@ -98,7 +105,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
98
105
  };
99
106
  const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
100
107
  if (state.widgetsSuspended) return;
101
- renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
108
+ renderWidget(ctx, options.widgetEnabled === false ? [] : jobs, options.widgetCollapsed);
102
109
  (ctx.ui as { requestRender?: () => void }).requestRender?.();
103
110
  };
104
111
  const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
@@ -118,7 +125,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
118
125
  if (state.widgetsSuspended) return;
119
126
  const requestRender = (ctx.ui as { requestRender?: () => void }).requestRender;
120
127
  if (requestRender) requestRender.call(ctx.ui);
121
- else renderWidget(ctx, Array.from(state.asyncJobs.values()));
128
+ else renderWidget(ctx, Array.from(state.asyncJobs.values()), options.widgetCollapsed);
122
129
  });
123
130
  };
124
131
  const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
@@ -217,6 +224,46 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
217
224
  }, completionRetentionMs);
218
225
  state.cleanupTimers.set(asyncId, timer);
219
226
  };
227
+ const deliverControlRecord = (record: ControlRecord, payload: ControlPayload) => {
228
+ if (record.channels.includes("event")) {
229
+ pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
230
+ }
231
+ if (record.event.type !== "active_long_running" && record.channels.includes("intercom") && record.intercom?.to && record.intercom.message) {
232
+ pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
233
+ ...payload,
234
+ to: record.intercom.to,
235
+ message: record.intercom.message,
236
+ });
237
+ }
238
+ };
239
+ const readSupervisorRequestState = (event: ControlEvent, asyncDir: string): "pending" | "resolved" | "unknown" => {
240
+ try {
241
+ return options.supervisorRequestState?.(event) ?? "unknown";
242
+ } catch (error) {
243
+ console.error(`Failed to resolve supervisor request state for async control event in '${asyncDir}':`, error);
244
+ return "unknown";
245
+ }
246
+ };
247
+ const scheduleSupervisorNotice = (asyncId: string, record: ControlRecord, payload: ControlPayload) => {
248
+ const key = `${asyncId}:${record.event.index}:${record.event.toolCallId}`;
249
+ if (supervisorNoticeTimers.has(key)) return;
250
+ const timer = setTimeout(() => {
251
+ supervisorNoticeTimers.delete(key);
252
+ const job = state.asyncJobs.get(asyncId);
253
+ if (job?.status !== "running" && job?.status !== "queued") return;
254
+ if (readSupervisorRequestState(record.event, payload.asyncDir) === "resolved") return;
255
+ deliverControlRecord(record, payload);
256
+ }, SUPERVISOR_NOTICE_GRACE_MS);
257
+ timer.unref?.();
258
+ supervisorNoticeTimers.set(key, { asyncId, timer });
259
+ };
260
+ const clearSupervisorNotices = (asyncId?: string) => {
261
+ for (const [key, entry] of supervisorNoticeTimers) {
262
+ if (asyncId !== undefined && entry.asyncId !== asyncId) continue;
263
+ clearTimeout(entry.timer);
264
+ supervisorNoticeTimers.delete(key);
265
+ }
266
+ };
220
267
  const emitNewControlEvents = (job: AsyncJobState) => {
221
268
  const eventsPath = path.join(job.asyncDir, "events.jsonl");
222
269
  let fd: number;
@@ -292,34 +339,27 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
292
339
  return;
293
340
  }
294
341
  if ((parsed as { type?: unknown }).type !== "subagent.control") return;
295
- const record = parsed as { event?: ControlEvent; channels?: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
296
- if (!record.event || !Array.isArray(record.channels)) return;
297
- if (record.event.type === "needs_attention" && record.event.reason === "supervisor_request" && options.supervisorRequestState) {
298
- let requestState: "pending" | "resolved" | "unknown" = "unknown";
299
- try {
300
- requestState = options.supervisorRequestState(record.event);
301
- } catch (error) {
302
- console.error(`Failed to resolve supervisor request state for async control event in '${job.asyncDir}':`, error);
303
- }
304
- if (requestState === "resolved") return;
305
- }
306
- const payload = {
342
+ const candidate = parsed as Partial<ControlRecord>;
343
+ if (!candidate.event || !Array.isArray(candidate.channels)) return;
344
+ // SAFETY: event is present and channels is an array; every other ControlRecord field is optional.
345
+ const record = candidate as ControlRecord;
346
+ const supervisorRequest = record.event.type === "needs_attention" && record.event.reason === "supervisor_request" && options.supervisorRequestState !== undefined;
347
+ if (supervisorRequest && readSupervisorRequestState(record.event, job.asyncDir) === "resolved") return;
348
+ const payload: ControlPayload = {
307
349
  event: record.event,
308
- source: "async" as const,
350
+ source: "async",
309
351
  asyncDir: job.asyncDir,
310
352
  childIntercomTarget: record.childIntercomTarget,
311
353
  noticeText: record.noticeText ?? formatControlNoticeMessage(record.event, record.childIntercomTarget),
312
354
  };
313
- if (record.channels.includes("event")) {
314
- pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
315
- }
316
- if (record.event.type !== "active_long_running" && record.channels.includes("intercom") && record.intercom?.to && record.intercom.message) {
317
- pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
318
- ...payload,
319
- to: record.intercom.to,
320
- message: record.intercom.message,
321
- });
355
+ // External intercom asks have no native lifecycle to re-check, so they keep the immediate notice.
356
+ if (supervisorRequest && record.event.currentTool !== "intercom") {
357
+ // Status and waits still react now; the parent notice and intercom copy wait for the grace period.
358
+ if (record.channels.includes("event")) pi.events.emit(SUBAGENT_CONTROL_EVENT, { ...payload, noticeDeferred: true });
359
+ scheduleSupervisorNotice(job.asyncId, record, payload);
360
+ return;
322
361
  }
362
+ deliverControlRecord(record, payload);
323
363
  };
324
364
  let readCursor = cursor;
325
365
  let lastCompleteCursor = cursor;
@@ -380,6 +420,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
380
420
  runningJobIds.delete(asyncId);
381
421
  externalJobBridgeRuns.delete(asyncId);
382
422
  terminalPublications.delete(asyncId);
423
+ clearSupervisorNotices(asyncId);
383
424
  };
384
425
 
385
426
  const refreshJob = (job: AsyncJobState): boolean => {
@@ -773,6 +814,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
773
814
  runningJobIds.clear();
774
815
  externalJobBridgeRuns.clear();
775
816
  terminalPublications.clear();
817
+ clearSupervisorNotices();
776
818
  };
777
819
 
778
820
  const resetJobs = (ctx?: ExtensionContext) => {