pi-subagents 0.89.2 → 0.90.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 (76) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agents.js +4 -4
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-U753SUBC.js → chunk-2LEBXCLU.js} +29 -19
  5. package/bundle/{chunk-UUW7P6KJ.js → chunk-37EJGDYO.js} +2 -2
  6. package/bundle/{chunk-ME4IS3Y3.js → chunk-4DA22WRU.js} +58 -29
  7. package/bundle/{chunk-77VQEATI.js → chunk-5J2RTMKW.js} +2 -2
  8. package/bundle/{chunk-UBPAMRVL.js → chunk-7HPZIT4W.js} +13 -13
  9. package/bundle/{chunk-SWGB2P5J.js → chunk-7Y4IJMCW.js} +1 -1
  10. package/bundle/{chunk-DGLXVN3F.js → chunk-ACTHBJUI.js} +1 -1
  11. package/bundle/{chunk-76WVWEFE.js → chunk-AJWRYQPH.js} +134 -74
  12. package/bundle/{chunk-TXC7WIPL.js → chunk-C45WQQZX.js} +1 -1
  13. package/bundle/{chunk-YJIU5WF4.js → chunk-CPWZN5KM.js} +1 -1
  14. package/bundle/{chunk-RHKIP45B.js → chunk-DNJ2GHSI.js} +6 -6
  15. package/bundle/{chunk-DYBRIEIF.js → chunk-EBGTTJKP.js} +6 -6
  16. package/bundle/{chunk-LWH7IGI3.js → chunk-F4NSLXB2.js} +8 -6
  17. package/bundle/{chunk-FO2GIU5F.js → chunk-G43SW4BT.js} +11 -10
  18. package/bundle/{chunk-Q4VH72JI.js → chunk-KNVQTRSY.js} +2 -2
  19. package/bundle/{chunk-5TXWZB73.js → chunk-P2M6RIVX.js} +1 -1
  20. package/bundle/{chunk-ROJH7KPK.js → chunk-PSB3VLMH.js} +2 -2
  21. package/bundle/{chunk-VEEUXJDO.js → chunk-PTN7XAXI.js} +2 -2
  22. package/bundle/{chunk-2UCFLUE4.js → chunk-RIBMW6V3.js} +9 -7
  23. package/bundle/{chunk-DHY5TY2Y.js → chunk-SIB2GQHL.js} +3 -3
  24. package/bundle/{chunk-JEZOSEWG.js → chunk-SRWJIAIP.js} +2 -0
  25. package/bundle/{chunk-JEYG7CNC.js → chunk-UC22RDXP.js} +2 -2
  26. package/bundle/{chunk-W2BZS6UC.js → chunk-VMJGZHUL.js} +9 -5
  27. package/bundle/{chunk-FF5K5HQU.js → chunk-WANQBKAZ.js} +5 -5
  28. package/bundle/{chunk-KA4MKMYT.js → chunk-WHHRG32M.js} +27 -20
  29. package/bundle/{chunk-464OJSDP.js → chunk-XIQKWTFY.js} +5 -5
  30. package/bundle/{chunk-4KQW5R6U.js → chunk-XYIVVS3A.js} +7 -3
  31. package/bundle/{chunk-AHGJSJYY.js → chunk-YVDKGAEO.js} +2 -2
  32. package/bundle/{chunk-SRCMJY4F.js → chunk-ZWGOHOGI.js} +5 -5
  33. package/bundle/control-channel.js +3 -3
  34. package/bundle/index.js +1 -1
  35. package/bundle/intercom-bridge.js +3 -3
  36. package/bundle/preflight.js +9 -9
  37. package/bundle/project-panes.js +4 -4
  38. package/bundle/shared-types.js +1 -1
  39. package/bundle/workflow-resources.js +1 -1
  40. package/docs/configuration.md +12 -3
  41. package/docs/models.md +1 -1
  42. package/docs/observability.md +7 -1
  43. package/docs/tool-reference.md +5 -2
  44. package/docs/workflows.md +1 -1
  45. package/package.json +1 -1
  46. package/skills/pi-subagents/SKILL.md +1 -1
  47. package/src/agents/agents.d.ts +2 -0
  48. package/src/agents/agents.js +4 -0
  49. package/src/extension/config.js +3 -0
  50. package/src/extension/public-execution.js +4 -2
  51. package/src/extension/reply-workflow-script.js +10 -1
  52. package/src/extension/schemas.d.ts +1 -0
  53. package/src/extension/schemas.js +2 -0
  54. package/src/extension/subagent-options.d.ts +2 -0
  55. package/src/extension/subagent-options.js +10 -4
  56. package/src/runs/background/async-execution.d.ts +1 -1
  57. package/src/runs/background/async-execution.js +3 -1
  58. package/src/runs/background/async-retention.js +48 -12
  59. package/src/runs/background/async-status.js +32 -17
  60. package/src/runs/background/retained-children.js +1 -1
  61. package/src/runs/foreground/execution.js +5 -7
  62. package/src/runs/foreground/subagent-executor.d.ts +1 -1
  63. package/src/runs/foreground/subagent-executor.js +122 -47
  64. package/src/runs/shared/fast-mode-extension.d.ts +2 -1
  65. package/src/runs/shared/fast-mode-extension.js +5 -3
  66. package/src/shared/capacity-resilient-json.d.ts +7 -3
  67. package/src/shared/capacity-resilient-json.js +8 -6
  68. package/src/shared/disabled-features.d.ts +4 -0
  69. package/src/shared/disabled-features.js +1 -0
  70. package/src/shared/types.d.ts +18 -1
  71. package/src/shared/types.js +2 -0
  72. package/src/tui/fleet.js +1 -0
  73. package/src/workflows/structured-workflow-scripts.js +6 -4
  74. package/src/workflows/workflow-resources.js +4 -2
  75. package/src/workflows/workflow-revival.d.ts +6 -0
  76. package/src/workflows/workflow-revival.js +1 -1
