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-IQIWF2VX.js → chunk-AIL46SZU.js} +8 -6
  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-3UZ5FVVJ.js → chunk-DGTZKYIE.js} +39 -34
  13. package/bundle/{chunk-KDMFBYFM.js → chunk-ESWW6XSX.js} +1 -1
  14. package/bundle/{chunk-WOVMHDES.js → chunk-EYGBK6CE.js} +194 -94
  15. package/bundle/{chunk-CS4O36CZ.js → chunk-HDICKROY.js} +5 -5
  16. package/bundle/{chunk-DV2NCNPR.js → chunk-JLDQ6YUR.js} +12 -12
  17. package/bundle/{chunk-RQAUNAWG.js → chunk-LFKMM3UH.js} +2 -2
  18. package/bundle/{chunk-L2ENOFVZ.js → chunk-LZKVUWIY.js} +66 -26
  19. package/bundle/{chunk-RV5OGHLO.js → chunk-M2VBGET6.js} +2 -2
  20. package/bundle/{chunk-HFTBF7SG.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-JNXT3MPI.js → chunk-OTLDAYEQ.js} +5 -5
  22. package/bundle/{chunk-JWYG26RE.js → chunk-OZCPYJEY.js} +80 -37
  23. package/bundle/{chunk-LGMILZNE.js → chunk-PGU4TZV3.js} +79 -32
  24. package/bundle/{chunk-KEY3UQMQ.js → chunk-SIAQXPJ4.js} +6 -8
  25. package/bundle/{chunk-QO75KJBT.js → chunk-USRX7QXD.js} +2 -2
  26. package/bundle/{chunk-7MAE3DJV.js → chunk-VFUFOZBU.js} +1 -1
  27. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  28. package/bundle/{chunk-T5V5BRCL.js → chunk-W52LJANO.js} +1 -1
  29. package/bundle/{chunk-PHZP3KHB.js → chunk-XSDYTXHF.js} +18 -11
  30. package/bundle/{chunk-LTPH2DXH.js → chunk-XV7RTWTS.js} +3 -3
  31. package/bundle/{chunk-JO67XSKD.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 +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 +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/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
@@ -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[]>;
@@ -957,7 +957,7 @@ export function buildAsyncRunnerSteps(id, params) {
957
957
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
958
958
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
959
959
  const primaryModelFromParent = modelOrigin === "inherited";
960
- const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
960
+ 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 });
961
961
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
962
962
  let claudeCodeOverride;
963
963
  if (claudeCodeAdapter) {
@@ -999,6 +999,7 @@ export function buildAsyncRunnerSteps(id, params) {
999
999
  scope: modelScopes,
1000
1000
  primaryModelFromParent,
1001
1001
  origin: modelOrigin,
1002
+ knownProviders: ctx.knownProviders,
1002
1003
  });
1003
1004
  requestedModel = modelEvidence.requestedModel;
1004
1005
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== undefined);
@@ -1755,7 +1756,7 @@ export function executeAsyncSingle(id, params) {
1755
1756
  try {
1756
1757
  primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
1757
1758
  ? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
1758
- : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
1759
+ : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders });
1759
1760
  }
1760
1761
  catch (error) {
1761
1762
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
@@ -1822,6 +1823,7 @@ export function executeAsyncSingle(id, params) {
1822
1823
  scope: modelScopes,
1823
1824
  primaryModelFromParent: modelOrigin === "inherited",
1824
1825
  origin: modelOrigin,
1826
+ knownProviders: ctx.knownProviders,
1825
1827
  });
1826
1828
  requestedModel = modelEvidence.requestedModel;
1827
1829
  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
  },
@@ -10,4 +10,4 @@ export declare function stopAsyncRun(state: SubagentState, runId: string | undef
10
10
  asyncDir: string | null;
11
11
  resolvedId?: string;
12
12
  reattachedRunId?: string;
13
- }, childId?: string): AgentToolResult<Details> | null;
13
+ }, childId?: string, drain?: boolean): AgentToolResult<Details> | null;
@@ -130,7 +130,7 @@ export function deliverAsyncRunStop(input) {
130
130
  if (pausedWholeRun)
131
131
  return sealPausedRun(delivery.asyncDir, status, resultsDir);
132
132
  }
133
- export function stopAsyncRun(state, runId, kill, location, childId) {
133
+ export function stopAsyncRun(state, runId, kill, location, childId, drain) {
134
134
  const target = getAsyncStopTarget(state, runId, location);
135
135
  // An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
136
136
  const workflowRunId = target?.asyncId ?? runId;
@@ -139,6 +139,14 @@ export function stopAsyncRun(state, runId, kill, location, childId) {
139
139
  const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
140
140
  // Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
141
141
  const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
142
+ if (drain) {
143
+ const drained = workflowController && workflowRunId && !foreignWorkflow && !workflowController.signal.aborted ? state.workflowDrains?.get(workflowRunId)?.() : undefined;
144
+ if (!drained)
145
+ return { content: [{ type: "text", text: `drain applies only to live async workflows in this session; '${runId ?? "current"}' is not one.` }], isError: true, details: { mode: "management", results: [] } };
146
+ if (!drained.ok)
147
+ return { content: [{ type: "text", text: `Could not save the drain request for '${workflowRunId}'; nothing was stopped. Retry, or use stop without drain.` }], isError: true, details: { mode: "management", results: [] } };
148
+ return { content: [{ type: "text", text: `Drain requested for async workflow ${workflowRunId}: no new children will start; ${drained.started} started child(ren) will finish.` }], details: { mode: "management", results: [] } };
149
+ }
142
150
  if (workflowController && workflowRunId && !foreignWorkflow) {
143
151
  if (workflowStatus)
144
152
  stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
@@ -1796,6 +1796,7 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1796
1796
  scope: options.modelScope,
1797
1797
  primaryModelFromParent: options.modelOverrideFromParent,
1798
1798
  origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1799
+ knownProviders: options.knownProviders,
1799
1800
  });
1800
1801
  try {
1801
1802
  const model = applyThinkingSuffix(selectedModel, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
@@ -48,6 +48,7 @@ export interface SubagentParamsLike {
48
48
  index?: number;
49
49
  toolCallId?: string;
50
50
  childId?: string;
51
+ drain?: boolean;
51
52
  view?: "fleet" | "transcript";
52
53
  lines?: number;
53
54
  topic?: string;