@vicary/pi-subagents 0.85.0 → 0.87.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 (97) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-O7CPL6H4.js → chunk-2D2DQGC2.js} +9 -9
  5. package/bundle/{chunk-KZ34KQQH.js → chunk-2NY5PCKQ.js} +11 -5
  6. package/bundle/{chunk-PVIVCDG2.js → chunk-3CVOAS77.js} +2 -2
  7. package/bundle/{chunk-N7B2KD74.js → chunk-6O7YH2QV.js} +1 -1
  8. package/bundle/{chunk-B3OOJJA6.js → chunk-75LVXBSA.js} +194 -94
  9. package/bundle/{chunk-H2NLFTC5.js → chunk-BFF6YDK6.js} +1 -1
  10. package/bundle/{chunk-UX4SCV5N.js → chunk-C3KWLXDH.js} +159 -98
  11. package/bundle/{chunk-GCSLVFCX.js → chunk-C5QWQSSM.js} +1 -1
  12. package/bundle/{chunk-KDMFBYFM.js → chunk-ESWW6XSX.js} +1 -1
  13. package/bundle/{chunk-CS4O36CZ.js → chunk-HDICKROY.js} +5 -5
  14. package/bundle/{chunk-JHBQ7N2L.js → chunk-HTI7DD5D.js} +2 -2
  15. package/bundle/{chunk-L2ENOFVZ.js → chunk-LZKVUWIY.js} +66 -26
  16. package/bundle/{chunk-RV5OGHLO.js → chunk-M2VBGET6.js} +2 -2
  17. package/bundle/{chunk-QZL2ZZPM.js → chunk-NJTSXIMG.js} +12 -12
  18. package/bundle/{chunk-YZBCREP5.js → chunk-NMYBVCGP.js} +39 -34
  19. package/bundle/{chunk-A7VJ5XXE.js → chunk-O7A26O6B.js} +8 -6
  20. package/bundle/{chunk-HFTBF7SG.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-LGMILZNE.js → chunk-PGU4TZV3.js} +79 -32
  22. package/bundle/{chunk-VEZMZDTW.js → chunk-PUSTU4Q7.js} +80 -37
  23. package/bundle/{chunk-KEY3UQMQ.js → chunk-SIAQXPJ4.js} +6 -8
  24. package/bundle/{chunk-QO75KJBT.js → chunk-USRX7QXD.js} +2 -2
  25. package/bundle/{chunk-7MAE3DJV.js → chunk-VFUFOZBU.js} +1 -1
  26. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  27. package/bundle/{chunk-T5V5BRCL.js → chunk-W52LJANO.js} +1 -1
  28. package/bundle/{chunk-PHZP3KHB.js → chunk-XSDYTXHF.js} +18 -11
  29. package/bundle/{chunk-LTPH2DXH.js → chunk-XV7RTWTS.js} +3 -3
  30. package/bundle/{chunk-JO67XSKD.js → chunk-YEXKJJVS.js} +12 -7
  31. package/bundle/{chunk-HS4WPO6B.js → chunk-Z4TR7MK6.js} +5 -5
  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 +12 -10
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/workflow-resources.js +1 -1
  38. package/docs/agents.md +9 -3
  39. package/docs/configuration.md +14 -6
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/tool-reference.md +3 -0
  43. package/package.json +2 -2
  44. package/skills/pi-subagents/SKILL.md +7 -4
  45. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  46. package/src/agents/agent-management.js +10 -6
  47. package/src/agents/agent-serializer.d.ts +2 -0
  48. package/src/agents/agent-serializer.js +1 -1
  49. package/src/agents/agents.js +37 -12
  50. package/src/api/preflight.d.ts +3 -1
  51. package/src/api/preflight.js +2 -0
  52. package/src/extension/index.js +4 -2
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/tool-activation.js +10 -1
  56. package/src/extension/tool-description.d.ts +1 -1
  57. package/src/extension/tool-description.js +8 -8
  58. package/src/runs/background/async-execution.d.ts +2 -1
  59. package/src/runs/background/async-execution.js +4 -2
  60. package/src/runs/background/run-status.js +5 -4
  61. package/src/runs/background/runner-aliases.js +15 -0
  62. package/src/runs/background/subagent-runner.js +6 -6
  63. package/src/runs/background/wait-subscriptions.js +124 -12
  64. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  65. package/src/runs/foreground/async-stop-action.js +9 -1
  66. package/src/runs/foreground/execution.js +1 -0
  67. package/src/runs/foreground/subagent-executor.d.ts +1 -0
  68. package/src/runs/foreground/subagent-executor.js +51 -8
  69. package/src/runs/shared/acceptance.js +69 -26
  70. package/src/runs/shared/child-session.d.ts +5 -4
  71. package/src/runs/shared/child-session.js +43 -33
  72. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  73. package/src/runs/shared/external-cli-contract.js +18 -13
  74. package/src/runs/shared/herdr-placed-run.js +3 -2
  75. package/src/runs/shared/mcp-config-sources.d.ts +2 -1
  76. package/src/runs/shared/mcp-config-sources.js +1 -1
  77. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -1
  78. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -6
  79. package/src/runs/shared/model-resolution.d.ts +19 -4
  80. package/src/runs/shared/model-resolution.js +50 -51
  81. package/src/runs/shared/structured-output.js +10 -3
  82. package/src/shared/artifacts.js +25 -13
  83. package/src/shared/pruned-fork.js +2 -2
  84. package/src/shared/types.d.ts +71 -48
  85. package/src/tui/render.js +83 -22
  86. package/src/watchdog/model-selection.js +2 -2
  87. package/src/watchdog/review.js +2 -2
  88. package/src/workflows/scripted-workflow.d.ts +2 -0
  89. package/src/workflows/scripted-workflow.js +103 -39
  90. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  91. package/src/workflows/structured-workflow-scripts.js +32 -11
  92. package/src/workflows/workflow-receipt.js +36 -53
  93. package/src/workflows/workflow-resources.js +4 -4
  94. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  95. package/src/workflows/workflow-resume-claim.js +1 -1
  96. package/src/workflows/workflow-resume.d.ts +1 -1
  97. package/src/workflows/workflow-resume.js +3 -1