@@ -170,7 +170,7 @@ function deriveAsyncActivityState(asyncDir, status) {
170
170
  ?? (status.mode === "workflow" ? undefined : currentStep?.startedAt ?? status.startedAt),
171
171
  };
172
172
  }
173
- function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
173
+ function statusToSummary(asyncDir, status, nestedWarnings = []) {
174
174
  const statusPath = path.join(asyncDir, "status.json");
175
175
  validateAsyncStatusLaneMetadata(status, `Invalid async status '${statusPath}'`);
176
176
  const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
@@ -188,7 +188,6 @@ function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
188
188
  const { activityState, lastActivityAt } = deriveAsyncActivityState(asyncDir, status);
189
189
  const processTerminal = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId })
190
190
  ?? sanitizeProcessTerminal(status.processTerminal, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId }, path.join(asyncDir, "status.json"));
191
- const nestedProjectionAllowed = nestedWarnings.length === 0;
192
191
  // Degrade to the status-stored snapshot when the persisted budget is unavailable (e.g. removed
193
192
  // by OS temp cleanup) instead of failing the whole run list; admission paths stay strict.
194
193
  let runFanoutBudget = status.runFanoutBudget;
@@ -203,17 +202,6 @@ function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
203
202
  const steps = status.steps ?? [];
204
203
  const chainStepCount = status.chainStepCount ?? steps.length;
205
204
  const parallelGroups = normalizeParallelGroups(status.parallelGroups, steps.length, chainStepCount);
206
- let nestedChildren = [];
207
- if (nestedProjectionAllowed && nestedRoute) {
208
- try {
209
- // The route is resolved by the caller via buildNestedRouteIndex, so this
210
- // avoids a fresh scan of the nested-events directory per run.
211
- nestedChildren = projectNestedEvents(nestedRoute)?.children ?? [];
212
- }
213
- catch (error) {
214
- nestedWarnings.push(`Nested status unavailable: ${getErrorMessage(error)}`);
215
- }
216
- }
217
205
  const summarizedSteps = steps.map((step, index) => {
218
206
  const stepActivityState = step.activityState;
219
207
  const stepLastActivityAt = step.lastActivityAt;
@@ -289,7 +277,7 @@ function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
289
277
  ...(step.children?.length ? { children: step.children } : {}),
290
278
  };
291
279
  });
