pi-subagents 0.86.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 (86) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-7QA7ZA46.js → chunk-2D2DQGC2.js} +9 -9
  5. package/bundle/{chunk-UR7OW5S7.js → chunk-2NY5PCKQ.js} +11 -5
  6. package/bundle/{chunk-PYOAIN3V.js → chunk-3CVOAS77.js} +2 -2
  7. package/bundle/{chunk-YK3QYNLE.js → chunk-6O7YH2QV.js} +1 -1
  8. package/bundle/{chunk-ZJJCPV3L.js → chunk-AIL46SZU.js} +8 -6
  9. package/bundle/{chunk-S2Q75LP3.js → chunk-BFF6YDK6.js} +1 -1
  10. package/bundle/{chunk-QGO6HXHG.js → chunk-C3KWLXDH.js} +79 -63
  11. package/bundle/{chunk-NAFLUJ26.js → chunk-C5QWQSSM.js} +1 -1
  12. package/bundle/{chunk-O3YH7XIY.js → chunk-DGTZKYIE.js} +25 -24
  13. package/bundle/{chunk-77ASNIEM.js → chunk-ESWW6XSX.js} +1 -1
  14. package/bundle/{chunk-BWC2LVII.js → chunk-EYGBK6CE.js} +166 -60
  15. package/bundle/{chunk-3RKFH2UZ.js → chunk-HDICKROY.js} +5 -5
  16. package/bundle/{chunk-QM3JGE4W.js → chunk-JLDQ6YUR.js} +12 -12
  17. package/bundle/{chunk-A637IMAO.js → chunk-LFKMM3UH.js} +2 -2
  18. package/bundle/{chunk-WN2E5XHN.js → chunk-LZKVUWIY.js} +4 -4
  19. package/bundle/{chunk-6VD7BGIC.js → chunk-M2VBGET6.js} +2 -2
  20. package/bundle/{chunk-7ZUFN6ME.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-7ADDXUGF.js → chunk-OTLDAYEQ.js} +5 -5
  22. package/bundle/{chunk-2IYBCYFU.js → chunk-OZCPYJEY.js} +75 -33
  23. package/bundle/{chunk-GJGTMLPE.js → chunk-PGU4TZV3.js} +79 -32
  24. package/bundle/{chunk-374MZFF4.js → chunk-SIAQXPJ4.js} +6 -8
  25. package/bundle/{chunk-LGINOOY5.js → chunk-USRX7QXD.js} +2 -2
  26. package/bundle/{chunk-5H4BICQZ.js → chunk-VFUFOZBU.js} +1 -1
  27. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  28. package/bundle/{chunk-ZPY5QZCS.js → chunk-W52LJANO.js} +1 -1
  29. package/bundle/{chunk-GRJHIXYF.js → chunk-XSDYTXHF.js} +18 -11
  30. package/bundle/{chunk-BGXEAYUM.js → chunk-XV7RTWTS.js} +3 -3
  31. package/bundle/{chunk-BU6PFPVX.js → chunk-YEXKJJVS.js} +12 -7
  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 +3 -3
  39. package/docs/configuration.md +12 -4
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/tool-reference.md +1 -0
  43. package/package.json +1 -1
  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/runs/background/async-execution.d.ts +2 -1
  56. package/src/runs/background/async-execution.js +4 -2
  57. package/src/runs/background/runner-aliases.js +15 -0
  58. package/src/runs/background/wait-subscriptions.js +124 -12
  59. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  60. package/src/runs/foreground/async-stop-action.js +9 -1
  61. package/src/runs/foreground/execution.js +1 -0
  62. package/src/runs/foreground/subagent-executor.d.ts +1 -0
  63. package/src/runs/foreground/subagent-executor.js +51 -8
  64. package/src/runs/shared/child-session.d.ts +5 -4
  65. package/src/runs/shared/child-session.js +43 -33
  66. package/src/runs/shared/herdr-placed-run.js +3 -2
  67. package/src/runs/shared/mcp-config-sources.d.ts +2 -1
  68. package/src/runs/shared/mcp-config-sources.js +1 -1
  69. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -1
  70. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -6
  71. package/src/runs/shared/model-resolution.d.ts +19 -4
  72. package/src/runs/shared/model-resolution.js +50 -51
  73. package/src/shared/artifacts.js +25 -13
  74. package/src/shared/pruned-fork.js +2 -2
  75. package/src/shared/types.d.ts +14 -0
  76. package/src/watchdog/model-selection.js +2 -2
  77. package/src/watchdog/review.js +2 -2
  78. package/src/workflows/scripted-workflow.d.ts +2 -0
  79. package/src/workflows/scripted-workflow.js +103 -39
  80. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  81. package/src/workflows/structured-workflow-scripts.js +32 -11
  82. package/src/workflows/workflow-resources.js +4 -4
  83. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  84. package/src/workflows/workflow-resume-claim.js +1 -1
  85. package/src/workflows/workflow-resume.d.ts +1 -1
  86. package/src/workflows/workflow-resume.js +3 -1