@@ -953,21 +953,24 @@ function readSubagentSettings(filePath) {
953
953
  const subagentsObject = subagents;
954
954
  let disableBuiltins;
955
955
  if ("disableBuiltins" in subagentsObject) {
956
- if (typeof subagentsObject.disableBuiltins === "boolean") {
956
+ if (typeof subagentsObject.disableBuiltins === "boolean")
957
957
  disableBuiltins = subagentsObject.disableBuiltins;
958
- }
959
- else {
958
+ else
960
959
  throw new Error(`Subagent settings in '${filePath}' have invalid 'disableBuiltins'; expected a boolean.`);
961
- }
962
960
  }
963
961
  let disableThinking;
964
962
  if ("disableThinking" in subagentsObject) {
965
- if (typeof subagentsObject.disableThinking === "boolean") {
963
+ if (typeof subagentsObject.disableThinking === "boolean")
966
964
  disableThinking = subagentsObject.disableThinking;
967
- }
968
- else {
965
+ else
969
966
  throw new Error(`Subagent settings in '${filePath}' have invalid 'disableThinking'; expected a boolean.`);
970
- }
967
+ }
968
+ let defaultInheritGlobalContext;
969
+ if ("defaultInheritGlobalContext" in subagentsObject) {
970
+ if (typeof subagentsObject.defaultInheritGlobalContext === "boolean")
971
+ defaultInheritGlobalContext = subagentsObject.defaultInheritGlobalContext;
972
+ else
973
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'defaultInheritGlobalContext'; expected a boolean.`);
971
974
  }
972
975
  let defaultModel;
973
976
  if ("defaultModel" in subagentsObject) {
@@ -1051,6 +1054,7 @@ function readSubagentSettings(filePath) {
1051
1054
  ...(maxThinking !== undefined ? { maxThinking } : {}),
1052
1055
  ...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
1053
1056
  ...(defaultSubagentOnlyExtensions !== undefined ? { defaultSubagentOnlyExtensions } : {}),
1057
+ ...(defaultInheritGlobalContext !== undefined ? { defaultInheritGlobalContext } : {}),
1054
1058
  ...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
1055
1059
  ...(agentExcludeDirs !== undefined ? { agentExcludeDirs } : {}),
1056
1060
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
@@ -1189,8 +1193,27 @@ function applySubagentDefaultSubagentOnlyExtensions(agents, defaultSubagentOnlyE
1189
1193
  return next;
1190
1194
  });
1191
1195
  }
1192
- function applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions) {
1193
- return applySubagentDefaultSubagentOnlyExtensions(applySubagentDefaultExtensions(applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking), defaultExtensions), defaultSubagentOnlyExtensions);
1196
+ function resolveSubagentDefaultInheritGlobalContext(userSettings, projectSettings, projectSettingsPath) {
1197
+ if (projectSettingsPath && projectSettings.defaultInheritGlobalContext !== undefined)
1198
+ return projectSettings.defaultInheritGlobalContext;
1199
+ return userSettings.defaultInheritGlobalContext;
1200
+ }
1201
+ // The parsed field is a plain boolean, so only the frontmatter key tells an explicit `false` from an unset field.
1202
+ function applySubagentDefaultInheritGlobalContext(agents, defaultInheritGlobalContext) {
1203
+ if (!defaultInheritGlobalContext)
1204
+ return agents;
1205
+ return agents.map((agent) => {
1206
+ const frontmatterFields = agentFrontmatterFields.get(agent);
1207
+ if (agent.inheritGlobalContext || frontmatterFields?.has("inheritGlobalContext"))
1208
+ return agent;
1209
+ const next = { ...agent, inheritGlobalContext: true };
1210
+ if (frontmatterFields)
1211
+ agentFrontmatterFields.set(next, frontmatterFields);
1212
+ return next;
1213
+ });
1214
+ }
1215
+ function applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions, defaultInheritGlobalContext) {
1216
+ return applySubagentDefaultInheritGlobalContext(applySubagentDefaultSubagentOnlyExtensions(applySubagentDefaultExtensions(applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking), defaultExtensions), defaultSubagentOnlyExtensions), defaultInheritGlobalContext);
1194
1217
  }
1195
1218
  function applyToolsOverride(target, toolsOverride) {
1196
1219
  if (toolsOverride === "inherit") {
@@ -2550,7 +2573,8 @@ function configuredAgentsForScope(sources, scope, settingsScope = scope) {
2550
2573
  const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, sources.projectSettingsPath);
2551
2574
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, sources.projectSettingsPath);
2552
2575
  const defaultSubagentOnlyExtensions = resolveSubagentDefaultSubagentOnlyExtensions(userSettings, projectSettings, sources.projectSettingsPath);
2553
- const applyDefaults = (agents) => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions);
2576
+ const defaultInheritGlobalContext = resolveSubagentDefaultInheritGlobalContext(userSettings, projectSettings, sources.projectSettingsPath);
2577
+ const applyDefaults = (agents) => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions, defaultInheritGlobalContext);
2554
2578
  const builtin = applyBuiltinOverrides(applyDefaults(sources.builtinLoaded.agents), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2555
2579
  const user = applyCustomAgentOverrides(applyDefaults(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.agents)), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2556
2580
  const projectMap = new Map();
@@ -2706,12 +2730,13 @@ function discoverAgentsUncached(cwd, scope, preferredModelProvider, options = {}
2706
2730
  const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
2707
2731
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
2708
2732
  const defaultSubagentOnlyExtensions = resolveSubagentDefaultSubagentOnlyExtensions(userSettings, projectSettings, projectSettingsPath);
2733
+ const defaultInheritGlobalContext = resolveSubagentDefaultInheritGlobalContext(userSettings, projectSettings, projectSettingsPath);
2709
2734
  const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
2710
2735
  const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user", globalNpmRoot: options.globalNpmRoot });
2711
2736
  const isExcluded = agentExclusions(agentExclusionRoots(userSettingsPath, projectSettingsPath));
2712
2737
  const directories = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
2713
2738
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2714
- const applyDefaults = (agents) => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions);
2739
+ const applyDefaults = (agents) => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions, defaultInheritGlobalContext);
2715
2740
  const builtinAgents = applyBuiltinOverrides(applyDefaults(builtinLoaded.agents), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2716
2741
  const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? [], isExcluded);
2717
2742
  const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? [], isExcluded);
@@ -1,5 +1,5 @@
1
1
  import { type AgentConfig, type AgentScope, type AgentSource } from "../agents/agents.ts";
2
- import { type AvailableModelInfo, type ParentModel } from "../runs/shared/model-resolution.ts";
2
+ import { type AvailableModelInfo, type KnownProviders, type ParentModel } from "../runs/shared/model-resolution.ts";
3
3
  import { type ThinkingLevel } from "../shared/thinking-ceiling.ts";
4
4
  import { type ArtifactDirPreference, type ArtifactPaths, type IntercomBridgeConfig, type IntercomBridgeMode, type JsonSchemaObject, type OutputMode } from "../shared/types.ts";
5
5
  import { type ResolvedSubagentCapabilityCeiling, type SubagentCapabilityAudit } from "../runs/shared/capability-ceiling.ts";
@@ -36,6 +36,8 @@ export interface SubagentLaunchContractInput {
36
36
  fullId?: string;
37
37
  reasoning?: boolean;
38
38
  }>;
39
+ /** Every provider in Pi's full catalog (`ctx.modelRegistry.getAll()`), signed in or not, so a `provider/id` never resolves under another provider. */
40
+ knownProviders?: KnownProviders;
39
41
  preferredProvider?: string;
40
42
  skill?: string | string[] | boolean;
41
43
  output?: string | boolean;
@@ -225,6 +225,7 @@ export async function resolveSubagentLaunchContract(input) {
225
225
  : resolveEffectiveSubagentModel(input.model, agent.model, input.parentModel, availableModels, preferredProvider, {
226
226
  scope: modelScopes,
227
227
  source: modelOrigin === "explicit" ? "explicit" : "inherited",
228
+ knownProviders: input.knownProviders,
228
229
  });
229
230
  const effectiveThinkingConfig = input.thinking !== undefined ? input.thinking : agent.thinking;
230
231
  const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(discovered.maxThinking, input.thinkingCeiling, input.inheritedThinkingCeiling);
@@ -232,6 +233,7 @@ export async function resolveSubagentLaunchContract(input) {
232
233
  scope: modelScopes,
233
234
  primaryModelFromParent: modelOrigin === "inherited" || inheritsParentModel(input.model, agent.model, input.parentModel),
234
235
  origin: modelOrigin,
236
+ knownProviders: input.knownProviders,
235
237
  }).model, effectiveThinkingConfig, input.thinking !== undefined);
236
238
  if (!externalRunner) {
237
239
  try {
@@ -57,7 +57,7 @@ import registerSubagentNotify from "../runs/background/notify.js";
57
57
  import { createParentWake } from "../shared/parent-wake.js";
58
58
  import { handleSubagentSteeringNotice } from "./steering-notices.js";
59
59
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.js";
60
- import { disposeChildSessions } from "../runs/shared/child-session.js";
60
+ import { disposeChildSessionsForParent } from "../runs/shared/child-session.js";
61
61
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.js";
62
62
  import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.js";
63
63
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.js";
@@ -1196,13 +1196,15 @@ export default function registerSubagentExtension(pi) {
1196
1196
  supervisorChannel.activateTransport();
1197
1197
  });
1198
1198
  pi.on("session_shutdown", async (event) => {
1199
+ // Captured first: runtimeEntry.cleanup() below clears state.parentSessionFile.
1200
+ const parentSessionFile = state.parentSessionFile ?? undefined;
1199
1201
  sessionSwitchGuard.sessionShutdown(event);
1200
1202
  cancelCompactionResume();
1201
1203
  completionNotifier.sessionShutdown(event?.reason);
1202
1204
  parentWake.sessionShutdown(event?.reason);
1203
1205
  runtimeEntry.cleanup(event?.reason);
1204
1206
  try {
1205
- await disposeChildSessions();
1207
+ await disposeChildSessionsForParent(parentSessionFile);
1206
1208
  }
1207
1209
  catch (error) {
1208
1210
  console.error("Failed to dispose in-process child sessions:", error);
@@ -19,6 +19,7 @@ export declare const SubagentFlatParams: Type.TObject<{
19
19
  supersession: Type.TOptional<Type.TUnsafe<unknown>>;
20
20
  index: Type.TOptional<Type.TInteger>;
21
21
  childId: Type.TOptional<Type.TString>;
22
+ drain: Type.TOptional<Type.TBoolean>;
22
23
  toolCallId: Type.TOptional<Type.TString>;
23
24
  view: Type.TOptional<Type.TString>;
24
25
  lines: Type.TOptional<Type.TInteger>;
@@ -150,6 +151,7 @@ export declare const SubagentOptionParams: Type.TObject<{
150
151
  supersession: Type.TOptional<Type.TUnsafe<unknown>>;
151
152
  index: Type.TOptional<Type.TInteger>;
152
153
  childId: Type.TOptional<Type.TString>;
154
+ drain: Type.TOptional<Type.TBoolean>;
153
155
  toolCallId: Type.TOptional<Type.TString>;
154
156
  view: Type.TOptional<Type.TString>;
155
157
  lines: Type.TOptional<Type.TInteger>;
@@ -159,6 +159,7 @@ const SubagentParamProperties = {
159
159
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
160
160
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
161
161
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
162
+ drain: Type.Optional(Type.Boolean({ description: "stop: a live async workflow starts no new children; started ones finish." })),
162
163
  toolCallId: Type.Optional(Type.String({ description: "Command tool-call id." })),
163
164
  view: Type.Optional(Type.String({
164
165
  enum: ["fleet", "transcript"],
@@ -56,7 +56,16 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
56
56
  if (!available.some((tool) => tool.name === LOADER_NAME))
57
57
  return true;
58
58
  // SAFETY: The running Pi session manager exposes buildSessionContext, but its read-only extension type omits it.
59
- const messages = ctx.sessionManager.buildSessionContext().messages;
59
+ let messages = ctx.sessionManager.buildSessionContext().messages;
60
+ // A compaction checkpoint (the system message before the summary) folds the branch's earlier system messages into
61
+ // one declaration, which hides an extension unload before the compaction. Replay those messages instead, as Pi
62
+ // restores the session's tools from them.
63
+ if (messages[0]?.role === "system" && messages[1]?.role === "compactionSummary") {
64
+ const branch = ctx.sessionManager.getBranch();
65
+ const history = branch.slice(0, branch.findLastIndex((entry) => entry.type === "compaction"))
66
+ .flatMap((entry) => entry.type === "message" && entry.message.role === "system" ? [entry.message] : []);
67
+ messages = [...history, ...messages.slice(1)];
68
+ }
60
69
  // A compaction without a checkpoint leaves its summary first, with no system message before it: the
61
70
  // declarations from before it are lost, even when no tool selection was recorded after it.
62
71
  const lost = messages.find((message) => message.role === "system" || message.role === "compactionSummary")?.role === "compactionSummary";
@@ -9,7 +9,7 @@ export interface ToolDescriptionOptions {
9
9
  cwd?: string;
10
10
  agentDir?: string;
11
11
  warn?: (message: string) => void;
12
- /** Removes lines for disabled features from the default and full descriptions; custom descriptions are unchanged apart from the appended safety guidance. */
12
+ /** Removes lines for disabled features from the default and full descriptions, including the ones custom templates insert with placeholders. */
13
13
  disabledFeatures?: DisabledFeatureSurface;
14
14
  }
15
15
  export declare function buildSubagentToolPromptMetadata(config?: Pick<ExtensionConfig, "toolDescriptionMode">, disabledFeatures?: DisabledFeatureSurface): {
@@ -82,15 +82,15 @@ function customDescriptionPaths(options) {
82
82
  path.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),
83
83
  ];
84
84
  }
85
- function renderCustomTemplate(template, options) {
85
+ function renderCustomTemplate(template, on, options) {
86
86
  const cwd = options?.cwd ?? process.cwd();
87
87
  const agentDir = options?.agentDir ?? getAgentDir();
88
88
  const projectConfigDir = getProjectConfigDir(cwd);
89
89
  const variables = {
90
- fullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,
91
- full: () => FULL_SUBAGENT_TOOL_DESCRIPTION,
92
- compactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,
93
- compact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,
90
+ fullDescription: () => fullDescription(on),
91
+ full: () => fullDescription(on),
92
+ compactDescription: () => essentials(on),
93
+ compact: () => essentials(on),
94
94
  safetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,
95
95
  safety: () => SUBAGENT_SAFETY_GUIDANCE,
96
96
  agentDir: () => agentDir,
@@ -104,7 +104,7 @@ function renderCustomTemplate(template, options) {
104
104
  return raw;
105
105
  });
106
106
  }
107
- function loadCustomToolDescription(options) {
107
+ function loadCustomToolDescription(on, options) {
108
108
  for (const filePath of customDescriptionPaths(options)) {
109
109
  let stat;
110
110
  try {
@@ -130,7 +130,7 @@ function loadCustomToolDescription(options) {
130
130
  warn(options, `Ignoring empty custom tool description '${filePath}'.`);
131
131
  continue;
132
132
  }
133
- const rendered = renderCustomTemplate(template, options).trim();
133
+ const rendered = renderCustomTemplate(template, on, options).trim();
134
134
  if (!rendered) {
135
135
  warn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);
136
136
  continue;
@@ -166,7 +166,7 @@ function describeSubagentTool(config, options) {
166
166
  if (mode === "compact")
167
167
  return essentials(on);
168
168
  if (mode === "custom") {
169
- const custom = loadCustomToolDescription(options);
169
+ const custom = loadCustomToolDescription(on, options);
170
170
  if (custom)
171
171
  return withMandatorySafetyGuidance(custom);
172
172
  warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
@@ -5,7 +5,7 @@ import { type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
5
5
  import { type ChainStep } from "../../shared/settings.ts";
6
6
  import { type RunnerStep } from "../shared/parallel-utils.ts";
7
7
  import type { ContextMode } from "../shared/context-mode.ts";
8
- import { type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
8
+ import { type AvailableModelInfo, type KnownProviders, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
9
9
  import { type ModelScopeConfig } from "../shared/model-scope.ts";
10
10
  import { type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
11
11
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
@@ -32,6 +32,7 @@ interface AsyncExecutionContext {
32
32
  currentModelProvider?: string;
33
33
  currentModel?: ParentModel;
34
34
  scopedModelIds?: string[];
35
+ knownProviders?: KnownProviders;
35
36
  /** Optional model-scope enforcement resolved from subagent settings. */
36
37
  modelScope?: ModelScopeConfig;
37
38
  modelResponseAliases?: Record<string, string[]>;
@@ -956,7 +956,7 @@ export function buildAsyncRunnerSteps(id, params) {
956
956
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
957
957
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
958
958
  const primaryModelFromParent = modelOrigin === "inherited";
959
- const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
959
+ const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders });
960
960
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
961
961
  let claudeCodeOverride;
962
962
  if (claudeCodeAdapter) {
@@ -998,6 +998,7 @@ export function buildAsyncRunnerSteps(id, params) {
998
998
  scope: modelScopes,
999
999
  primaryModelFromParent,
1000
1000
  origin: modelOrigin,
1001
+ knownProviders: ctx.knownProviders,
1001
1002
  });
1002
1003
  requestedModel = modelEvidence.requestedModel;
1003
1004
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== undefined);
@@ -1754,7 +1755,7 @@ export function executeAsyncSingle(id, params) {
1754
1755
  try {
1755
1756
  primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
1756
1757
  ? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
1757
- : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
1758
+ : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders });
1758
1759
  }
1759
1760
  catch (error) {
1760
1761
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
@@ -1821,6 +1822,7 @@ export function executeAsyncSingle(id, params) {
1821
1822
  scope: modelScopes,
1822
1823
  primaryModelFromParent: modelOrigin === "inherited",
1823
1824
  origin: modelOrigin,
1825
+ knownProviders: ctx.knownProviders,
1824
1826
  });
1825
1827
  requestedModel = modelEvidence.requestedModel;
1826
1828
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, params.thinkingOverride !== undefined);
@@ -674,14 +674,15 @@ export function inspectSubagentStatus(params, deps = {}) {
674
674
  lines.push(` Runner: external-cli (${runner.command}${runner.args.length ? ` ${runner.args.join(" ")}` : ""})`);
675
675
  lines.push(` Adapter: ${runner.adapter.id} v${runner.adapter.version} (${runner.adapter.executionMode})`);
676
676
  if (runner.safety) {
677
+ const safetyLabel = " Safety (adapter profile, not measured):";
677
678
  if ("approvalPolicy" in runner.safety)
678
- lines.push(` Safety: ${"access" in runner.safety ? `access=${runner.safety.access}, ` : ""}sandbox=${runner.safety.sandbox}, approval=${runner.safety.approvalPolicy}, ephemeral=${runner.safety.ephemeral}`);
679
+ lines.push(`${safetyLabel} ${"access" in runner.safety ? `access=${runner.safety.access}, ` : ""}sandbox=${runner.safety.sandbox}, approval=${runner.safety.approvalPolicy}, ephemeral=${runner.safety.ephemeral}`);
679
680
  else if ("mode" in runner.safety)
680
- lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, mode=${runner.safety.mode}, sandbox=${runner.safety.sandbox}, workspaceTrust=${runner.safety.workspaceTrust}, sessionReuse=${runner.safety.sessionReuse}`);
681
+ lines.push(`${safetyLabel} access=${runner.safety.access}, auth=${runner.safety.authentication}, mode=${runner.safety.mode}, sandbox=${runner.safety.sandbox}, workspaceTrust=${runner.safety.workspaceTrust}, sessionReuse=${runner.safety.sessionReuse}`);
681
682
  else if ("authentication" in runner.safety)
682
- lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, settingsTrust=${runner.safety.userSettingsTrust}, persistence=${runner.safety.sessionPersistence}`);
683
+ lines.push(`${safetyLabel} access=${runner.safety.access}, auth=${runner.safety.authentication}, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, settingsTrust=${runner.safety.userSettingsTrust}, persistence=${runner.safety.sessionPersistence}`);
683
684
  else
684
- lines.push(` Safety: access=read-only, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, persistence=${runner.safety.sessionPersistence}`);
685
+ lines.push(`${safetyLabel} access=read-only, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, persistence=${runner.safety.sessionPersistence}`);
685
686
  }
686
687
  lines.push(` Capabilities: stop=${runner.capabilities.stop}, steer=false, resume=false, structuredOutput=false, toolEvents=false, supervisor=unsupported, forkContext=false, extensionBindings=false`);
687
688
  lines.push(` Unsupported steer: ${runner.unsupportedReasons.steer}`);
@@ -33,6 +33,7 @@ const CHORD_PEER_ALIASES = [
33
33
  { specifier: "@earendil-works/chord", pkg: "@earendil-works/chord", subpath: "." },
34
34
  { specifier: "@earendil-works/chord/context", pkg: "@earendil-works/chord", subpath: "./context" },
35
35
  ];
36
+ const SCHEMA_PACKAGE = "@earendil-works/pi-schema";
36
37
  function readManifest(packageDir) {
37
38
  try {
38
39
  return JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf-8"));
@@ -155,5 +156,19 @@ export function resolveHostPeerAliases(piPackageRoot) {
155
156
  else if (pkg !== CHORD_PACKAGE || chordRequired)
156
157
  missing.push(specifier);
157
158
  }
159
+ // Pi 1.5+ pi-ai imports pi-schema; without it a child dies after its launch was accepted. pi-ai's
160
+ // own import already reaches the right copy, so this is only a presence check, never an alias:
161
+ // an alias would also redirect extensions that ship their own copy.
162
+ const piAiDir = findPeerPackageDir(piPackageRoot, "@earendil-works/pi-ai", hostManifest?.name);
163
+ const piAiManifest = piAiDir ? readManifest(piAiDir) : undefined;
164
+ if (piAiDir && piAiManifest && declaresDependency(piAiManifest, SCHEMA_PACKAGE)) {
165
+ // Resolve from pi-ai's real path, as Node does, so nested, hoisted and pnpm-sibling copies count.
166
+ const schemaDir = findPeerPackageDir(fs.realpathSync(piAiDir), SCHEMA_PACKAGE, undefined);
167
+ for (const subpath of [".", "./formats"]) {
168
+ const target = schemaDir ? resolvePackageSubpath(schemaDir, subpath) : undefined;
169
+ if (!target || !fs.existsSync(target))
170
+ missing.push(subpath === "." ? SCHEMA_PACKAGE : `${SCHEMA_PACKAGE}/formats`);
171
+ }
172
+ }
158
173
  return { aliases, missing };
159
174
  }
@@ -1290,9 +1290,9 @@ async function runSingleStep(step, ctx) {
1290
1290
  ctx.orcaProgressTab?.section({ agent: step.agent, index: ctx.flatIndex, count: ctx.flatStepCount });
1291
1291
  return runSingleStepInner(step, ctx);
1292
1292
  }
1293
- function externalRunnerStatus(runner) {
1293
+ function externalRunnerStatus(runner, machine) {
1294
1294
  if (runner?.type === "external-cli") {
1295
- return resolveExternalCliRunnerStatus(runner);
1295
+ return resolveExternalCliRunnerStatus(machine?.provider === "herdr" ? { ...runner, machine } : runner);
1296
1296
  }
1297
1297
  if (runner?.type === "external-job") {
1298
1298
  return {
@@ -1570,7 +1570,7 @@ export async function runSubagent(config, childSessions) {
1570
1570
  agent: task.agent,
1571
1571
  ...(task.lane ? { lane: task.lane } : config.lane ? { lane: config.lane } : {}),
1572
1572
  ...(taskSessionName ? { sessionName: taskSessionName } : {}),
1573
- ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
1573
+ ...(externalRunnerStatus(task.runner, task.machine) ? { runner: externalRunnerStatus(task.runner, task.machine) } : {}),
1574
1574
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
1575
1575
  ...(task.context ? { context: task.context } : {}),
1576
1576
  phase: task.phase,
@@ -1601,7 +1601,7 @@ export async function runSubagent(config, childSessions) {
1601
1601
  parallelGroups.push({ start: flatStepCount, count: 1, stepIndex });
1602
1602
  initialStatusSteps.push(omitUndefinedProperties({
1603
1603
  agent: `expand:${step.parallel.agent}`,
1604
- ...(externalRunnerStatus(step.parallel.runner) ? { runner: externalRunnerStatus(step.parallel.runner) } : {}),
1604
+ ...(externalRunnerStatus(step.parallel.runner, step.parallel.machine) ? { runner: externalRunnerStatus(step.parallel.runner, step.parallel.machine) } : {}),
1605
1605
  ...(step.parallel.context ? { context: step.parallel.context } : {}),
1606
1606
  phase: step.phase ?? step.parallel.phase,
1607
1607
  label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
@@ -1626,7 +1626,7 @@ export async function runSubagent(config, childSessions) {
1626
1626
  agent: step.agent,
1627
1627
  ...(step.lane ? { lane: step.lane } : config.lane ? { lane: config.lane } : {}),
1628
1628
  ...(stepSessionName ? { sessionName: stepSessionName } : {}),
1629
- ...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),
1629
+ ...(externalRunnerStatus(step.runner, step.machine) ? { runner: externalRunnerStatus(step.runner, step.machine) } : {}),
1630
1630
  ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),
1631
1631
  ...(step.context ? { context: step.context } : {}),
1632
1632
  phase: step.phase,
@@ -3460,7 +3460,7 @@ export async function runSubagent(config, childSessions) {
3460
3460
  return omitUndefinedProperties({
3461
3461
  agent: task.agent,
3462
3462
  ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3463
- ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
3463
+ ...(externalRunnerStatus(task.runner, task.machine) ? { runner: externalRunnerStatus(task.runner, task.machine) } : {}),
3464
3464
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3465
3465
  ...(task.context ? { context: task.context } : {}),
3466
3466
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -1,12 +1,16 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { listAsyncRuns } from "./async-status.js";
5
5
  import { formatResumeFirstFailedRunDetail } from "./resume-guidance.js";
6
6
  import { readCompletionReplay } from "./completion-replay.js";
7
7
  import { writeAtomicJson } from "../../shared/atomic-json.js";
8
8
  import { COMPLETION_ACTION, STATUS_ACTION } from "../../shared/parent-wake.js";
9
9
  import { DIRS, INTERCOM_DETACH_REQUEST_EVENT, SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_RESULT_INTERCOM_EVENT, } from "../../shared/types.js";
10
+ import { currentBootId, currentRecordedPid } from "./boot-id.js";
11
+ import { currentPidNamespaceScope } from "./pid-namespace.js";
12
+ import { checkRecordedPidLiveness, isRecordedPid } from "./stale-run-reconciler.js";
13
+ import { createClaimFile } from "../../workflows/workflow-resume-claim.js";
10
14
  const SUBSCRIPTION_VERSION = 1;
11
15
  // Outcomes that report no saved results, so the notice points the parent at the run status instead.
12
16
  const STATUS_OUTCOMES = new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
@@ -36,6 +40,8 @@ function parseRecord(value) {
36
40
  || typeof record.token !== "string"
37
41
  || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.token)
38
42
  || typeof record.sessionId !== "string"
43
+ || (record.completionOwnerId !== undefined && typeof record.completionOwnerId !== "string")
44
+ || (record.completionOwnerProcess !== undefined && !isRecordedPid(record.completionOwnerProcess))
39
45
  || (record.targetKind !== "async" && record.targetKind !== "foreground")
40
46
  || typeof record.runId !== "string"
41
47
  || typeof record.requestedId !== "string"
@@ -50,6 +56,40 @@ function needsAttention(run) {
50
56
  function subscriptionFile(dir, token) {
51
57
  return path.join(dir, `${token}.json`);
52
58
  }
59
+ /**
60
+ * Takeover claims are `<token>.claim-<owner hash>.<generation>`, not `.json`, so record scans skip them.
61
+ * Each generation is created exclusively, so one process takes over from a dead owner per generation;
62
+ * a dead claimant's generation is superseded by the next one.
63
+ */
64
+ function claimPrefix(token, replacedOwnerId) {
65
+ return `${token}.claim-${createHash("sha256").update(replacedOwnerId).digest("hex").slice(0, 16)}.`;
66
+ }
67
+ function latestClaimGeneration(files, prefix) {
68
+ let latest = 0;
69
+ for (const file of files) {
70
+ const generation = file.startsWith(prefix) ? file.slice(prefix.length) : "";
71
+ // Exact digits only: leftover `<claim>.<pid>.<uuid>.tmp` files from a crashed create are not generations.
72
+ if (/^[1-9][0-9]*$/.test(generation))
73
+ latest = Math.max(latest, Number(generation));
74
+ }
75
+ return latest;
76
+ }
77
+ /**
78
+ * Call only after the record file is gone, so a late claimer that wins a freed claim finds no record to bring back.
79
+ * Never throws: a leftover claim cannot bring a removed record back.
80
+ */
81
+ function removeClaimFiles(dir, token) {
82
+ try {
83
+ for (const file of fs.readdirSync(dir)) {
84
+ if (file.startsWith(`${token}.claim-`))
85
+ fs.rmSync(path.join(dir, file), { force: true });
86
+ }
87
+ }
88
+ catch (error) {
89
+ if (!isNotFound(error))
90
+ console.error(`Failed to remove claims of wait subscription '${token}':`, error);
91
+ }
92
+ }
53
93
  export function formatWaitSubscriptions(state, now = Date.now()) {
54
94
  const subscriptions = [...(state.waitSubscriptions?.values() ?? [])].sort((left, right) => left.createdAt - right.createdAt);
55
95
  if (subscriptions.length === 0)
@@ -71,6 +111,64 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
71
111
  let disposed = false;
72
112
  let interval;
73
113
  let lastForeignSweepAt = 0;
114
+ const readRecordFile = (filePath) => {
115
+ try {
116
+ return parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
117
+ }
118
+ catch (error) {
119
+ if (isNotFound(error))
120
+ return undefined;
121
+ throw error;
122
+ }
123
+ };
124
+ const isDead = (recorded) => recorded !== undefined && checkRecordedPidLiveness(recorded, {
125
+ observedScope: currentPidNamespaceScope(),
126
+ observedBootId: currentBootId(),
127
+ kill: options.kill,
128
+ }) === "dead";
129
+ const latestClaimantHolds = (claimPath) => {
130
+ let body;
131
+ try {
132
+ body = JSON.parse(fs.readFileSync(claimPath, "utf-8"));
133
+ }
134
+ catch (error) {
135
+ // Claims are created whole, so a body that does not parse is damage; a claim that cannot be read counts as held.
136
+ return !(error instanceof SyntaxError);
137
+ }
138
+ const claimant = body?.process;
139
+ return isRecordedPid(claimant) && !isDead(claimant);
140
+ };
141
+ // Two Pi processes can share one session. The arming process owns the wake while it lives;
142
+ // after it dies, the next process to open the session claims the record and becomes its owner.
143
+ const claimRecord = (filePath, record) => {
144
+ if (!record.completionOwnerId || record.completionOwnerId === state.completionOwnerId)
145
+ return record;
146
+ if (!isDead(record.completionOwnerProcess))
147
+ return undefined;
148
+ if (!state.completionOwnerId)
149
+ return record;
150
+ const prefix = claimPrefix(record.token, record.completionOwnerId);
151
+ const latest = latestClaimGeneration(fs.readdirSync(subscriptionsDir), prefix);
152
+ if (latest > 0 && latestClaimantHolds(path.join(subscriptionsDir, `${prefix}${latest}`)))
153
+ return undefined;
154
+ const claimPath = path.join(subscriptionsDir, `${prefix}${latest + 1}`);
155
+ if (!createClaimFile(claimPath, { ownerId: state.completionOwnerId, process: currentRecordedPid() }))
156
+ return undefined;
157
+ try {
158
+ // The record may have been settled (and its claims removed) after this process first read it.
159
+ if (readRecordFile(filePath)?.completionOwnerId !== record.completionOwnerId) {
160
+ fs.rmSync(claimPath, { force: true });
161
+ return undefined;
162
+ }
163
+ const claimed = { ...record, completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() };
164
+ writeAtomicJson(filePath, claimed);
165
+ return claimed;
166
+ }
167
+ catch (error) {
168
+ fs.rmSync(claimPath, { force: true });
169
+ throw error;
170
+ }
171
+ };
74
172
  /**
75
173
  * Remove expired records armed by another session.
76
174
  *
@@ -109,7 +207,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
109
207
  const filePath = path.join(subscriptionsDir, file);
110
208
  let record;
111
209
  try {
112
- record = parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
210
+ record = readRecordFile(filePath);
113
211
  }
114
212
  catch (error) {
115
213
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error);
@@ -130,27 +228,36 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
130
228
  // Losing this race is harmless: another session may have swept the
131
229
  // same expired record. Anything else is reported and retried on the
132
230
  // next sweep rather than interrupting the caller.
133
- if (!isNotFound(error))
231
+ if (!isNotFound(error)) {
134
232
  console.error(`Failed to remove expired wait subscription '${filePath}':`, error);
233
+ continue;
234
+ }
135
235
  }
236
+ removeClaimFiles(subscriptionsDir, record.token);
136
237
  }
137
238
  };
138
239
  const remove = (record) => {
240
+ let removed = true;
139
241
  try {
140
242
  fs.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
141
243
  }
142
244
  catch (error) {
143
245
  if (!isNotFound(error))
144
246
  throw error;
247
+ removed = false;
145
248
  }
146
249
  subscriptions.delete(record.token);
147
250
  unresolvedRestoredForegroundTokens.delete(record.token);
251
+ removeClaimFiles(subscriptionsDir, record.token);
252
+ return removed;
148
253
  };
149
254
  const settle = (record, outcome, detail, completion) => {
150
255
  if (disposed || state.currentSessionId !== record.sessionId)
151
256
  return;
152
257
  try {
153
- remove(record);
258
+ // Only the process that removes the record may deliver its wake.
259
+ if (!remove(record))
260
+ return;
154
261
  }
155
262
  catch (error) {
156
263
  console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error);
@@ -274,6 +381,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
274
381
  version: SUBSCRIPTION_VERSION,
275
382
  token: randomUUID(),
276
383
  sessionId,
384
+ ...(state.completionOwnerId ? { completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() } : {}),
277
385
  targetKind: input.targetKind,
278
386
  runId: input.runId,
279
387
  requestedId: input.requestedId,
@@ -303,19 +411,23 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
303
411
  throw error;
304
412
  }
305
413
  for (const file of files) {
414
+ const filePath = path.join(subscriptionsDir, file);
415
+ let record;
306
416
  try {
307
- const record = parseRecord(JSON.parse(fs.readFileSync(path.join(subscriptionsDir, file), "utf-8")));
308
- if (!record || file !== `${record.token}.json`)
417
+ const found = readRecordFile(filePath);
418
+ if (!found || file !== `${found.token}.json` || found.sessionId !== state.currentSessionId)
309
419
  continue;
310
- if (record.sessionId === state.currentSessionId) {
311
- subscriptions.set(record.token, record);
312
- if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
313
- unresolvedRestoredForegroundTokens.add(record.token);
314
- }
420
+ record = claimRecord(filePath, found);
315
421
  }
316
422
  catch (error) {
317
- console.error(`Ignoring invalid wait subscription '${path.join(subscriptionsDir, file)}':`, error);
423
+ console.error(`Failed to restore wait subscription '${filePath}':`, error);
424
+ continue;
318
425
  }
426
+ if (!record)
427
+ continue;
428
+ subscriptions.set(record.token, record);
429
+ if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
430
+ unresolvedRestoredForegroundTokens.add(record.token);
319
431
  }
320
432
  reconcile();
321
433
  },