292
- attachRootChildrenToSteps(status.runId || path.basename(asyncDir), summarizedSteps, nestedChildren);
280
+ attachRootChildrenToSteps(status.runId || path.basename(asyncDir), summarizedSteps, undefined);
293
281
  return {
294
282
  id: status.runId || path.basename(asyncDir),
295
283
  asyncDir,
@@ -326,7 +314,6 @@ function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
326
314
  ...(hostSteps.length ? { hostSteps } : {}),
327
315
  ...(status.mode === "workflow" && status.workflowGraph ? { workflowGraph: status.workflowGraph } : {}),
328
316
  steps: summarizedSteps,
329
- ...(nestedChildren.length ? { nestedChildren } : {}),
330
317
  ...(nestedWarnings.length ? { nestedWarnings } : {}),
331
318
  ...(processTerminal ? { processTerminal } : {}),
332
319
  ...(runFanoutBudget ? { runFanoutBudget } : {}),
@@ -352,6 +339,24 @@ function statusToSummary(asyncDir, status, nestedWarnings = [], nestedRoute) {
352
339
  export function summarizeAsyncStatus(asyncDir, status) {
353
340
  return statusToSummary(asyncDir, status);
354
341
  }
342
+ /** Projects nested children onto summaries built without them. It never reconciles descendants. */
343
+ function attachNestedChildren(runs, resolveRoute = (run) => findNestedRouteForRootId(run.id)) {
344
+ for (const run of runs) {
345
+ let nestedChildren;
346
+ try {
347
+ const route = resolveRoute(run);
348
+ nestedChildren = route ? projectNestedEvents(route).children : [];
349
+ }
350
+ catch (error) {
351
+ run.nestedWarnings = [...(run.nestedWarnings ?? []), `Nested status unavailable: ${getErrorMessage(error)}`];
352
+ continue;
353
+ }
354
+ if (!nestedChildren.length)
355
+ continue;
356
+ run.nestedChildren = nestedChildren;
357
+ attachRootChildrenToSteps(run.id, run.steps, nestedChildren);
358
+ }
359
+ }
355
360
  function sortRuns(runs) {
356
361
  const rank = (state) => {
357
362
  switch (state) {
@@ -433,6 +438,7 @@ export function listAsyncRuns(asyncDirRoot, options = {}, observeStatus) {
433
438
  // load-time restoration (which only wants queued/running runs) skips it
434
439
  // entirely when no active runs match.
435
440
  let nestedRouteIndex;
441
+ const reconciledRoutes = new Map();
436
442
  const resolveNestedRoute = (rootRunId) => {
437
443
  if (!includeNested)
438
444
  return undefined;
@@ -505,11 +511,13 @@ export function listAsyncRuns(asyncDirRoot, options = {}, observeStatus) {
505
511
  catch (error) {
506
512
  observeStatus?.(null);
507
513
  nestedWarnings.push(`Nested status unavailable: ${getErrorMessage(error)}`);
514
+ // Children that failed to reconcile are not projected.
515
+ nestedRoute = undefined;
508
516
  }
509
517
  }
510
518
  let summary;
511
519
  try {
512
- summary = statusToSummary(asyncDir, status, nestedWarnings, nestedRoute);
520
+ summary = statusToSummary(asyncDir, status, nestedWarnings);
513
521
  }
514
522
  catch (error) {
515
523
  observeStatus?.(null);
@@ -519,9 +527,16 @@ export function listAsyncRuns(asyncDirRoot, options = {}, observeStatus) {
519
527
  continue;
520
528
  }
521
529
  runs.push(summary);
530
+ if (nestedRoute)
531
+ reconciledRoutes.set(summary, nestedRoute);
522
532
  }
523
533
  const sorted = sortRuns(runs);
524
- return options.limit !== undefined ? sorted.slice(0, options.limit) : sorted;
534
+ const listed = options.limit !== undefined ? sorted.slice(0, options.limit) : sorted;
535
+ // Project nested children only for the runs returned. A non-reconciling read
536
+ // (FleetView polls one) looks up each run's own route-index directory.
537
+ if (includeNested)
538
+ attachNestedChildren(listed, options.reconcile === false ? undefined : (run) => reconciledRoutes.get(run));
539
+ return listed;
525
540
  }
526
541
  function formatActivityFacts(input) {
527
542
  const facts = [];
@@ -69,7 +69,7 @@ function boundedTaskSummary(value) {
69
69
  : normalized;
70
70
  }
71
71
  export function listRetainedChildren(asyncDirRoot, sessionId) {
72
- const children = listAsyncRuns(asyncDirRoot, { sessionId, states: ["complete", "failed", "paused", "stopped"], entryLimit: MAX_RETAINED_CHILD_CANDIDATES, reconcile: false })
72
+ const children = listAsyncRuns(asyncDirRoot, { sessionId, states: ["complete", "failed", "paused", "stopped"], entryLimit: MAX_RETAINED_CHILD_CANDIDATES, reconcile: false, includeNested: false })
73
73
  .flatMap((run) => {
74
74
  if (!run.parentWorkflowRunId || run.steps.length !== 1)
75
75
  return [];
@@ -248,8 +248,8 @@ function isCompleteUsageCounter(value) {
248
248
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
249
249
  }
250
250
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
251
- const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
252
- const REMAINING_TIMEOUT_MS = Symbol("remainingTimeoutMs");
251
+ // Kept off the result so the object returned in tool details stays plain JSON.
252
+ const attemptRecoveryState = new WeakMap();
253
253
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
254
254
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
255
255
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
@@ -1480,9 +1480,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1480
1480
  result.exitCode = exitCode;
1481
1481
  result.providerDiagnostics = clearProviderRetry(result.providerDiagnostics);
1482
1482
  progress.providerDiagnostics = result.providerDiagnostics;
1483
- if (afterCompactionSettlement)
1484
- result[AFTER_COMPACTION_SETTLEMENT] = true;
1485
- result[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
1483
+ attemptRecoveryState.set(result, { afterCompactionSettlement, remainingTimeoutMs });
1486
1484
  if (interruptedByControl) {
1487
1485
  result.exitCode = 0;
1488
1486
  result.interrupted = true;
@@ -1955,12 +1953,12 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1955
1953
  structuredOutputFailed: attemptResult.structuredOutputFailed,
1956
1954
  acceptanceFailed: false,
1957
1955
  currentTool: attemptResult.progress?.currentTool,
1958
- afterCompactionSettlement: attemptResult[AFTER_COMPACTION_SETTLEMENT],
1956
+ afterCompactionSettlement: attemptRecoveryState.get(attemptResult)?.afterCompactionSettlement,
1959
1957
  });
1960
1958
  if (recovery.action === "resume") {
1961
1959
  recoveryPrompt = recovery.prompt;
1962
1960
  // The retry gets the budget the first attempt left, so that attempt's supervisor waits stay uncounted.
1963
- const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
1961
+ const remainingMs = attemptRecoveryState.get(attemptResult)?.remainingTimeoutMs;
1964
1962
  if (remainingMs !== undefined)
1965
1963
  attemptOptions.deadlineAt = Date.now() + remainingMs;
1966
1964
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
@@ -79,7 +79,7 @@ export interface SubagentParamsLike {
79
79
  /** Internal workflow ownership metadata; not part of the public schema. */
80
80
  workflowParentRunId?: string;
81
81
  workflowKey?: string;
82
- /** Workflow child's `runs.run` label, trimmed; names the child's own session instead of a task excerpt. */
82
+ /** Top-level `label` or a workflow child's `runs.run` label; names the child's own session instead of a task excerpt. */
83
83
  label?: string;
84
84
  lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
85
85
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
- import { discoverAgents, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext } from "../../agents/agents.js";
4
+ import { agentRunDescription, discoverAgents, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext } from "../../agents/agents.js";
5
5
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir, missingForkCopyNote } from "../../shared/artifacts.js";
6
- import { writeAtomicJson } from "../../shared/atomic-json.js";
6
+ import { createAtomicJsonWriter, writeAtomicJson } from "../../shared/atomic-json.js";
7
7
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.js";
8
+ import { isRetryableFileSystemError, isStorageCapacityError } from "../../shared/file-system-retry.js";
8
9
  import { reportSessionWarning } from "../../shared/session-warnings.js";
9
10
  import { resolveEffectiveThinking, toModelInfo } from "../../shared/model-info.js";
10
11
  import { beginForegroundChild, finishForegroundChild, foregroundSchedulingSettled, settleForegroundSchedulingOwner, updateForegroundChild, } from "./foreground-control.js";
@@ -117,7 +118,7 @@ import { agentDefinitionDigest, stableJsonDigest } from "../../shared/launch-con
117
118
  import { cleanupWorktrees, createWorktrees, preflightWorktreeSource, withWorktreeTransaction, diffWorktrees, formatWorktreeDiffSummary, } from "../shared/worktree.js";
118
119
  import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.js";
119
120
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.js";
120
- import { DIRS, DEFAULT_ARTIFACT_CONFIG, DEFAULT_MAX_OUTPUT, DEFAULT_FORK_PREAMBLE, SUBAGENT_ACTIONS, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, checkSubagentDepth, resolveChildMaxSubagentDepth, resolveCurrentMaxSubagentDepth, resolveMaxSubagentSpawnsPerRun, truncateOutput, wrapForkTask, } from "../../shared/types.js";
121
+ import { DIRS, DEFAULT_ARTIFACT_CONFIG, DEFAULT_MAX_OUTPUT, DEFAULT_FORK_PREAMBLE, SUBAGENT_ACTIONS, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, TASK_SUBAGENT_LIFECYCLE_EVENT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, checkSubagentDepth, resolveChildMaxSubagentDepth, resolveCurrentMaxSubagentDepth, resolveMaxSubagentSpawnsPerRun, truncateOutput, wrapForkTask, } from "../../shared/types.js";
121
122
  import { deriveChildSessionName } from "../../shared/child-session-name.js";
122
123
  import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.js";
123
124
  import { waitToolName } from "../../shared/wait-tool-name.js";
@@ -517,6 +518,21 @@ function rememberedForegroundChild(input, result, index, status, updatedAt) {
517
518
  ...(result.capabilityAudit ? { capabilityAudit: result.capabilityAudit } : {}),
518
519
  };
519
520
  }
521
+ function foregroundStatusInput(result) {
522
+ return omitUndefinedProperties({
523
+ exitCode: result.exitCode,
524
+ interrupted: result.interrupted,
525
+ detached: result.detached,
526
+ processSignal: result.processSignal,
527
+ timedOut: result.timedOut,
528
+ stopped: result.stopped,
529
+ turnBudgetExceeded: result.turnBudgetExceeded,
530
+ });
531
+ }
532
+ /** The execution outcome a finished attached run is saved with; a rejected acceptance does not change it. */
533
+ function foregroundExecutionStatus(result) {
534
+ return resolveSubagentResultStatus(foregroundStatusInput(result));
535
+ }
520
536
  function rememberForegroundRun(state, input) {
521
537
  state.foregroundRuns ??= new Map();
522
538
  const previous = state.foregroundRuns.get(input.runId);
@@ -528,15 +544,7 @@ function rememberForegroundRun(state, input) {
528
544
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
529
545
  updatedAt,
530
546
  children: input.results.map((result, index) => {
531
- const child = rememberedForegroundChild(input, result, index, resolveSubagentResultStatus(omitUndefinedProperties({
532
- exitCode: result.exitCode,
533
- interrupted: result.interrupted,
534
- detached: result.detached,
535
- processSignal: result.processSignal,
536
- timedOut: result.timedOut,
537
- stopped: result.stopped,
538
- turnBudgetExceeded: result.turnBudgetExceeded,
539
- })), updatedAt);
547
+ const child = rememberedForegroundChild(input, result, index, foregroundExecutionStatus(result), updatedAt);
540
548
  const recovered = previous?.children[index];
541
549
  return child.status === "detached" && recovered && recovered.status !== "detached" ? recovered : child;
542
550
  }),
@@ -797,6 +805,28 @@ function resolveResumeTarget(params, state, options = {}) {
797
805
  throw asyncError;
798
806
  throw new Error("Run not found. Provide id or runId.");
799
807
  }
808
+ function foregroundLifecycleStatus(status) {
809
+ if (status === "completed")
810
+ return "completed";
811
+ return status === "stopped" || status === "paused" ? "aborted" : "failed";
812
+ }
813
+ /** Never throws: a host listener or a stale extension runtime must not fail a child run. */
814
+ function emitForegroundLifecycle(pi, input) {
815
+ const payload = { id: input.runId, status: input.status, agent: input.agent, description: input.description, mode: "foreground" };
816
+ if (input.status !== "started")
817
+ payload.success = input.status === "completed";
818
+ if (input.parentWorkflowRunId)
819
+ payload.parentWorkflowRunId = input.parentWorkflowRunId;
820
+ if (input.workflowKey)
821
+ payload.workflowKey = input.workflowKey;
822
+ try {
823
+ pi.events.emit(TASK_SUBAGENT_LIFECYCLE_EVENT, payload);
824
+ }
825
+ catch (error) {
826
+ if (!isStaleExtensionContextError(error))
827
+ console.error("Failed to emit foreground lifecycle event:", error);
828
+ }
829
+ }
800
830
  function isStaleExtensionContextError(error) {
801
831
  if (!(error instanceof Error))
802
832
  return false;
@@ -1947,6 +1977,12 @@ async function resumeAsyncRun(input) {
1947
1977
  if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
1948
1978
  return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' uses launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
1949
1979
  }
1980
+ // A resume restores the launch's saved options, so the request-only disabled-feature check cannot see a
1981
+ // saved `share: true`. Refuse here, before capacity moves, instead of uploading the continued session later.
1982
+ const restoredShareDisabledBy = resolveDisabledFeatureSurface(input.deps.config).params.get("share");
1983
+ if (recoveryDescriptor?.share === true && restoredShareDisabledBy !== undefined) {
1984
+ return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' was launched with share enabled, which config ${restoredShareDisabledBy} now disables. Re-enable session sharing to resume it.` }], isError: true, details: { mode: "management", results: [] } };
1985
+ }
1950
1986
  const runId = randomUUID();
1951
1987
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1952
1988
  let activeAsyncCapacity;
@@ -2200,16 +2236,10 @@ function createForegroundControlNotifier(data, deps) {
2200
2236
  };
2201
2237
  }
2202
2238
  export function foregroundResultIntercomStatus(result) {
2203
- return resolveSubagentResultStatus(omitUndefinedProperties({
2204
- exitCode: result.exitCode,
2239
+ return resolveSubagentResultStatus({
2240
+ ...foregroundStatusInput(result),
2205
2241
  ...(result.acceptance?.status === "rejected" ? { success: false } : {}),
2206
- interrupted: result.interrupted,
2207
- detached: result.detached,
2208
- processSignal: result.processSignal,
2209
- timedOut: result.timedOut,
2210
- stopped: result.stopped,
2211
- turnBudgetExceeded: result.turnBudgetExceeded,
2212
- }));
2242
+ });
2213
2243
  }
2214
2244
  export function shouldSuppressRoutineResultIntercom(input) {
2215
2245
  return input.suppressRoutineResultIntercom === true
@@ -3139,6 +3169,10 @@ async function waitForWorkflowAsyncSingleResult(params, launchResult, options) {
3139
3169
  })).finally(stopListener.remove);
3140
3170
  return importWorkflowAwaitedChildResult(completed, { runId: options.runId, asyncDir, resultPath, task: options.task, parentWorkflowRunId: params.workflowParentRunId, details: launchResult.details, state: options.state, pi: options.pi });
3141
3171
  }
3172
+ /** Callers outside the tool schema can pass any value; only a non-blank string names a run. */
3173
+ function launchLabel(label) {
3174
+ return typeof label === "string" && label.trim() ? label.trim() : undefined;
3175
+ }
3142
3176
  async function runAsyncPath(data, deps) {
3143
3177
  const { params, effectiveCwd, agents, ctx, shareEnabled, sessionRoot, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, effectiveAsync, controlConfig, intercomBridge, nestedRoute, contextPolicy, unknownAgentDiagnosticContext, } = data;
3144
3178
  const hasChain = (params.chain?.length ?? 0) > 0;
@@ -3283,8 +3317,7 @@ async function runAsyncPath(data, deps) {
3283
3317
  runFanoutBudget: data.runFanoutBudget,
3284
3318
  parentWorkflowRunId: params.workflowParentRunId,
3285
3319
  workflowKey: params.workflowKey,
3286
- // Top-level calls pass unknown keys through; only a workflow child's label is normalized.
3287
- label: params.workflowParentRunId !== undefined ? params.label : undefined,
3320
+ label: launchLabel(params.label),
3288
3321
  lane: params.lane,
3289
3322
  workflowAwaitAsync: params.workflowAwaitAsync,
3290
3323
  }));
@@ -3393,6 +3426,10 @@ function appendWorkflowOutputWarning(text, warning) {
3393
3426
  return warning ? `${text}\n\n${warning}` : text;
3394
3427
  }
3395
3428
  const WORKFLOW_TRACE_ERROR_MAX_CHARS = 500;
3429
+ // How long an async workflow keeps retrying a status.json write that a file lock blocks.
3430
+ const WORKFLOW_STATUS_LOCK_RETRY_WINDOW_MS = 60_000;
3431
+ // Deferred retries make one quick attempt per tick instead of blocking the event loop on a lock.
3432
+ const writeAtomicJsonWithoutLockWaits = createAtomicJsonWriter({ retryRenameErrors: false });
3396
3433
  // Return, emits, console, and trace errors (which carry child text) have no size limit of their
3397
3434
  // own, so only they are cut; other host sections stay whole. The saved full result is uncut.
3398
3435
  function formatWorkflowResultText(input) {
@@ -3793,7 +3830,7 @@ async function runSinglePath(data, deps) {
3793
3830
  cwd: singleCwd,
3794
3831
  outputPath,
3795
3832
  rerun: { params: { ...params, task: authoredTask, async: params.async ?? false } },
3796
- description: foregroundControl.description,
3833
+ description: launchLabel(params.label) ?? foregroundControl.description,
3797
3834
  ...(modelOverride ? { model: modelOverride } : {}),
3798
3835
  ...(thinking ? { thinking } : {}),
3799
3836
  interrupt: () => {
@@ -3847,6 +3884,13 @@ async function runSinglePath(data, deps) {
3847
3884
  const detachedWorkflowChild = params.workflowAwaitDetached === true
3848
3885
  ? new Promise((resolve) => { resolveDetachedWorkflowChild = resolve; })
3849
3886
  : undefined;
3887
+ const lifecycleBase = {
3888
+ runId,
3889
+ agent: params.agent,
3890
+ description: agentRunDescription(params.agent, agents.find((candidate) => candidate.name === params.agent), launchLabel(params.label)),
3891
+ parentWorkflowRunId: params.workflowParentRunId ?? foregroundControl?.parentWorkflowRunId,
3892
+ workflowKey: params.workflowKey,
3893
+ };
3850
3894
  try {
3851
3895
  const childSessionFile = sessionFileForTask(params.agent, 0, modelOverride, modelOverrideFromParent, modelOrigin);
3852
3896
  rememberRunningForegroundRun({
@@ -3861,6 +3905,7 @@ async function runSinglePath(data, deps) {
3861
3905
  }),
3862
3906
  parentWorkflowRunId: params.workflowParentRunId ?? foregroundControl?.parentWorkflowRunId,
3863
3907
  });
3908
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: "started" });
3864
3909
  const launched = await runSync(ctx.cwd, agents, params.agent, task, compactOptional({
3865
3910
  machine: foregroundMachine,
3866
3911
  parentProviderRegistry: ctx.modelRegistry,
@@ -3882,7 +3927,7 @@ async function runSinglePath(data, deps) {
3882
3927
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3883
3928
  cwd: singleCwd,
3884
3929
  requestedCwd: data.requestedCwd,
3885
- label: params.workflowParentRunId !== undefined ? params.label : undefined,
3930
+ label: launchLabel(params.label),
3886
3931
  signal,
3887
3932
  abortedAsStopped: params.workflowParentRunId !== undefined,
3888
3933
  interruptSignal: interruptController.signal,
@@ -3939,6 +3984,8 @@ async function runSinglePath(data, deps) {
3939
3984
  resolveDetachedWorkflowChild(result);
3940
3985
  return;
3941
3986
  }
3987
+ // Same status updateRememberedForegroundChild saves and sends with subagent:foreground-complete.
3988
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: foregroundLifecycleStatus(foregroundResultIntercomStatus(result)) });
3942
3989
  try {
3943
3990
  if (worktreeSetup) {
3944
3991
  try {
@@ -4006,8 +4053,11 @@ async function runSinglePath(data, deps) {
4006
4053
  };
4007
4054
  }
4008
4055
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4056
+ if (!r.detached)
4057
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: foregroundLifecycleStatus(foregroundExecutionStatus(r)) });
4009
4058
  }
4010
4059
  catch (error) {
4060
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: "failed" });
4011
4061
  discardRunningRecord();
4012
4062
  await cleanupSingleWorktree();
4013
4063
  throw error;
@@ -5292,10 +5342,44 @@ export function createSubagentExecutor(deps) {
5292
5342
  };
5293
5343
  const pendingWorkflowChildAnnouncements = new Map();
5294
5344
  let announcePersistedWorkflowChildren = () => { };
5345
+ let statusPersistenceDegraded = false;
5346
+ let statusLockedSince;
5347
+ const reportStatusWriteFailure = (error) => {
5348
+ const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
5349
+ console.error(message, error);
5350
+ if (statusPersistenceDegraded)
5351
+ return;
5352
+ statusPersistenceDegraded = true;
5353
+ try {
5354
+ appendWorkflowEvent({ type: "subagent.workflow.status_write_failed", error: message });
5355
+ }
5356
+ catch (eventError) {
5357
+ console.error(`Failed to record degraded status persistence for '${statusPath}':`, eventError);
5358
+ }
5359
+ };
5360
+ // A Windows rename lock can outlast writeAtomicJson's own retries. Keep the newest
5361
+ // status for the writer's 1s retry so a terminal state still lands once the lock
5362
+ // clears, but only for WORKFLOW_STATUS_LOCK_RETRY_WINDOW_MS: a lock that never clears
5363
+ // must not keep the referenced retry timer, and with it the process, alive.
5364
+ const shouldDeferRunWrite = (error, filePath) => {
5365
+ if (isStorageCapacityError(error))
5366
+ return true;
5367
+ if (filePath !== statusPath || !isRetryableFileSystemError(error))
5368
+ return false;
5369
+ statusLockedSince ??= Date.now();
5370
+ if (Date.now() - statusLockedSince >= WORKFLOW_STATUS_LOCK_RETRY_WINDOW_MS)
5371
+ return false;
5372
+ if (!statusPersistenceDegraded)
5373
+ reportStatusWriteFailure(error);
5374
+ return true;
5375
+ };
5295
5376
  const runPersistence = createCapacityResilientJsonWriter({
5296
5377
  keepAlive: true,
5378
+ shouldDefer: shouldDeferRunWrite,
5297
5379
  onSuccess: (filePath, payload) => {
5298
5380
  if (filePath === statusPath) {
5381
+ statusPersistenceDegraded = false;
5382
+ statusLockedSince = undefined;
5299
5383
  announcePersistedWorkflowChildren();
5300
5384
  queueActiveRunIndex(payload);
5301
5385
  }
@@ -5311,17 +5395,19 @@ export function createSubagentExecutor(deps) {
5311
5395
  write: (filePath, payload) => filePath === resultPath
5312
5396
  ? writeAsyncResultFile(filePath, payload)
5313
5397
  : writeAtomicJson(filePath, payload),
5398
+ retryWrite: (filePath, payload) => filePath === resultPath
5399
+ ? writeAsyncResultFile(filePath, payload)
5400
+ : writeAtomicJsonWithoutLockWaits(filePath, payload),
5314
5401
  });
5315
5402
  let initialPersistenceComplete = false;
5316
5403
  let persistClosed = false;
5317
- let statusPersistenceDegraded = false;
5318
5404
  // Progress journalling runs from admit, launch, the launch and progress observers,
5319
5405
  // onTrace and onEmit -- all inside the promises a workflowScript awaits. Those
5320
5406
  // callers pass tolerateStatusWriteFailure so a transient lock on status.json cannot
5321
- // mark a finished child failed or abort its still-running siblings. Initial and
5322
- // terminal writes stay fail-fast on purpose: no child work is at risk by then, and
5323
- // silently dropping a terminal write would leave status.json and the active-run
5324
- // index pinned at "running" after the result already says complete.
5407
+ // mark a finished child failed or abort its still-running siblings. The initial
5408
+ // write stays fail-fast so a run without storage never starts. Teardown writes
5409
+ // tolerate failure too: they run in a detached promise, so a throw there would
5410
+ // crash the host. A locked status.json is retried by runPersistence instead.
5325
5411
  const persist = (options = {}) => {
5326
5412
  if (persistClosed)
5327
5413
  return;
@@ -5339,21 +5425,9 @@ export function createSubagentExecutor(deps) {
5339
5425
  else if (options.tolerateStatusWriteFailure) {
5340
5426
  try {
5341
5427
  runPersistence.write(statusPath, { ...status });
5342
- if (runPersistence.pendingCount() === 0)
5343
- statusPersistenceDegraded = false;
5344
5428
  }
5345
5429
  catch (error) {
5346
- const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
5347
- console.error(message, error);
5348
- if (!statusPersistenceDegraded) {
5349
- statusPersistenceDegraded = true;
5350
- try {
5351
- appendWorkflowEvent({ type: "subagent.workflow.status_write_failed", error: message });
5352
- }
5353
- catch (eventError) {
5354
- console.error(`Failed to record degraded status persistence for '${statusPath}':`, eventError);
5355
- }
5356
- }
5430
+ reportStatusWriteFailure(error);
5357
5431
  }
5358
5432
  }
5359
5433
  else {
@@ -5608,7 +5682,7 @@ export function createSubagentExecutor(deps) {
5608
5682
  }
5609
5683
  // Commit receipts while run status is still nonterminal. Result/index publication
5610
5684
  // can fail next; teardown must not publish the subsequently computed terminal status.
5611
- persist();
5685
+ persist({ tolerateStatusWriteFailure: true });
5612
5686
  };
5613
5687
  void Promise.resolve().then(async () => {
5614
5688
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
@@ -6121,7 +6195,7 @@ export function createSubagentExecutor(deps) {
6121
6195
  return;
6122
6196
  if (pendingResultPublication && !await pendingResultPublication)
6123
6197
  return;
6124
- persist();
6198
+ persist({ tolerateStatusWriteFailure: true });
6125
6199
  deps.refreshResultDelivery?.();
6126
6200
  persistClosed = true;
6127
6201
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(status.error ? { error: status.error } : {}) });
@@ -6186,7 +6260,7 @@ export function createSubagentExecutor(deps) {
6186
6260
  return;
6187
6261
  if (pendingResultPublication && !await pendingResultPublication)
6188
6262
  return;
6189
- persist();
6263
+ persist({ tolerateStatusWriteFailure: true });
6190
6264
  deps.refreshResultDelivery?.();
6191
6265
  persistClosed = true;
6192
6266
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
@@ -7471,7 +7545,8 @@ export function createSubagentExecutor(deps) {
7471
7545
  return runFanoutErrorResult(error, foregroundMode);
7472
7546
  return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
7473
7547
  }
7474
- const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(runId);
7548
+ // Key the route by the id status.json records, so status lookups find nested children.
7549
+ const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(effectiveAsync ? asyncRunId : runId);
7475
7550
  const artifactConfig = omitUndefinedProperties({
7476
7551
  ...DEFAULT_ARTIFACT_CONFIG,
7477
7552
  enabled: effectiveParams.artifacts !== false,
@@ -1,3 +1,4 @@
1
1
  import type { BeforeProviderRequestEvent, ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- export declare function rewriteFastModeProviderRequest(event: BeforeProviderRequestEvent): unknown;
2
+ import type { FastServiceTier } from "../../shared/types.ts";
3
+ export declare function rewriteFastModeProviderRequest(event: BeforeProviderRequestEvent, serviceTier: FastServiceTier): unknown;
3
4
  export default function registerSubagentFastModeExtension(pi: ExtensionAPI): void;
@@ -1,8 +1,10 @@
1
- export function rewriteFastModeProviderRequest(event) {
1
+ import { loadConfig } from "../../extension/config.js";
2
+ export function rewriteFastModeProviderRequest(event, serviceTier) {
2
3
  if (!event.payload || typeof event.payload !== "object" || Array.isArray(event.payload))
3
4
  return event.payload;
4
- return { ...event.payload, service_tier: "priority" };
5
+ return { ...event.payload, service_tier: serviceTier };
5
6
  }
6
7
  export default function registerSubagentFastModeExtension(pi) {
7
- pi.on("before_provider_request", rewriteFastModeProviderRequest);
8
+ const serviceTier = loadConfig().fastServiceTier ?? "priority";
9
+ pi.on("before_provider_request", (event) => rewriteFastModeProviderRequest(event, serviceTier));
8
10
  }
@@ -5,12 +5,16 @@ type TimerApi = {
5
5
  export type CapacityResilientJsonWriterOptions = {
6
6
  /** It must be atomic for each target path. */
7
7
  write?: (filePath: string, payload: object) => void;
8
+ /** Replaces `write` for deferred retries, so a timer tick can skip blocking lock waits. */
9
+ retryWrite?: (filePath: string, payload: object) => void;
8
10
  /** Keep retry timers referenced by the event loop (needed by child runners). */
9
11
  keepAlive?: boolean;
10
12
  retryDelayMs?: number;
11
13
  timerApi?: TimerApi;
12
14
  onError?: (error: unknown, filePath: string) => void;
13
15
  onSuccess?: (filePath: string, payload: object) => void;
16
+ /** Decides which failures keep the newest payload for retry. Default: storage-capacity errors. */
17
+ shouldDefer?: (error: unknown, filePath: string) => boolean;
14
18
  };
15
19
  export type CapacityResilientJsonWriter = {
16
20
  write(filePath: string, payload: object, writeOperation?: (filePath: string, payload: object) => void): void;
@@ -18,9 +22,9 @@ export type CapacityResilientJsonWriter = {
18
22
  dispose(): void;
19
23
  };
20
24
  /**
21
- * Defers only storage-capacity failures, retaining the newest payload per path.
22
- * Initial/ordinary writes remain synchronous and preserve their throwing contract;
23
- * only ENOSPC-like failures enter the guarded retry loop.
25
+ * Defers storage-capacity failures (or those `shouldDefer` accepts), retaining the
26
+ * newest payload per path. Initial/ordinary writes remain synchronous and preserve
27
+ * their throwing contract; only deferred failures enter the guarded retry loop.
24
28
  */
25
29
  export declare function createCapacityResilientJsonWriter(options?: CapacityResilientJsonWriterOptions): CapacityResilientJsonWriter;
26
30
  export {};
@@ -5,17 +5,19 @@ const defaultTimerApi = {
5
5
  clearTimeout: (handle) => clearTimeout(handle),
6
6
  };
7
7
  /**
8
- * Defers only storage-capacity failures, retaining the newest payload per path.
9
- * Initial/ordinary writes remain synchronous and preserve their throwing contract;
10
- * only ENOSPC-like failures enter the guarded retry loop.
8
+ * Defers storage-capacity failures (or those `shouldDefer` accepts), retaining the
9
+ * newest payload per path. Initial/ordinary writes remain synchronous and preserve
10
+ * their throwing contract; only deferred failures enter the guarded retry loop.
11
11
  */
12
12
  export function createCapacityResilientJsonWriter(options = {}) {
13
13
  const defaultWrite = options.write ?? writeAtomicJson;
14
+ const retryWrite = options.retryWrite ?? defaultWrite;
14
15
  const keepAlive = options.keepAlive ?? false;
15
16
  const retryDelayMs = options.retryDelayMs ?? 1_000;
16
17
  const timerApi = options.timerApi ?? defaultTimerApi;
17
18
  const onError = options.onError ?? ((error, filePath) => console.error(`Failed to persist JSON '${filePath}':`, error));
18
19
  const onSuccess = options.onSuccess;
20
+ const shouldDefer = options.shouldDefer ?? isStorageCapacityError;
19
21
  const reportError = (error, filePath) => {
20
22
  try {
21
23
  onError(error, filePath);
@@ -48,7 +50,7 @@ export function createCapacityResilientJsonWriter(options = {}) {
48
50
  notifySuccess(filePath, entry.payload);
49
51
  }
50
52
  catch (error) {
51
- if (isStorageCapacityError(error))
53
+ if (shouldDefer(error, filePath))
52
54
  continue;
53
55
  pending.delete(filePath);
54
56
  reportError(error, filePath);
@@ -69,9 +71,9 @@ export function createCapacityResilientJsonWriter(options = {}) {
69
71
  notifySuccess(filePath, payload);
70
72
  }
71
73
  catch (error) {
72
- if (!isStorageCapacityError(error))
74
+ if (!shouldDefer(error, filePath))
73
75
  throw error;
74
- pending.set(filePath, { payload, write: writeOperation });
76
+ pending.set(filePath, { payload, write: writeOperation === defaultWrite ? retryWrite : writeOperation });
75
77
  scheduleRetry();
76
78
  }
77
79
  },
@@ -62,6 +62,10 @@ export declare const SUBAGENT_FEATURES: {
62
62
  readonly actions: readonly [];
63
63
  readonly params: readonly ["machine"];
64
64
  };
65
+ readonly "session-sharing": {
66
+ readonly actions: readonly [];
67
+ readonly params: readonly ["share"];
68
+ };
65
69
  readonly "workflow-scripts": {
66
70
  readonly actions: readonly ["validate"];
67
71
  readonly params: readonly ["workflow", "args", "preflight", "globalConcurrencyLimit", "maxSubagentSpawnsPerRun"];
@@ -35,6 +35,7 @@ export const SUBAGENT_FEATURES = {
35
35
  "control-overrides": { actions: [], params: ["control"] },
36
36
  "extension-bindings": { actions: [], params: ["extensionBindings"] },
37
37
  "external-machines": { actions: [], params: ["machine"] },
38
+ "session-sharing": { actions: [], params: ["share"] },
38
39
  "workflow-scripts": { actions: ["validate"], params: ["workflow", "args", "preflight", "globalConcurrencyLimit", "maxSubagentSpawnsPerRun"] },
39
40
  };
40
41
  const SCHEDULE_SURFACE = {