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
@@ -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
  }
@@ -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;
@@ -24,7 +24,7 @@ import { commandAction } from "./command-action.js";
24
24
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.js";
25
25
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.js";
26
26
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.js";
27
- import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, scopedModelIdsFromContext } from "../shared/model-resolution.js";
27
+ import { knownModelProviders, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, scopedModelIdsFromContext } from "../shared/model-resolution.js";
28
28
  import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.js";
29
29
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.js";
30
30
  import { resolveModelScopesForAgent } from "../shared/model-scope.js";
@@ -1063,6 +1063,7 @@ function appendStepToAsyncChain(input) {
1063
1063
  parentProviderRegistry: input.ctx.modelRegistry,
1064
1064
  currentModel: parentModel,
1065
1065
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1066
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1066
1067
  modelScope: discoveredForAppend.modelScope,
1067
1068
  modelResponseAliases: input.deps.config.modelResponseAliases,
1068
1069
  interactive: input.ctx.hasUI,
@@ -1551,6 +1552,7 @@ async function resumeExternalJobFollowUp(input) {
1551
1552
  parentProviderRegistry: input.ctx.modelRegistry,
1552
1553
  currentModel: parentModel,
1553
1554
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1555
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1554
1556
  modelScope: input.modelScope,
1555
1557
  modelResponseAliases: input.deps.config.modelResponseAliases,
1556
1558
  interactive: input.ctx.hasUI,
@@ -1855,6 +1857,7 @@ async function resumeAsyncRun(input) {
1855
1857
  parentProviderRegistry: input.ctx.modelRegistry,
1856
1858
  currentModel: parentModel,
1857
1859
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1860
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1858
1861
  modelScope,
1859
1862
  modelResponseAliases: input.deps.config.modelResponseAliases,
1860
1863
  runnerLaunchers: input.deps.config.runnerLaunchers,
@@ -1998,6 +2001,7 @@ async function resumeAsyncRun(input) {
1998
2001
  parentProviderRegistry: input.ctx.modelRegistry,
1999
2002
  currentModel: parentModel,
2000
2003
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
2004
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
2001
2005
  modelScope,
2002
2006
  // Absence in the retained contract is meaningful; never acquire current aliases.
2003
2007
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
@@ -2874,7 +2878,7 @@ function resolveStaticLaunchSummary(input) {
2874
2878
  const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel, input.scopedModelIds);
2875
2879
  const model = externalRunner
2876
2880
  ? undefined
2877
- : resolveEffectiveSubagentModel(input.explicitModel, agentConfig?.model, input.parentModel, input.availableModels, agentConfig?.modelProvider ?? input.currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes });
2881
+ : resolveEffectiveSubagentModel(input.explicitModel, agentConfig?.model, input.parentModel, input.availableModels, agentConfig?.modelProvider ?? input.currentProvider, { scope: modelScopes, knownProviders: input.knownProviders });
2878
2882
  const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask();
2879
2883
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2880
2884
  return {
@@ -2892,6 +2896,7 @@ function collectStaticLaunchSummaries(input) {
2892
2896
  parentModel: input.parentModel,
2893
2897
  scopedModelIds: input.scopedModelIds,
2894
2898
  availableModels: input.availableModels,
2899
+ knownProviders: input.knownProviders,
2895
2900
  currentProvider: input.currentProvider,
2896
2901
  modelScope: input.modelScope,
2897
2902
  thinkingOverrideForTask: input.thinkingOverrideForTask,
@@ -3171,6 +3176,7 @@ async function runAsyncPath(data, deps) {
3171
3176
  parentProviderRegistry: ctx.modelRegistry,
3172
3177
  currentModel: parentModel,
3173
3178
  scopedModelIds: data.scopedModelIds,
3179
+ knownProviders: knownModelProviders(ctx.modelRegistry),
3174
3180
  modelScope: data.modelScope,
3175
3181
  modelResponseAliases: deps.config.modelResponseAliases,
3176
3182
  runnerLaunchers: deps.config.runnerLaunchers,
@@ -3215,8 +3221,9 @@ async function runAsyncPath(data, deps) {
3215
3221
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
3216
3222
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
3217
3223
  : resolveEffectiveSubagentModel(params.model, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, {
3218
- ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3224
+ scope: modelScopes,
3219
3225
  source: modelOrigin === "explicit" ? "explicit" : "inherited",
3226
+ knownProviders: asyncCtx.knownProviders,
3220
3227
  });
3221
3228
  const modelOverrideFromParent = modelOrigin === "inherited";
3222
3229
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -3644,6 +3651,7 @@ async function runSinglePath(data, deps) {
3644
3651
  const parentModel = data.parentModel;
3645
3652
  const currentProvider = parentModel?.provider;
3646
3653
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
3654
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
3647
3655
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
3648
3656
  let task = typeof params.task === "string" ? params.task : "";
3649
3657
  const modelOrigin = resolveModelOrigin({
@@ -3653,8 +3661,9 @@ async function runSinglePath(data, deps) {
3653
3661
  parentModel,
3654
3662
  });
3655
3663
  let modelOverride = resolveEffectiveSubagentModel(params.model, agentConfig.model, parentModel, availableModels, agentConfig.modelProvider ?? currentProvider, {
3656
- ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3664
+ scope: modelScopes,
3657
3665
  source: modelOrigin === "explicit" ? "explicit" : "inherited",
3666
+ knownProviders,
3658
3667
  });
3659
3668
  const modelOverrideFromParent = modelOrigin === "inherited";
3660
3669
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: agentConfig.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -3902,6 +3911,7 @@ async function runSinglePath(data, deps) {
3902
3911
  thinkingCeiling: agentConfig.maxThinking,
3903
3912
  extensionBindings: params.extensionBindings,
3904
3913
  availableModels,
3914
+ knownProviders,
3905
3915
  modelResponseAliases,
3906
3916
  preferredModelProvider: currentProvider,
3907
3917
  modelScope: modelScopes,
@@ -5179,6 +5189,7 @@ export function createSubagentExecutor(deps) {
5179
5189
  const controller = new AbortController();
5180
5190
  deps.state.workflowControllers ??= new Map();
5181
5191
  deps.state.workflowChildStops ??= new Map();
5192
+ deps.state.workflowDrains ??= new Map();
5182
5193
  deps.state.workflowControllers.set(workflowRunId, controller);
5183
5194
  workflowCapacity?.markWorkflowStarted();
5184
5195
  if (workflowCapacity)
@@ -5809,6 +5820,36 @@ export function createSubagentExecutor(deps) {
5809
5820
  else
5810
5821
  deps.state.workflowChildStops?.delete(workflowRunId);
5811
5822
  },
5823
+ registerDrain: (drain) => {
5824
+ if (!drain)
5825
+ deps.state.workflowDrains?.delete(workflowRunId);
5826
+ else
5827
+ deps.state.workflowDrains?.set(workflowRunId, () => {
5828
+ if (workflowRunEvidence.drainRequestedAt === undefined) {
5829
+ // The marker must be on disk before anything is stopped: without it a reload during the drain would resume the run.
5830
+ const previousWorkflow = status.workflow;
5831
+ workflowRunEvidence.drainRequestedAt = Date.now();
5832
+ status.workflow = { ...(previousWorkflow ?? { trace: [], emits: [], console: [] }), drainRequestedAt: workflowRunEvidence.drainRequestedAt };
5833
+ let saved = false;
5834
+ try {
5835
+ persist();
5836
+ saved = runPersistence.pendingCount() === 0;
5837
+ }
5838
+ catch (error) {
5839
+ console.error(`Failed to save the drain request for async workflow '${workflowRunId}':`, error);
5840
+ }
5841
+ if (!saved) {
5842
+ delete workflowRunEvidence.drainRequestedAt;
5843
+ status.workflow = previousWorkflow;
5844
+ // Replaces a queued write that still carries the marker.
5845
+ persist({ tolerateStatusWriteFailure: true });
5846
+ return { ok: false };
5847
+ }
5848
+ }
5849
+ // Deferred so a full stop that stops the last running child aborts with its own reason first.
5850
+ return { ok: true, started: drain(() => queueMicrotask(() => controller.abort(new Error("Workflow drained: started children finished; no new children were started.")))) };
5851
+ });
5852
+ },
5812
5853
  ...(workflowState ? { state: workflowState } : {}),
5813
5854
  onTrace: updateTrace,
5814
5855
  onChildSettled: (notification) => {
@@ -6151,8 +6192,7 @@ export function createSubagentExecutor(deps) {
6151
6192
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
6152
6193
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
6153
6194
  const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
6154
- // A top-level artifact file: outside outputs/, where children save their reports, and
6155
- // within artifact retention, which only removes top-level files.
6195
+ // Outside outputs/ so it cannot overwrite a child's report.
6156
6196
  const workflowFullResultPath = path.join(workflowArtifactsDir, `${sanitizeRunPathSegment(foregroundWorkflowRunId)}_workflow-result.md`);
6157
6197
  const claimedOutputPaths = new Map();
6158
6198
  const childOutputOverrides = new Map();
@@ -7039,6 +7079,8 @@ export function createSubagentExecutor(deps) {
7039
7079
  }
7040
7080
  if (action === "stop") {
7041
7081
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
7082
+ if (paramsWithResolvedCwd.drain && paramsWithResolvedCwd.childId !== undefined)
7083
+ return { content: [{ type: "text", text: "action='stop' drain applies to a whole workflow; omit childId." }], isError: true, details: { mode: "management", results: [] } };
7042
7084
  // Whole-workflow stops reach stopAsyncRun below, which stops a live workflow in-process.
7043
7085
  const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== undefined ? resolveLiveWorkflowRunId(deps, targetRunId) : undefined;
7044
7086
  if (workflowRunId && paramsWithResolvedCwd.childId !== undefined) {
@@ -7085,7 +7127,7 @@ export function createSubagentExecutor(deps) {
7085
7127
  if (paramsWithResolvedCwd.dir) {
7086
7128
  try {
7087
7129
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
7088
- const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
7130
+ const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
7089
7131
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
7090
7132
  }
7091
7133
  catch (error) {
@@ -7106,7 +7148,7 @@ export function createSubagentExecutor(deps) {
7106
7148
  return { content: [{ type: "text", text: "action='stop' supports current-session top-level async runs only." }], isError: true, details: { mode: "management", results: [] } };
7107
7149
  if (resolved?.kind === "foreground")
7108
7150
  return { content: [{ type: "text", text: "action='stop' supports async runs only. Use action='interrupt' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
7109
- const stopResult = stopAsyncRun(deps.state, resolved?.kind === "async" ? resolved.id : targetRunId, deps.kill, resolved?.kind === "async" ? resolved.location : undefined, paramsWithResolvedCwd.childId);
7151
+ const stopResult = stopAsyncRun(deps.state, resolved?.kind === "async" ? resolved.id : targetRunId, deps.kill, resolved?.kind === "async" ? resolved.location : undefined, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
7110
7152
  if (stopResult)
7111
7153
  return stopResult;
7112
7154
  return {
@@ -7651,6 +7693,7 @@ export function createSubagentExecutor(deps) {
7651
7693
  parentModel: requestParentModel,
7652
7694
  scopedModelIds: scopedModelIdsFromContext(ctx),
7653
7695
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7696
+ knownProviders: knownModelProviders(ctx.modelRegistry),
7654
7697
  currentProvider: requestParentModel?.provider,
7655
7698
  modelScope,
7656
7699
  thinkingOverrideForTask,
@@ -122,9 +122,9 @@ export interface ChildSession {
122
122
  };
123
123
  /** Event-updated pane-native status; reading it performs no network work. */
124
124
  readonly placementSnapshot?: unknown;
125
- /** Set by the foreground host once the run detached; `factory.dispose()` leaves such children running. */
125
+ /** Set by the foreground host once the run detached; factory disposal leaves such children running. */
126
126
  detached?: boolean;
127
- /** Set by `factory.dispose()` before it aborts the child, so the host can report the stop truthfully. */
127
+ /** Set by factory disposal before it aborts the child, so the host can report the stop truthfully. */
128
128
  shutDown?: boolean;
129
129
  }
130
130
  export declare function childSessionHasQueuedMessages(session: ChildSession | undefined): boolean;
@@ -132,6 +132,8 @@ export interface ChildSessionFactory {
132
132
  create(launch: ChildSessionLaunch): Promise<ChildSession>;
133
133
  /** Abort and dispose every live attached child; detached children keep running and hold the shared runtime. */
134
134
  dispose(): Promise<void>;
135
+ /** `dispose()` for only the children `parentSessionFile`'s session launched (undefined: sessions without a file); pi-web shuts sessions down one at a time. */
136
+ disposeForParent(parentSessionFile: string | undefined): Promise<void>;
135
137
  }
136
138
  export type PiCodingAgentModule = typeof import("@earendil-works/pi-coding-agent");
137
139
  export interface DefaultChildSessionFactoryOptions {
@@ -175,6 +177,5 @@ export declare function setChildSessionFactory(factory: ChildSessionFactory | un
175
177
  */
176
178
  export declare function childSessionFactoryModule(): string | undefined;
177
179
  export declare function setChildSessionFactoryModule(modulePath: string | undefined): void;
178
- /** Abort and dispose every live in-process child and release the shared runtime. */
179
- export declare function disposeChildSessions(): Promise<void>;
180
+ export declare function disposeChildSessionsForParent(parentSessionFile: string | undefined): Promise<void>;
180
181
  export {};