@@ -11,10 +11,10 @@ import {
11
11
  startWatchdogDiffBaselineCapture,
12
12
  writeUserWatchdogEnabled,
13
13
  writeWatchdogModelSettings
14
- } from "./chunk-ZJJCPV3L.js";
14
+ } from "./chunk-AIL46SZU.js";
15
15
  import {
16
16
  resolveGitRepositoryIdentity
17
- } from "./chunk-UR7OW5S7.js";
17
+ } from "./chunk-2NY5PCKQ.js";
18
18
  import {
19
19
  listAsyncRuns,
20
20
  parallelHandoffPath,
@@ -22,14 +22,14 @@ import {
22
22
  readAsyncRecoveryDescriptor,
23
23
  readWorkflowLaunchRecord,
24
24
  resolveRetainedWorktreeCwd
25
- } from "./chunk-BGXEAYUM.js";
25
+ } from "./chunk-XV7RTWTS.js";
26
26
  import {
27
27
  ownsRun
28
28
  } from "./chunk-HXRB42AF.js";
29
29
  import {
30
30
  deepFreezeWorkflowArgs,
31
31
  normalizeWorkflowArgs
32
- } from "./chunk-NF7IEKBH.js";
32
+ } from "./chunk-W2BZS6UC.js";
33
33
  import {
34
34
  HOST_STEP_MAX_COUNT,
35
35
  REQUIRE_LAUNCHER_SHAPE_ERROR,
@@ -54,21 +54,21 @@ import {
54
54
  resolveMissionStoreLocation,
55
55
  validateMissionId,
56
56
  workflowRunParamsFingerprint
57
- } from "./chunk-GJGTMLPE.js";
57
+ } from "./chunk-PGU4TZV3.js";
58
58
  import {
59
59
  requestAsyncCommand,
60
60
  watchAsyncControlInbox
61
- } from "./chunk-5H4BICQZ.js";
61
+ } from "./chunk-VFUFOZBU.js";
62
62
  import {
63
63
  supervisorChannelDir
64
- } from "./chunk-374MZFF4.js";
64
+ } from "./chunk-SIAQXPJ4.js";
65
65
  import {
66
66
  createHerdrClient,
67
67
  detectHerdr
68
- } from "./chunk-PYOAIN3V.js";
68
+ } from "./chunk-3CVOAS77.js";
69
69
  import {
70
70
  getProjectSubagentsDir
71
- } from "./chunk-GRJHIXYF.js";
71
+ } from "./chunk-XSDYTXHF.js";
72
72
  import {
73
73
  ExternalJobProviderError,
74
74
  getExternalJobProvider,
@@ -78,7 +78,7 @@ import {
78
78
  } from "./chunk-YYREO77V.js";
79
79
  import {
80
80
  mergeRuntimeAgents
81
- } from "./chunk-NAFLUJ26.js";
81
+ } from "./chunk-C5QWQSSM.js";
82
82
  import {
83
83
  CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL,
84
84
  EXTERNAL_CLI_ADAPTER_SAFETY,
@@ -106,6 +106,7 @@ import {
106
106
  getSupportedThinkingLevels,
107
107
  isCodeOwnedExternalCliAdapterId,
108
108
  isUnavailableSubagentModel,
109
+ knownModelProviders,
109
110
  mergeAgentsForScope,
110
111
  mergeBuiltinAgentOverride,
111
112
  normalizeModelSegment,
@@ -136,7 +137,7 @@ import {
136
137
  withFileLease,
137
138
  writeAtomicJson,
138
139
  writePrivateAtomicJson
139
- } from "./chunk-QGO6HXHG.js";
140
+ } from "./chunk-C3KWLXDH.js";
140
141
  import {
141
142
  DIRS,
142
143
  INTERCOM_DETACH_REQUEST_EVENT,
@@ -3108,6 +3109,7 @@ function editableAgentConfig(agent) {
3108
3109
  const next = { ...config };
3109
3110
  if (!hasDeclaredField("model")) delete next.model;
3110
3111
  if (!hasDeclaredField("thinking")) delete next.thinking;
3112
+ if (!hasDeclaredField("inheritGlobalContext")) next.inheritGlobalContext = false;
3111
3113
  return next;
3112
3114
  };
3113
3115
  const {
@@ -3156,7 +3158,7 @@ function editableAgentConfig(agent) {
3156
3158
  ...base.thinking !== void 0 && hasDeclaredField("thinking") ? { thinking: base.thinking } : {},
3157
3159
  systemPromptMode: base.systemPromptMode,
3158
3160
  inheritProjectContext: base.inheritProjectContext,
3159
- inheritGlobalContext: base.inheritGlobalContext,
3161
+ inheritGlobalContext: hasDeclaredField("inheritGlobalContext") && base.inheritGlobalContext,
3160
3162
  inheritSkills: base.inheritSkills,
3161
3163
  ...base.defaultContext !== void 0 ? { defaultContext: base.defaultContext } : {},
3162
3164
  ...base.acceptanceRole !== void 0 ? { acceptanceRole: base.acceptanceRole } : {},
@@ -3779,7 +3781,8 @@ function handleList(params, ctx) {
3779
3781
  const capabilityMode = params.capabilities === true;
3780
3782
  const externalCliAvailability = capabilityMode ? externalCliAvailabilityForAgents([...agents, ...restrictedAgents]) : void 0;
3781
3783
  const availableModels = capabilityMode ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
3782
- const unavailableModels = new Set([...agents, ...restrictedAgents].filter((agent) => (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? ctx.model?.provider)));
3784
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
3785
+ const unavailableModels = new Set([...agents, ...restrictedAgents].filter((agent) => (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? ctx.model?.provider, knownProviders)));
3783
3786
  const formatLine = capabilityMode ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability, unavailableModels) : formatAgentListLine;
3784
3787
  const lines = [
3785
3788
  capabilityMode ? "Executable agents (capabilities):" : "Executable agents:",
@@ -3822,6 +3825,7 @@ function handleModels(params, ctx) {
3822
3825
  const discovered = discoverCatalog(ctx, ctx.cwd, ctx.model?.provider);
3823
3826
  const effectiveAgents = effectiveAgentsForScope(scope, discovered, ctx.runtimeAgentOwner, ctx.model?.provider).sort((a, b) => a.name.localeCompare(b.name));
3824
3827
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
3828
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
3825
3829
  const currentModel = ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : void 0;
3826
3830
  const preferredProvider = ctx.model?.provider;
3827
3831
  const capabilityCeiling = resolveCurrentSubagentCapabilityCeiling(ctx.piSessionId);
@@ -3850,8 +3854,8 @@ function handleModels(params, ctx) {
3850
3854
  ];
3851
3855
  const modelEntries = selectedAgents.flatMap((agent) => requestedAgent ? [{ agent, name: requestedAgent }] : [{ agent, name: agent.name }, ...(agent.aliases ?? []).map((name) => ({ agent, name }))]);
3852
3856
  for (const { agent, name } of modelEntries) {
3853
- const resolvedModel = resolveSubagentModelOverride(agent.model, currentModel, availableModels, agent.modelProvider ?? preferredProvider);
3854
- const shownModel = resolvedModel === void 0 ? "(unresolved)" : (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? preferredProvider) ? `${resolvedModel} ${UNAVAILABLE_MODEL_MARKER}` : resolvedModel;
3857
+ const resolvedModel = resolveSubagentModelOverride(agent.model, currentModel, availableModels, agent.modelProvider ?? preferredProvider, { knownProviders });
3858
+ const shownModel = resolvedModel === void 0 ? "(unresolved)" : (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? preferredProvider, knownProviders) ? `${resolvedModel} ${UNAVAILABLE_MODEL_MARKER}` : resolvedModel;
3855
3859
  const effectiveThinking = resolveEffectiveThinking(resolvedModel, agent.thinking) ?? (agent.thinking === false ? "off" : void 0);
3856
3860
  const source = `${formatModelSource(agent, currentModel)}${agent.disabled ? "; disabled" : ""}${isAgentAllowedByCapabilityCeiling(agent.name, capabilityCeiling) ? "" : "; restricted"}`;
3857
3861
  if (requestedAgent) {
@@ -3966,7 +3970,7 @@ function handleCreate(params, ctx) {
3966
3970
  if (mw) warnings.push(mw);
3967
3971
  const sw = skillsWarning(ctx.cwd, agent);
3968
3972
  if (sw) warnings.push(sw);
3969
- fs7.writeFileSync(targetPath, serializeAgent(agent), "utf-8");
3973
+ fs7.writeFileSync(targetPath, serializeAgent(agent, { explicitInheritGlobalContext: hasKey(cfg, "inheritGlobalContext") }), "utf-8");
3970
3974
  ctx.onAgentsChanged?.();
3971
3975
  return result4([`Created agent '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
3972
3976
  }
@@ -4356,7 +4360,7 @@ function resolveWatchdogModelInput(ctx, rawModel) {
4356
4360
  if (!trimmed) throw new Error("Watchdog model must be a non-empty provider/model value.");
4357
4361
  const availableModels = modelRegistryEntries(ctx);
4358
4362
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : void 0;
4359
- const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider) ?? trimmed;
4363
+ const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry)) ?? trimmed;
4360
4364
  const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(resolved);
4361
4365
  const named = splitProviderModel(baseModel);
4362
4366
  if (!named) throw new Error(`Watchdog model '${rawModel}' did not resolve to provider/model. Use a provider-qualified model such as openai-codex/gpt-5.5:high or anthropic/claude-opus-4-8:high.`);
@@ -6569,7 +6573,7 @@ function registerPiWebSessionLiveness(registration) {
6569
6573
  // src/runs/background/wait-subscriptions.ts
6570
6574
  import * as fs10 from "node:fs";
6571
6575
  import * as path9 from "node:path";
6572
- import { randomUUID as randomUUID4 } from "node:crypto";
6576
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
6573
6577
  var SUBSCRIPTION_VERSION = 1;
6574
6578
  var STATUS_OUTCOMES = /* @__PURE__ */ new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
6575
6579
  var RECONCILE_INTERVAL_MS = 1e3;
@@ -6581,7 +6585,7 @@ function isNotFound(error2) {
6581
6585
  function parseRecord(value) {
6582
6586
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
6583
6587
  const record = value;
6584
- if (record.version !== SUBSCRIPTION_VERSION || typeof record.token !== "string" || !/^[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) || typeof record.sessionId !== "string" || record.targetKind !== "async" && record.targetKind !== "foreground" || typeof record.runId !== "string" || typeof record.requestedId !== "string" || typeof record.createdAt !== "number" || typeof record.expiresAt !== "number") return void 0;
6588
+ if (record.version !== SUBSCRIPTION_VERSION || typeof record.token !== "string" || !/^[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) || typeof record.sessionId !== "string" || record.completionOwnerId !== void 0 && typeof record.completionOwnerId !== "string" || record.completionOwnerProcess !== void 0 && !isRecordedPid(record.completionOwnerProcess) || record.targetKind !== "async" && record.targetKind !== "foreground" || typeof record.runId !== "string" || typeof record.requestedId !== "string" || typeof record.createdAt !== "number" || typeof record.expiresAt !== "number") return void 0;
6585
6589
  return record;
6586
6590
  }
6587
6591
  function needsAttention(run) {
@@ -6590,6 +6594,26 @@ function needsAttention(run) {
6590
6594
  function subscriptionFile(dir, token) {
6591
6595
  return path9.join(dir, `${token}.json`);
6592
6596
  }
6597
+ function claimPrefix(token, replacedOwnerId) {
6598
+ return `${token}.claim-${createHash3("sha256").update(replacedOwnerId).digest("hex").slice(0, 16)}.`;
6599
+ }
6600
+ function latestClaimGeneration(files, prefix) {
6601
+ let latest = 0;
6602
+ for (const file of files) {
6603
+ const generation = file.startsWith(prefix) ? file.slice(prefix.length) : "";
6604
+ if (/^[1-9][0-9]*$/.test(generation)) latest = Math.max(latest, Number(generation));
6605
+ }
6606
+ return latest;
6607
+ }
6608
+ function removeClaimFiles(dir, token) {
6609
+ try {
6610
+ for (const file of fs10.readdirSync(dir)) {
6611
+ if (file.startsWith(`${token}.claim-`)) fs10.rmSync(path9.join(dir, file), { force: true });
6612
+ }
6613
+ } catch (error2) {
6614
+ if (!isNotFound(error2)) console.error(`Failed to remove claims of wait subscription '${token}':`, error2);
6615
+ }
6616
+ }
6593
6617
  function formatWaitSubscriptions(state, now = Date.now()) {
6594
6618
  const subscriptions = [...state.waitSubscriptions?.values() ?? []].sort((left, right) => left.createdAt - right.createdAt);
6595
6619
  if (subscriptions.length === 0) return void 0;
@@ -6610,6 +6634,51 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6610
6634
  let disposed = false;
6611
6635
  let interval;
6612
6636
  let lastForeignSweepAt = 0;
6637
+ const readRecordFile = (filePath) => {
6638
+ try {
6639
+ return parseRecord(JSON.parse(fs10.readFileSync(filePath, "utf-8")));
6640
+ } catch (error2) {
6641
+ if (isNotFound(error2)) return void 0;
6642
+ throw error2;
6643
+ }
6644
+ };
6645
+ const isDead = (recorded) => recorded !== void 0 && checkRecordedPidLiveness(recorded, {
6646
+ observedScope: currentPidNamespaceScope(),
6647
+ observedBootId: currentBootId(),
6648
+ kill: options.kill
6649
+ }) === "dead";
6650
+ const latestClaimantHolds = (claimPath) => {
6651
+ let body;
6652
+ try {
6653
+ body = JSON.parse(fs10.readFileSync(claimPath, "utf-8"));
6654
+ } catch (error2) {
6655
+ return !(error2 instanceof SyntaxError);
6656
+ }
6657
+ const claimant = body?.process;
6658
+ return isRecordedPid(claimant) && !isDead(claimant);
6659
+ };
6660
+ const claimRecord = (filePath, record) => {
6661
+ if (!record.completionOwnerId || record.completionOwnerId === state.completionOwnerId) return record;
6662
+ if (!isDead(record.completionOwnerProcess)) return void 0;
6663
+ if (!state.completionOwnerId) return record;
6664
+ const prefix = claimPrefix(record.token, record.completionOwnerId);
6665
+ const latest = latestClaimGeneration(fs10.readdirSync(subscriptionsDir), prefix);
6666
+ if (latest > 0 && latestClaimantHolds(path9.join(subscriptionsDir, `${prefix}${latest}`))) return void 0;
6667
+ const claimPath = path9.join(subscriptionsDir, `${prefix}${latest + 1}`);
6668
+ if (!createClaimFile(claimPath, { ownerId: state.completionOwnerId, process: currentRecordedPid() })) return void 0;
6669
+ try {
6670
+ if (readRecordFile(filePath)?.completionOwnerId !== record.completionOwnerId) {
6671
+ fs10.rmSync(claimPath, { force: true });
6672
+ return void 0;
6673
+ }
6674
+ const claimed = { ...record, completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() };
6675
+ writeAtomicJson(filePath, claimed);
6676
+ return claimed;
6677
+ } catch (error2) {
6678
+ fs10.rmSync(claimPath, { force: true });
6679
+ throw error2;
6680
+ }
6681
+ };
6613
6682
  const sweepExpiredForeignSubscriptions = (force = false) => {
6614
6683
  const sweptAt = now();
6615
6684
  if (!force && sweptAt - lastForeignSweepAt < FOREIGN_SWEEP_INTERVAL_MS) return;
@@ -6625,7 +6694,7 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6625
6694
  const filePath = path9.join(subscriptionsDir, file);
6626
6695
  let record;
6627
6696
  try {
6628
- record = parseRecord(JSON.parse(fs10.readFileSync(filePath, "utf-8")));
6697
+ record = readRecordFile(filePath);
6629
6698
  } catch (error2) {
6630
6699
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error2);
6631
6700
  continue;
@@ -6636,23 +6705,31 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6636
6705
  try {
6637
6706
  fs10.unlinkSync(filePath);
6638
6707
  } catch (error2) {
6639
- if (!isNotFound(error2)) console.error(`Failed to remove expired wait subscription '${filePath}':`, error2);
6708
+ if (!isNotFound(error2)) {
6709
+ console.error(`Failed to remove expired wait subscription '${filePath}':`, error2);
6710
+ continue;
6711
+ }
6640
6712
  }
6713
+ removeClaimFiles(subscriptionsDir, record.token);
6641
6714
  }
6642
6715
  };
6643
6716
  const remove = (record) => {
6717
+ let removed = true;
6644
6718
  try {
6645
6719
  fs10.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
6646
6720
  } catch (error2) {
6647
6721
  if (!isNotFound(error2)) throw error2;
6722
+ removed = false;
6648
6723
  }
6649
6724
  subscriptions.delete(record.token);
6650
6725
  unresolvedRestoredForegroundTokens.delete(record.token);
6726
+ removeClaimFiles(subscriptionsDir, record.token);
6727
+ return removed;
6651
6728
  };
6652
6729
  const settle = (record, outcome, detail, completion) => {
6653
6730
  if (disposed || state.currentSessionId !== record.sessionId) return;
6654
6731
  try {
6655
- remove(record);
6732
+ if (!remove(record)) return;
6656
6733
  } catch (error2) {
6657
6734
  console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error2);
6658
6735
  return;
@@ -6765,6 +6842,7 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6765
6842
  version: SUBSCRIPTION_VERSION,
6766
6843
  token: randomUUID4(),
6767
6844
  sessionId,
6845
+ ...state.completionOwnerId ? { completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() } : {},
6768
6846
  targetKind: input.targetKind,
6769
6847
  runId: input.runId,
6770
6848
  requestedId: input.requestedId,
@@ -6789,16 +6867,19 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6789
6867
  throw error2;
6790
6868
  }
6791
6869
  for (const file of files) {
6870
+ const filePath = path9.join(subscriptionsDir, file);
6871
+ let record;
6792
6872
  try {
6793
- const record = parseRecord(JSON.parse(fs10.readFileSync(path9.join(subscriptionsDir, file), "utf-8")));
6794
- if (!record || file !== `${record.token}.json`) continue;
6795
- if (record.sessionId === state.currentSessionId) {
6796
- subscriptions.set(record.token, record);
6797
- if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
6798
- }
6873
+ const found = readRecordFile(filePath);
6874
+ if (!found || file !== `${found.token}.json` || found.sessionId !== state.currentSessionId) continue;
6875
+ record = claimRecord(filePath, found);
6799
6876
  } catch (error2) {
6800
- console.error(`Ignoring invalid wait subscription '${path9.join(subscriptionsDir, file)}':`, error2);
6877
+ console.error(`Failed to restore wait subscription '${filePath}':`, error2);
6878
+ continue;
6801
6879
  }
6880
+ if (!record) continue;
6881
+ subscriptions.set(record.token, record);
6882
+ if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
6802
6883
  }
6803
6884
  reconcile();
6804
6885
  },
@@ -7101,6 +7182,7 @@ var CHORD_PEER_ALIASES = [
7101
7182
  { specifier: "@earendil-works/chord", pkg: "@earendil-works/chord", subpath: "." },
7102
7183
  { specifier: "@earendil-works/chord/context", pkg: "@earendil-works/chord", subpath: "./context" }
7103
7184
  ];
7185
+ var SCHEMA_PACKAGE = "@earendil-works/pi-schema";
7104
7186
  function readManifest(packageDir) {
7105
7187
  try {
7106
7188
  return JSON.parse(fs12.readFileSync(path11.join(packageDir, "package.json"), "utf-8"));
@@ -7191,6 +7273,15 @@ function resolveHostPeerAliases(piPackageRoot) {
7191
7273
  if (target && fs12.existsSync(target)) aliases[specifier] = fs12.realpathSync(target);
7192
7274
  else if (pkg !== CHORD_PACKAGE || chordRequired) missing.push(specifier);
7193
7275
  }
7276
+ const piAiDir = findPeerPackageDir(piPackageRoot, "@earendil-works/pi-ai", hostManifest?.name);
7277
+ const piAiManifest = piAiDir ? readManifest(piAiDir) : void 0;
7278
+ if (piAiDir && piAiManifest && declaresDependency(piAiManifest, SCHEMA_PACKAGE)) {
7279
+ const schemaDir = findPeerPackageDir(fs12.realpathSync(piAiDir), SCHEMA_PACKAGE, void 0);
7280
+ for (const subpath of [".", "./formats"]) {
7281
+ const target = schemaDir ? resolvePackageSubpath(schemaDir, subpath) : void 0;
7282
+ if (!target || !fs12.existsSync(target)) missing.push(subpath === "." ? SCHEMA_PACKAGE : `${SCHEMA_PACKAGE}/formats`);
7283
+ }
7284
+ }
7194
7285
  return { aliases, missing };
7195
7286
  }
7196
7287
 
@@ -7462,10 +7553,12 @@ function createDefaultChildSessionFactory(options = {}) {
7462
7553
  const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
7463
7554
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5e3;
7464
7555
  let runtime;
7465
- const live = /* @__PURE__ */ new Set();
7556
+ const live = /* @__PURE__ */ new Map();
7466
7557
  const shutdowns = /* @__PURE__ */ new Set();
7467
7558
  const mcpWaits = /* @__PURE__ */ new Map();
7468
- let disposals = 0;
7559
+ let globalDisposals = 0;
7560
+ const parentDisposals = /* @__PURE__ */ new Map();
7561
+ const parentDisposalEpoch = (parent) => parentDisposals.get(parent) ?? 0;
7469
7562
  const sharedRuntime = async (pi) => {
7470
7563
  runtime ??= pi.ModelRuntime.create().catch((error2) => {
7471
7564
  runtime = void 0;
@@ -7473,9 +7566,28 @@ function createDefaultChildSessionFactory(options = {}) {
7473
7566
  });
7474
7567
  return runtime;
7475
7568
  };
7569
+ const disposeMatching = async (matches) => {
7570
+ for (const [cancel, wait] of mcpWaits) if (matches(wait.parent)) cancel.abort();
7571
+ const children = [...live.keys()].filter((child) => !child.detached && matches(live.get(child)));
7572
+ for (const child of children) child.shutDown = true;
7573
+ await Promise.allSettled(children.map((child) => child.abort()));
7574
+ for (const child of children) {
7575
+ try {
7576
+ void child.dispose();
7577
+ } catch {
7578
+ }
7579
+ }
7580
+ await Promise.allSettled([
7581
+ ...shutdowns,
7582
+ ...[...mcpWaits.values()].filter((wait) => matches(wait.parent)).map((wait) => wait.ready)
7583
+ ]);
7584
+ if (live.size === 0) runtime = void 0;
7585
+ };
7476
7586
  return {
7477
7587
  async create(launch) {
7478
- const disposalsAtStart = disposals;
7588
+ const globalDisposalsAtStart = globalDisposals;
7589
+ const parentEpochAtStart = parentDisposalEpoch(launch.parentSessionFile);
7590
+ const disposedSinceStart = () => globalDisposals !== globalDisposalsAtStart || parentDisposalEpoch(launch.parentSessionFile) !== parentEpochAtStart;
7479
7591
  const pi = await loadPiCodingAgent();
7480
7592
  const builtinMcpTools = launch.builtinMcpTools ?? [];
7481
7593
  let readinessTool;
@@ -7624,11 +7736,11 @@ function createDefaultChildSessionFactory(options = {}) {
7624
7736
  if (builtinMcp) {
7625
7737
  const cancel = new AbortController();
7626
7738
  const signal = launch.signal ? AbortSignal.any([cancel.signal, launch.signal]) : cancel.signal;
7627
- if (disposals !== disposalsAtStart) cancel.abort();
7739
+ if (disposedSinceStart()) cancel.abort();
7628
7740
  const ready = (async () => {
7629
7741
  try {
7630
7742
  await builtinMcp.waitForTools(signal, () => loader.getExtensions().errors.find(({ path: path17 }) => path17 === "builtin:mcp")?.error);
7631
- if (disposals !== disposalsAtStart) throw new Error("The child session factory was disposed while the child waited for its MCP tools.");
7743
+ if (disposedSinceStart()) throw new Error("The child session factory was disposed while the child waited for its MCP tools.");
7632
7744
  if (signal.aborted) throw new Error("The child launch was cancelled while waiting for its MCP tools.");
7633
7745
  const missing = missingBuiltinMcpTools(session, builtinMcpTools.map(({ name }) => name));
7634
7746
  if (missing.length) throw new Error(`Selected built-in MCP tools did not register in the child session: ${missing.join(", ")}. The MCP server may have failed to connect, or the name belongs to a different tool than the selector names; check it with /mcp.`);
@@ -7637,7 +7749,7 @@ function createDefaultChildSessionFactory(options = {}) {
7637
7749
  throw error2;
7638
7750
  }
7639
7751
  })();
7640
- mcpWaits.set(cancel, ready);
7752
+ mcpWaits.set(cancel, { ready, parent: launch.parentSessionFile });
7641
7753
  try {
7642
7754
  await ready;
7643
7755
  } finally {
@@ -7691,23 +7803,16 @@ function createDefaultChildSessionFactory(options = {}) {
7691
7803
  return session.model?.contextWindow;
7692
7804
  }
7693
7805
  };
7694
- live.add(child);
7806
+ live.set(child, launch.parentSessionFile);
7695
7807
  return child;
7696
7808
  },
7697
7809
  async dispose() {
7698
- disposals += 1;
7699
- for (const cancel of mcpWaits.keys()) cancel.abort();
7700
- const children = [...live].filter((child) => !child.detached);
7701
- for (const child of children) child.shutDown = true;
7702
- await Promise.allSettled(children.map((child) => child.abort()));
7703
- for (const child of children) {
7704
- try {
7705
- void child.dispose();
7706
- } catch {
7707
- }
7708
- }
7709
- await Promise.allSettled([...shutdowns, ...mcpWaits.values()]);
7710
- if (live.size === 0) runtime = void 0;
7810
+ globalDisposals += 1;
7811
+ await disposeMatching(() => true);
7812
+ },
7813
+ async disposeForParent(parentSessionFile) {
7814
+ parentDisposals.set(parentSessionFile, parentDisposalEpoch(parentSessionFile) + 1);
7815
+ await disposeMatching((parent) => parent === parentSessionFile);
7711
7816
  }
7712
7817
  };
7713
7818
  }
@@ -7719,28 +7824,28 @@ function childSessionFactory() {
7719
7824
  }
7720
7825
  function createLazyPlacementFactory(local) {
7721
7826
  let placed;
7722
- const factory = async () => placed ??= (await import("./chunk-BU6PFPVX.js")).createPlacementAwareChildSessionFactory(local);
7827
+ const factory = async () => placed ??= (await import("./chunk-YEXKJJVS.js")).createPlacementAwareChildSessionFactory(local);
7723
7828
  return {
7724
7829
  async create(launch) {
7725
7830
  return launch.machine ? (await factory()).create(launch) : local.create(launch);
7726
7831
  },
7727
7832
  async dispose() {
7728
- if (placed) await placed.dispose();
7729
- else await local.dispose();
7833
+ await (placed ?? local).dispose();
7834
+ },
7835
+ async disposeForParent(parentSessionFile) {
7836
+ await (placed ?? local).disposeForParent(parentSessionFile);
7730
7837
  }
7731
7838
  };
7732
7839
  }
7733
7840
  function childSessionFactoryModule() {
7734
7841
  return activeFactoryModule;
7735
7842
  }
7736
- async function disposeChildSessions() {
7737
- const factory = activeFactory;
7738
- if (!factory) return;
7739
- await factory.dispose();
7843
+ async function disposeChildSessionsForParent(parentSessionFile) {
7844
+ await activeFactory?.disposeForParent(parentSessionFile);
7740
7845
  }
7741
7846
 
7742
7847
  // src/workflows/workflow-reuse.ts
7743
- import { createHash as createHash3 } from "node:crypto";
7848
+ import { createHash as createHash4 } from "node:crypto";
7744
7849
  import * as fs14 from "node:fs";
7745
7850
  import * as path13 from "node:path";
7746
7851
  var WORKFLOW_CHILD_JOURNAL_FILE = "workflow-children.jsonl";
@@ -7752,7 +7857,7 @@ function workflowStopCause(reason) {
7752
7857
  return reason instanceof Error && "workflowStopCause" in reason && reason.workflowStopCause === WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED ? WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED : void 0;
7753
7858
  }
7754
7859
  function sha256(text2) {
7755
- return createHash3("sha256").update(text2).digest("hex");
7860
+ return createHash4("sha256").update(text2).digest("hex");
7756
7861
  }
7757
7862
  function workflowScriptDigest(script) {
7758
7863
  return sha256(script);
@@ -7877,7 +7982,7 @@ import { randomUUID as randomUUID6 } from "node:crypto";
7877
7982
  import * as path14 from "node:path";
7878
7983
  var MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
7879
7984
  function workflowResumeRefusal(code, reason, runId) {
7880
- const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
7985
+ const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" || code === "drained" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
7881
7986
  return { code, reason, byHand };
7882
7987
  }
7883
7988
  function manualWorkflowResumeRefusalText(runId, refusal) {
@@ -7907,6 +8012,7 @@ function prepareWorkflowResume(input) {
7907
8012
  if (trigger === "manual") reconcileAsyncRun(sourceAsyncDir);
7908
8013
  const status = readStatus(sourceAsyncDir);
7909
8014
  if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause)) return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
8015
+ if (status.workflow?.drainRequestedAt !== void 0) return refuse("drained", "it was being drained when it was interrupted");
7910
8016
  const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
7911
8017
  if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS) return refuse("attempts", `${MAX_WORKFLOW_RESUME_ATTEMPTS} resumes already followed Pi exits`);
7912
8018
  if (record.source === "structured") return refuse("structured", "launched from tasks/chain");
@@ -8652,7 +8758,7 @@ export {
8652
8758
  childSessionHasQueuedMessages,
8653
8759
  childSessionFactory,
8654
8760
  childSessionFactoryModule,
8655
- disposeChildSessions,
8761
+ disposeChildSessionsForParent,
8656
8762
  WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE,
8657
8763
  runtimeReplacedAbortReason,
8658
8764
  workflowStopCause,
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  isTrustedRecordedSessionFile,
3
3
  resolveSubagentRunId
4
- } from "./chunk-UR7OW5S7.js";
4
+ } from "./chunk-2NY5PCKQ.js";
5
5
  import {
6
6
  agentStreamOptions,
7
7
  opencodeSessionHeaders,
8
8
  resolveAsyncResumeTarget
9
- } from "./chunk-BGXEAYUM.js";
9
+ } from "./chunk-XV7RTWTS.js";
10
10
  import {
11
11
  ownsRun
12
12
  } from "./chunk-HXRB42AF.js";
@@ -18,12 +18,12 @@ import {
18
18
  reconcileAsyncRun,
19
19
  resolveAuthorityDecision,
20
20
  resolveMissionStoreLocation
21
- } from "./chunk-GJGTMLPE.js";
21
+ } from "./chunk-PGU4TZV3.js";
22
22
  import {
23
23
  deliverInterruptRequest,
24
24
  queueRevivalBrief,
25
25
  requestAsyncSteer
26
- } from "./chunk-5H4BICQZ.js";
26
+ } from "./chunk-VFUFOZBU.js";
27
27
  import {
28
28
  formatShellCommand
29
29
  } from "./chunk-7J4ZXMY7.js";
@@ -34,7 +34,7 @@ import {
34
34
  tryLease,
35
35
  writeAtomicJson,
36
36
  writePrivateAtomicJson
37
- } from "./chunk-QGO6HXHG.js";
37
+ } from "./chunk-C3KWLXDH.js";
38
38
  import {
39
39
  DIRS
40
40
  } from "./chunk-JEZOSEWG.js";
@@ -1,32 +1,32 @@
1
1
  import {
2
2
  rewriteSubagentPrompt
3
- } from "./chunk-7ADDXUGF.js";
3
+ } from "./chunk-OTLDAYEQ.js";
4
4
  import {
5
5
  package_default
6
- } from "./chunk-7ZUFN6ME.js";
6
+ } from "./chunk-OOE3R7IQ.js";
7
7
  import {
8
8
  WATCHDOG_DIFF_TOOL_NAME,
9
9
  captureWatchdogDiffBaseline,
10
10
  createWatchdogDiffTool
11
- } from "./chunk-ZJJCPV3L.js";
12
- import "./chunk-BGXEAYUM.js";
13
- import "./chunk-ZPY5QZCS.js";
11
+ } from "./chunk-AIL46SZU.js";
12
+ import "./chunk-XV7RTWTS.js";
13
+ import "./chunk-W52LJANO.js";
14
14
  import {
15
15
  MODEL_ONLY_TOOL
16
16
  } from "./chunk-HXRB42AF.js";
17
- import "./chunk-NF7IEKBH.js";
17
+ import "./chunk-W2BZS6UC.js";
18
18
  import {
19
19
  appendAgentRefinementOverlay
20
- } from "./chunk-LGINOOY5.js";
21
- import "./chunk-GJGTMLPE.js";
20
+ } from "./chunk-USRX7QXD.js";
21
+ import "./chunk-PGU4TZV3.js";
22
22
  import "./chunk-NIXWDZZV.js";
23
- import "./chunk-77ASNIEM.js";
23
+ import "./chunk-ESWW6XSX.js";
24
24
  import "./chunk-7F6RKT6W.js";
25
25
  import {
26
26
  assertNoToolModifierEntries
27
- } from "./chunk-374MZFF4.js";
27
+ } from "./chunk-SIAQXPJ4.js";
28
28
  import "./chunk-CTPAE36Y.js";
29
- import "./chunk-GRJHIXYF.js";
29
+ import "./chunk-XSDYTXHF.js";
30
30
  import {
31
31
  HERDR_PI_MAX_FRAME_BYTES,
32
32
  HERDR_PI_PROTOCOL,
@@ -43,7 +43,7 @@ import {
43
43
  discoverAgents,
44
44
  resolveExistingReadPaths,
45
45
  resolveSkills
46
- } from "./chunk-QGO6HXHG.js";
46
+ } from "./chunk-C3KWLXDH.js";
47
47
  import "./chunk-JEZOSEWG.js";
48
48
  import "./chunk-YFCK7H2S.js";
49
49
  import "./chunk-QXASAHIA.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  appendAgentRefinementOverlay
3
- } from "./chunk-LGINOOY5.js";
3
+ } from "./chunk-USRX7QXD.js";
4
4
  import {
5
5
  buildAgentMemoryInjection,
6
6
  buildSkillInjection
7
- } from "./chunk-QGO6HXHG.js";
7
+ } from "./chunk-C3KWLXDH.js";
8
8
 
9
9
  // src/runs/shared/effective-system-prompt.ts
10
10
  function appendSection(prompt, section) {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  buildWorkflowChatProgressRows
3
- } from "./chunk-UR7OW5S7.js";
3
+ } from "./chunk-2NY5PCKQ.js";
4
4
  import {
5
5
  aggregateStepStatus,
6
6
  contextModeBadge,
@@ -21,7 +21,7 @@ import {
21
21
  projectAsyncWorkflowRows,
22
22
  projectWorkflowChecklist,
23
23
  workflowGraphStageNodes
24
- } from "./chunk-BGXEAYUM.js";
24
+ } from "./chunk-XV7RTWTS.js";
25
25
  import {
26
26
  isStaleExtensionContextError,
27
27
  isUnboundExtensionRuntimeError,
@@ -33,7 +33,7 @@ import {
33
33
  formatWorkflowJsonPreview,
34
34
  hostStepReportName,
35
35
  hostStepVerdictLabel
36
- } from "./chunk-GJGTMLPE.js";
36
+ } from "./chunk-PGU4TZV3.js";
37
37
  import {
38
38
  snapshotExternalRuns
39
39
  } from "./chunk-UKG4V45O.js";
@@ -51,7 +51,7 @@ import {
51
51
  getSingleResultOutput,
52
52
  shortenPath,
53
53
  unresolvedChildWatchdogBlockers
54
- } from "./chunk-QGO6HXHG.js";
54
+ } from "./chunk-C3KWLXDH.js";
55
55
  import {
56
56
  MAX_WIDGET_JOBS,
57
57
  WIDGET_ANIMATION_INTERVAL_MS,
@@ -11,13 +11,13 @@ import {
11
11
  validateAuthorityPolicy,
12
12
  validateMissionStoreConfig,
13
13
  validateModelResponseAliases
14
- } from "./chunk-GJGTMLPE.js";
14
+ } from "./chunk-PGU4TZV3.js";
15
15
  import {
16
16
  getAgentDir,
17
17
  readStatus,
18
18
  validatePermissionConfig,
19
19
  writePrivateAtomicJson
20
- } from "./chunk-QGO6HXHG.js";
20
+ } from "./chunk-C3KWLXDH.js";
21
21
  import {
22
22
  FLEET_KEYBINDING_ACTIONS,
23
23
  RUNNER_LAUNCHER_NAME_PATTERN,