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
@@ -3,7 +3,7 @@ import {
3
3
  projectRuntimeAcknowledgedExtensions,
4
4
  registerSubagentPromptBoundary,
5
5
  registerSubagentPromptRuntime
6
- } from "./chunk-DYBRIEIF.js";
6
+ } from "./chunk-EBGTTJKP.js";
7
7
  import {
8
8
  INSPECTOR_ACTIONS,
9
9
  canQueueRetainedAsyncFollowUp,
@@ -25,12 +25,12 @@ import {
25
25
  updateSteeringTarget,
26
26
  waitForSteeringAction,
27
27
  workflowAsyncChildSteeringGuidance
28
- } from "./chunk-RHKIP45B.js";
28
+ } from "./chunk-DNJ2GHSI.js";
29
29
  import {
30
30
  PLACED_RESTORE_UNSUPPORTED,
31
31
  formatHerdrMachineRunnerUnsupported,
32
32
  resolveMachinePlacement
33
- } from "./chunk-TXC7WIPL.js";
33
+ } from "./chunk-C45WQQZX.js";
34
34
  import {
35
35
  COMPLETION_ACTION,
36
36
  DEFAULT_CONTROL_CONFIG,
@@ -77,6 +77,7 @@ import {
77
77
  incrementalChildCompletionTriggersTurn,
78
78
  isOrdinaryToolForMidToolExit,
79
79
  isScheduledRunAction,
80
+ isUnsetPlaceholder,
80
81
  isWorkflowScriptPath,
81
82
  listRetainedChildren,
82
83
  manualWorkflowResumeRefusalText,
@@ -119,7 +120,7 @@ import {
119
120
  workflowScriptDigest,
120
121
  workflowStopCause,
121
122
  writeWorkflowReceipt
122
- } from "./chunk-KA4MKMYT.js";
123
+ } from "./chunk-WHHRG32M.js";
123
124
  import {
124
125
  SUBAGENT_PARENT_SESSION_ENV,
125
126
  applyWatchdogLaunchRules,
@@ -132,7 +133,7 @@ import {
132
133
  resolveWatchdogConfig,
133
134
  sendRuleViolationWarning,
134
135
  writeWatchdogModelSettings
135
- } from "./chunk-2UCFLUE4.js";
136
+ } from "./chunk-RIBMW6V3.js";
136
137
  import {
137
138
  MAX_REMEMBERED_FOREGROUND_RUNS,
138
139
  discardRunningForegroundRun,
@@ -145,7 +146,7 @@ import {
145
146
  resolveSubagentRunId,
146
147
  resolveWorkflowChatProgress,
147
148
  stopAsyncRun
148
- } from "./chunk-464OJSDP.js";
149
+ } from "./chunk-XIQKWTFY.js";
149
150
  import {
150
151
  RunFanoutLimitError,
151
152
  annotateWorkflowPreflightTrace,
@@ -209,12 +210,12 @@ import {
209
210
  writeRunFanoutBudgetDescriptor,
210
211
  writeWorkflowLaunchRecord,
211
212
  writeWorktreeSetupHandoff
212
- } from "./chunk-U753SUBC.js";
213
+ } from "./chunk-2LEBXCLU.js";
213
214
  import {
214
215
  NATIVE_SUPERVISOR_TOOL_NAME,
215
216
  createNativeSupervisorChannel,
216
217
  resolveSupervisorChannelDir
217
- } from "./chunk-VEEUXJDO.js";
218
+ } from "./chunk-PTN7XAXI.js";
218
219
  import {
219
220
  MODEL_ONLY_TOOL,
220
221
  inheritedSessionIds,
@@ -231,16 +232,16 @@ import {
231
232
  resolveStructuredWorkflowResource,
232
233
  resolveWorkflowResource,
233
234
  validateWorkflowChildPermitRoot
234
- } from "./chunk-W2BZS6UC.js";
235
+ } from "./chunk-VMJGZHUL.js";
235
236
  import {
236
237
  buildEffectiveSystemPrompt,
237
238
  canPreferFork,
238
239
  createForkContextResolver,
239
240
  resolveSubagentLaunchContext
240
- } from "./chunk-ROJH7KPK.js";
241
+ } from "./chunk-PSB3VLMH.js";
241
242
  import {
242
243
  handleRefinementAction
243
- } from "./chunk-Q4VH72JI.js";
244
+ } from "./chunk-KNVQTRSY.js";
244
245
  import {
245
246
  ActiveAsyncCapacityError,
246
247
  acquireActiveAsyncCapacity,
@@ -256,7 +257,7 @@ import {
256
257
  resolveDisabledFeatureSurface,
257
258
  resolveMaxActiveAsyncRunsPerSession,
258
259
  transferActiveAsyncCapacity
259
- } from "./chunk-4KQW5R6U.js";
260
+ } from "./chunk-XYIVVS3A.js";
260
261
  import {
261
262
  DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS,
262
263
  MACHINE_DIFF_OPTIONS,
@@ -344,7 +345,7 @@ import {
344
345
  writeNestedControlRequest,
345
346
  writeNestedControlResult,
346
347
  writeNestedEvent
347
- } from "./chunk-DHY5TY2Y.js";
348
+ } from "./chunk-SIB2GQHL.js";
348
349
  import {
349
350
  closeSteerInbox,
350
351
  consumeSteerRequests,
@@ -352,7 +353,7 @@ import {
352
353
  readRevivalBriefs,
353
354
  requestAsyncSteer,
354
355
  watchAsyncControlInbox
355
- } from "./chunk-UUW7P6KJ.js";
356
+ } from "./chunk-37EJGDYO.js";
356
357
  import "./chunk-NIXWDZZV.js";
357
358
  import {
358
359
  INTERCOM_BRIDGE_MARKER,
@@ -361,7 +362,7 @@ import {
361
362
  resolveIntercomBridge,
362
363
  resolveIntercomSessionTarget,
363
364
  resolveSubagentIntercomTarget
364
- } from "./chunk-YJIU5WF4.js";
365
+ } from "./chunk-CPWZN5KM.js";
365
366
  import {
366
367
  agentDefinitionDigest,
367
368
  resolveLaunchBinding,
@@ -376,7 +377,7 @@ import {
376
377
  resolvePiLaunchToolPlan,
377
378
  resolveRuntimeModulePath,
378
379
  supervisorChannelDir
379
- } from "./chunk-AHGJSJYY.js";
380
+ } from "./chunk-YVDKGAEO.js";
380
381
  import {
381
382
  assertRequiredChildExtensionsAdmitted,
382
383
  createRequiredChildExtensionIdentity,
@@ -388,7 +389,7 @@ import {
388
389
  import {
389
390
  HERDR_PROJECT_PANE_ACTIONS,
390
391
  handleHerdrProjectPaneAction
391
- } from "./chunk-JEYG7CNC.js";
392
+ } from "./chunk-UC22RDXP.js";
392
393
  import "./chunk-72334PEI.js";
393
394
  import {
394
395
  PROJECT_SUBAGENTS_RELATIVE_DIR,
@@ -402,12 +403,12 @@ import {
402
403
  missingForkCopyNote,
403
404
  writeArtifact,
404
405
  writeMetadata
405
- } from "./chunk-77VQEATI.js";
406
+ } from "./chunk-5J2RTMKW.js";
406
407
  import "./chunk-XA3DY6UG.js";
407
408
  import {
408
409
  getExternalJobProvider
409
410
  } from "./chunk-YYREO77V.js";
410
- import "./chunk-SWGB2P5J.js";
411
+ import "./chunk-7Y4IJMCW.js";
411
412
  import {
412
413
  ChainOutputValidationError,
413
414
  DEFAULT_WAIT_TOOL_NAME,
@@ -427,6 +428,7 @@ import {
427
428
  acceptChildWatchdogEvent,
428
429
  acceptanceFailureMessage,
429
430
  acceptanceHasTypedVerify,
431
+ agentRunDescription,
430
432
  applyChildWatchdogMessage,
431
433
  assertClaudeCodeModelScope,
432
434
  assertJsonSchemaObject,
@@ -492,6 +494,7 @@ import {
492
494
  isDynamicRunnerGroup,
493
495
  isParallelGroup,
494
496
  isParallelStep,
497
+ isRetryableFileSystemError,
495
498
  isSettlementFatalOutputError,
496
499
  isStorageCapacityError,
497
500
  isToolBudgetBlockedMessage,
@@ -561,7 +564,7 @@ import {
561
564
  writeAtomicJson,
562
565
  writeInitialProgressFile,
563
566
  writePrivateAtomicJson
564
- } from "./chunk-LWH7IGI3.js";
567
+ } from "./chunk-F4NSLXB2.js";
565
568
  import {
566
569
  CHAIN_RUNS_DIR,
567
570
  DEFAULT_ARTIFACT_CONFIG,
@@ -579,6 +582,7 @@ import {
579
582
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
580
583
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
581
584
  SUBAGENT_PROCESS_TERMINAL_EVENT,
585
+ TASK_SUBAGENT_LIFECYCLE_EVENT,
582
586
  TEMP_ROOT_DIR,
583
587
  checkSubagentDepth,
584
588
  getAsyncConfigPath,
@@ -590,7 +594,7 @@ import {
590
594
  resolveMaxSubagentSpawnsPerSession,
591
595
  truncateOutput,
592
596
  wrapForkTask
593
- } from "./chunk-JEZOSEWG.js";
597
+ } from "./chunk-SRWJIAIP.js";
594
598
  import {
595
599
  safeTerminalText,
596
600
  sanitizeDisplayText
@@ -614,11 +618,13 @@ var defaultTimerApi = {
614
618
  };
615
619
  function createCapacityResilientJsonWriter(options = {}) {
616
620
  const defaultWrite = options.write ?? writeAtomicJson;
621
+ const retryWrite = options.retryWrite ?? defaultWrite;
617
622
  const keepAlive = options.keepAlive ?? false;
618
623
  const retryDelayMs = options.retryDelayMs ?? 1e3;
619
624
  const timerApi = options.timerApi ?? defaultTimerApi;
620
625
  const onError = options.onError ?? ((error, filePath) => console.error(`Failed to persist JSON '${filePath}':`, error));
621
626
  const onSuccess = options.onSuccess;
627
+ const shouldDefer = options.shouldDefer ?? isStorageCapacityError;
622
628
  const reportError = (error, filePath) => {
623
629
  try {
624
630
  onError(error, filePath);
@@ -646,7 +652,7 @@ function createCapacityResilientJsonWriter(options = {}) {
646
652
  pending.delete(filePath);
647
653
  notifySuccess(filePath, entry.payload);
648
654
  } catch (error) {
649
- if (isStorageCapacityError(error)) continue;
655
+ if (shouldDefer(error, filePath)) continue;
650
656
  pending.delete(filePath);
651
657
  reportError(error, filePath);
652
658
  }
@@ -664,8 +670,8 @@ function createCapacityResilientJsonWriter(options = {}) {
664
670
  pending.delete(filePath);
665
671
  notifySuccess(filePath, payload);
666
672
  } catch (error) {
667
- if (!isStorageCapacityError(error)) throw error;
668
- pending.set(filePath, { payload, write: writeOperation });
673
+ if (!shouldDefer(error, filePath)) throw error;
674
+ pending.set(filePath, { payload, write: writeOperation === defaultWrite ? retryWrite : writeOperation });
669
675
  scheduleRetry();
670
676
  }
671
677
  },
@@ -1084,12 +1090,13 @@ function registerFanoutChildSubagentExtension(pi, childConfig) {
1084
1090
  }
1085
1091
 
1086
1092
  // src/runs/shared/fast-mode-extension.ts
1087
- function rewriteFastModeProviderRequest(event) {
1093
+ function rewriteFastModeProviderRequest(event, serviceTier) {
1088
1094
  if (!event.payload || typeof event.payload !== "object" || Array.isArray(event.payload)) return event.payload;
1089
- return { ...event.payload, service_tier: "priority" };
1095
+ return { ...event.payload, service_tier: serviceTier };
1090
1096
  }
1091
1097
  function registerSubagentFastModeExtension(pi) {
1092
- pi.on("before_provider_request", rewriteFastModeProviderRequest);
1098
+ const serviceTier = loadConfig().fastServiceTier ?? "priority";
1099
+ pi.on("before_provider_request", (event) => rewriteFastModeProviderRequest(event, serviceTier));
1093
1100
  }
1094
1101
 
1095
1102
  // src/runs/shared/child-hooks.ts
@@ -2932,6 +2939,7 @@ function executeAsyncChain(id, params) {
2932
2939
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
2933
2940
  mode: resultMode,
2934
2941
  agent: firstAgents[0],
2942
+ description: agentRunDescription(firstAgents[0], agents.find((candidate) => candidate.name === firstAgents[0])),
2935
2943
  agents: flatAgents,
2936
2944
  task: firstTask?.trim() ? PROMPT_REDACTED : void 0,
2937
2945
  goal: workflowGoal?.trim() ? PROMPT_REDACTED : void 0,
@@ -3525,6 +3533,7 @@ function executeAsyncSingle(id, params) {
3525
3533
  mode: "single",
3526
3534
  ...params.toolCallId ? { toolCallId: params.toolCallId } : {},
3527
3535
  agent,
3536
+ description: agentRunDescription(agent, agentConfig, params.label),
3528
3537
  task: task?.trim() ? PROMPT_REDACTED : void 0,
3529
3538
  goal: (params.goal ?? task).trim() ? PROMPT_REDACTED : void 0,
3530
3539
  cwd: runnerCwd,
@@ -3868,8 +3877,13 @@ function earlierTurnHasJsBlock(branch, callIndex) {
3868
3877
  }
3869
3878
  return false;
3870
3879
  }
3880
+ function hasOptionsScript(options) {
3881
+ if (typeof options !== "object" || options === null || Array.isArray(options)) return false;
3882
+ const script = options.script;
3883
+ return script !== void 0 && !isUnsetPlaceholder(script);
3884
+ }
3871
3885
  function scriptFromReply(content, earlierBlock) {
3872
- const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
3886
+ const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true") && !hasOptionsScript(block.arguments?.options)).length;
3873
3887
  if (replyCalls > 1) return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
3874
3888
  if (!content.some((block) => block.type === "text")) {
3875
3889
  if (earlierBlock()) return { error: "The assistant message that issued this call has no text. A ```js block is in an earlier message of this turn, but workflow: true reads only the message that issues the call. Pass that script's source as options: { script: \"...\" } in place of workflow: true, with the call's other fields unchanged, or write the block and the call in one message." };
@@ -5376,8 +5390,7 @@ function isCompleteUsageCounter(value) {
5376
5390
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
5377
5391
  }
5378
5392
  var STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
5379
- var AFTER_COMPACTION_SETTLEMENT = /* @__PURE__ */ Symbol("afterCompactionSettlement");
5380
- var REMAINING_TIMEOUT_MS = /* @__PURE__ */ Symbol("remainingTimeoutMs");
5393
+ var attemptRecoveryState = /* @__PURE__ */ new WeakMap();
5381
5394
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
5382
5395
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
5383
5396
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== void 0);
@@ -6432,8 +6445,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6432
6445
  result2.exitCode = exitCode;
6433
6446
  result2.providerDiagnostics = clearProviderRetry(result2.providerDiagnostics);
6434
6447
  progress.providerDiagnostics = result2.providerDiagnostics;
6435
- if (afterCompactionSettlement) result2[AFTER_COMPACTION_SETTLEMENT] = true;
6436
- result2[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
6448
+ attemptRecoveryState.set(result2, { afterCompactionSettlement, remainingTimeoutMs });
6437
6449
  if (interruptedByControl) {
6438
6450
  result2.exitCode = 0;
6439
6451
  result2.interrupted = true;
@@ -6887,11 +6899,11 @@ ${PROMPT_REDACTED}; live Prompt Audit only.
6887
6899
  structuredOutputFailed: attemptResult.structuredOutputFailed,
6888
6900
  acceptanceFailed: false,
6889
6901
  currentTool: attemptResult.progress?.currentTool,
6890
- afterCompactionSettlement: attemptResult[AFTER_COMPACTION_SETTLEMENT]
6902
+ afterCompactionSettlement: attemptRecoveryState.get(attemptResult)?.afterCompactionSettlement
6891
6903
  });
6892
6904
  if (recovery.action === "resume") {
6893
6905
  recoveryPrompt = recovery.prompt;
6894
- const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
6906
+ const remainingMs = attemptRecoveryState.get(attemptResult)?.remainingTimeoutMs;
6895
6907
  if (remainingMs !== void 0) attemptOptions.deadlineAt = Date.now() + remainingMs;
6896
6908
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
6897
6909
  continue;
@@ -10266,6 +10278,20 @@ function rememberedForegroundChild(input, result2, index, status, updatedAt) {
10266
10278
  ...result2.capabilityAudit ? { capabilityAudit: result2.capabilityAudit } : {}
10267
10279
  };
10268
10280
  }
10281
+ function foregroundStatusInput(result2) {
10282
+ return omitUndefinedProperties({
10283
+ exitCode: result2.exitCode,
10284
+ interrupted: result2.interrupted,
10285
+ detached: result2.detached,
10286
+ processSignal: result2.processSignal,
10287
+ timedOut: result2.timedOut,
10288
+ stopped: result2.stopped,
10289
+ turnBudgetExceeded: result2.turnBudgetExceeded
10290
+ });
10291
+ }
10292
+ function foregroundExecutionStatus(result2) {
10293
+ return resolveSubagentResultStatus(foregroundStatusInput(result2));
10294
+ }
10269
10295
  function rememberForegroundRun(state, input) {
10270
10296
  state.foregroundRuns ??= /* @__PURE__ */ new Map();
10271
10297
  const previous = state.foregroundRuns.get(input.runId);
@@ -10277,15 +10303,7 @@ function rememberForegroundRun(state, input) {
10277
10303
  ...input.sessionId ? { sessionId: input.sessionId } : {},
10278
10304
  updatedAt,
10279
10305
  children: input.results.map((result2, index) => {
10280
- const child = rememberedForegroundChild(input, result2, index, resolveSubagentResultStatus(omitUndefinedProperties({
10281
- exitCode: result2.exitCode,
10282
- interrupted: result2.interrupted,
10283
- detached: result2.detached,
10284
- processSignal: result2.processSignal,
10285
- timedOut: result2.timedOut,
10286
- stopped: result2.stopped,
10287
- turnBudgetExceeded: result2.turnBudgetExceeded
10288
- })), updatedAt);
10306
+ const child = rememberedForegroundChild(input, result2, index, foregroundExecutionStatus(result2), updatedAt);
10289
10307
  const recovered = previous?.children[index];
10290
10308
  return child.status === "detached" && recovered && recovered.status !== "detached" ? recovered : child;
10291
10309
  })
@@ -10510,6 +10528,21 @@ function resolveResumeTarget(params, state, options = {}) {
10510
10528
  if (asyncError) throw asyncError;
10511
10529
  throw new Error("Run not found. Provide id or runId.");
10512
10530
  }
10531
+ function foregroundLifecycleStatus(status) {
10532
+ if (status === "completed") return "completed";
10533
+ return status === "stopped" || status === "paused" ? "aborted" : "failed";
10534
+ }
10535
+ function emitForegroundLifecycle(pi, input) {
10536
+ const payload = { id: input.runId, status: input.status, agent: input.agent, description: input.description, mode: "foreground" };
10537
+ if (input.status !== "started") payload.success = input.status === "completed";
10538
+ if (input.parentWorkflowRunId) payload.parentWorkflowRunId = input.parentWorkflowRunId;
10539
+ if (input.workflowKey) payload.workflowKey = input.workflowKey;
10540
+ try {
10541
+ pi.events.emit(TASK_SUBAGENT_LIFECYCLE_EVENT, payload);
10542
+ } catch (error) {
10543
+ if (!isStaleExtensionContextError2(error)) console.error("Failed to emit foreground lifecycle event:", error);
10544
+ }
10545
+ }
10513
10546
  function isStaleExtensionContextError2(error) {
10514
10547
  if (!(error instanceof Error)) return false;
10515
10548
  return /extension ctx is stale|stale after session replacement or reload/i.test(error.message);
@@ -11518,6 +11551,10 @@ async function resumeAsyncRun(input) {
11518
11551
  if (agentConfig.launcher !== void 0 && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
11519
11552
  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: [] } };
11520
11553
  }
11554
+ const restoredShareDisabledBy = resolveDisabledFeatureSurface(input.deps.config).params.get("share");
11555
+ if (recoveryDescriptor?.share === true && restoredShareDisabledBy !== void 0) {
11556
+ 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: [] } };
11557
+ }
11521
11558
  const runId = randomUUID5();
11522
11559
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
11523
11560
  let activeAsyncCapacity;
@@ -11755,16 +11792,10 @@ function createForegroundControlNotifier(data, deps) {
11755
11792
  };
11756
11793
  }
11757
11794
  function foregroundResultIntercomStatus(result2) {
11758
- return resolveSubagentResultStatus(omitUndefinedProperties({
11759
- exitCode: result2.exitCode,
11760
- ...result2.acceptance?.status === "rejected" ? { success: false } : {},
11761
- interrupted: result2.interrupted,
11762
- detached: result2.detached,
11763
- processSignal: result2.processSignal,
11764
- timedOut: result2.timedOut,
11765
- stopped: result2.stopped,
11766
- turnBudgetExceeded: result2.turnBudgetExceeded
11767
- }));
11795
+ return resolveSubagentResultStatus({
11796
+ ...foregroundStatusInput(result2),
11797
+ ...result2.acceptance?.status === "rejected" ? { success: false } : {}
11798
+ });
11768
11799
  }
11769
11800
  function shouldSuppressRoutineResultIntercom(input) {
11770
11801
  return input.suppressRoutineResultIntercom === true && input.results.length > 0 && input.results.every((result2) => foregroundResultIntercomStatus(result2) === "completed");
@@ -12584,6 +12615,9 @@ async function waitForWorkflowAsyncSingleResult(params, launchResult, options) {
12584
12615
  })).finally(stopListener.remove);
12585
12616
  return importWorkflowAwaitedChildResult(completed, { runId: options.runId, asyncDir, resultPath, task: options.task, parentWorkflowRunId: params.workflowParentRunId, details: launchResult.details, state: options.state, pi: options.pi });
12586
12617
  }
12618
+ function launchLabel(label) {
12619
+ return typeof label === "string" && label.trim() ? label.trim() : void 0;
12620
+ }
12587
12621
  async function runAsyncPath(data, deps) {
12588
12622
  const {
12589
12623
  params,
@@ -12739,8 +12773,7 @@ async function runAsyncPath(data, deps) {
12739
12773
  runFanoutBudget: data.runFanoutBudget,
12740
12774
  parentWorkflowRunId: params.workflowParentRunId,
12741
12775
  workflowKey: params.workflowKey,
12742
- // Top-level calls pass unknown keys through; only a workflow child's label is normalized.
12743
- label: params.workflowParentRunId !== void 0 ? params.label : void 0,
12776
+ label: launchLabel(params.label),
12744
12777
  lane: params.lane,
12745
12778
  workflowAwaitAsync: params.workflowAwaitAsync
12746
12779
  }));
@@ -12833,6 +12866,8 @@ function appendWorkflowOutputWarning(text, warning) {
12833
12866
  ${warning}` : text;
12834
12867
  }
12835
12868
  var WORKFLOW_TRACE_ERROR_MAX_CHARS = 500;
12869
+ var WORKFLOW_STATUS_LOCK_RETRY_WINDOW_MS = 6e4;
12870
+ var writeAtomicJsonWithoutLockWaits = createAtomicJsonWriter({ retryRenameErrors: false });
12836
12871
  function formatWorkflowResultText(input) {
12837
12872
  const traceSection = (error) => input.trace.length > 0 ? [`Call trace:
12838
12873
  ${input.trace.map((entry) => `${entry.line}${entry.error ? ` \u2014 ${error(entry.error)}` : ""}`).join("\n")}`] : [];
@@ -13247,7 +13282,7 @@ async function runSinglePath(data, deps) {
13247
13282
  cwd: singleCwd,
13248
13283
  outputPath,
13249
13284
  rerun: { params: { ...params, task: authoredTask, async: params.async ?? false } },
13250
- description: foregroundControl.description,
13285
+ description: launchLabel(params.label) ?? foregroundControl.description,
13251
13286
  ...modelOverride ? { model: modelOverride } : {},
13252
13287
  ...thinking ? { thinking } : {},
13253
13288
  interrupt: () => {
@@ -13291,6 +13326,13 @@ async function runSinglePath(data, deps) {
13291
13326
  const detachedWorkflowChild = params.workflowAwaitDetached === true ? new Promise((resolve9) => {
13292
13327
  resolveDetachedWorkflowChild = resolve9;
13293
13328
  }) : void 0;
13329
+ const lifecycleBase = {
13330
+ runId,
13331
+ agent: params.agent,
13332
+ description: agentRunDescription(params.agent, agents.find((candidate) => candidate.name === params.agent), launchLabel(params.label)),
13333
+ parentWorkflowRunId: params.workflowParentRunId ?? foregroundControl?.parentWorkflowRunId,
13334
+ workflowKey: params.workflowKey
13335
+ };
13294
13336
  try {
13295
13337
  const childSessionFile = sessionFileForTask(params.agent, 0, modelOverride, modelOverrideFromParent, modelOrigin);
13296
13338
  rememberRunningForegroundRun({
@@ -13314,6 +13356,7 @@ async function runSinglePath(data, deps) {
13314
13356
  }),
13315
13357
  parentWorkflowRunId: params.workflowParentRunId ?? foregroundControl?.parentWorkflowRunId
13316
13358
  });
13359
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: "started" });
13317
13360
  const launched = await runSync(ctx.cwd, agents, params.agent, task, compactOptional({
13318
13361
  machine: foregroundMachine,
13319
13362
  parentProviderRegistry: ctx.modelRegistry,
@@ -13334,7 +13377,7 @@ async function runSinglePath(data, deps) {
13334
13377
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
13335
13378
  cwd: singleCwd,
13336
13379
  requestedCwd: data.requestedCwd,
13337
- label: params.workflowParentRunId !== void 0 ? params.label : void 0,
13380
+ label: launchLabel(params.label),
13338
13381
  signal,
13339
13382
  abortedAsStopped: params.workflowParentRunId !== void 0,
13340
13383
  interruptSignal: interruptController.signal,
@@ -13390,6 +13433,7 @@ async function runSinglePath(data, deps) {
13390
13433
  resolveDetachedWorkflowChild(result2);
13391
13434
  return;
13392
13435
  }
13436
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: foregroundLifecycleStatus(foregroundResultIntercomStatus(result2)) });
13393
13437
  try {
13394
13438
  if (worktreeSetup) {
13395
13439
  try {
@@ -13445,7 +13489,9 @@ async function runSinglePath(data, deps) {
13445
13489
  };
13446
13490
  }
13447
13491
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
13492
+ if (!r.detached) emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: foregroundLifecycleStatus(foregroundExecutionStatus(r)) });
13448
13493
  } catch (error) {
13494
+ emitForegroundLifecycle(deps.pi, { ...lifecycleBase, status: "failed" });
13449
13495
  discardRunningRecord();
13450
13496
  await cleanupSingleWorktree();
13451
13497
  throw error;
@@ -14511,10 +14557,34 @@ Parent action: ${STATUS_ACTION}`,
14511
14557
  const pendingWorkflowChildAnnouncements = /* @__PURE__ */ new Map();
14512
14558
  let announcePersistedWorkflowChildren = () => {
14513
14559
  };
14560
+ let statusPersistenceDegraded = false;
14561
+ let statusLockedSince;
14562
+ const reportStatusWriteFailure = (error) => {
14563
+ const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
14564
+ console.error(message, error);
14565
+ if (statusPersistenceDegraded) return;
14566
+ statusPersistenceDegraded = true;
14567
+ try {
14568
+ appendWorkflowEvent({ type: "subagent.workflow.status_write_failed", error: message });
14569
+ } catch (eventError) {
14570
+ console.error(`Failed to record degraded status persistence for '${statusPath}':`, eventError);
14571
+ }
14572
+ };
14573
+ const shouldDeferRunWrite = (error, filePath) => {
14574
+ if (isStorageCapacityError(error)) return true;
14575
+ if (filePath !== statusPath || !isRetryableFileSystemError(error)) return false;
14576
+ statusLockedSince ??= Date.now();
14577
+ if (Date.now() - statusLockedSince >= WORKFLOW_STATUS_LOCK_RETRY_WINDOW_MS) return false;
14578
+ if (!statusPersistenceDegraded) reportStatusWriteFailure(error);
14579
+ return true;
14580
+ };
14514
14581
  const runPersistence = createCapacityResilientJsonWriter({
14515
14582
  keepAlive: true,
14583
+ shouldDefer: shouldDeferRunWrite,
14516
14584
  onSuccess: (filePath, payload) => {
14517
14585
  if (filePath === statusPath) {
14586
+ statusPersistenceDegraded = false;
14587
+ statusLockedSince = void 0;
14518
14588
  announcePersistedWorkflowChildren();
14519
14589
  queueActiveRunIndex(payload);
14520
14590
  }
@@ -14524,11 +14594,11 @@ Parent action: ${STATUS_ACTION}`,
14524
14594
  if (filePath === resultPath) settleResultPublication?.(reportResultWriteFailure(error));
14525
14595
  else console.error(`Failed to persist async workflow state '${filePath}':`, error);
14526
14596
  },
14527
- write: (filePath, payload) => filePath === resultPath ? writeAsyncResultFile(filePath, payload) : writeAtomicJson(filePath, payload)
14597
+ write: (filePath, payload) => filePath === resultPath ? writeAsyncResultFile(filePath, payload) : writeAtomicJson(filePath, payload),
14598
+ retryWrite: (filePath, payload) => filePath === resultPath ? writeAsyncResultFile(filePath, payload) : writeAtomicJsonWithoutLockWaits(filePath, payload)
14528
14599
  });
14529
14600
  let initialPersistenceComplete = false;
14530
14601
  let persistClosed = false;
14531
- let statusPersistenceDegraded = false;
14532
14602
  const persist = (options = {}) => {
14533
14603
  if (persistClosed) return;
14534
14604
  const liveJob = deps2.state.asyncJobs.get(workflowRunId);
@@ -14543,18 +14613,8 @@ Parent action: ${STATUS_ACTION}`,
14543
14613
  } else if (options.tolerateStatusWriteFailure) {
14544
14614
  try {
14545
14615
  runPersistence.write(statusPath, { ...status });
14546
- if (runPersistence.pendingCount() === 0) statusPersistenceDegraded = false;
14547
14616
  } catch (error) {
14548
- const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
14549
- console.error(message, error);
14550
- if (!statusPersistenceDegraded) {
14551
- statusPersistenceDegraded = true;
14552
- try {
14553
- appendWorkflowEvent({ type: "subagent.workflow.status_write_failed", error: message });
14554
- } catch (eventError) {
14555
- console.error(`Failed to record degraded status persistence for '${statusPath}':`, eventError);
14556
- }
14557
- }
14617
+ reportStatusWriteFailure(error);
14558
14618
  }
14559
14619
  } else {
14560
14620
  runPersistence.write(statusPath, { ...status });
@@ -14773,7 +14833,7 @@ Parent action: ${STATUS_ACTION}`,
14773
14833
  } catch (error) {
14774
14834
  appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase: "close", error: error instanceof Error ? error.message : String(error) });
14775
14835
  }
14776
- persist();
14836
+ persist({ tolerateStatusWriteFailure: true });
14777
14837
  };
14778
14838
  void Promise.resolve().then(async () => {
14779
14839
  const workflowDeadlineAt2 = timeout === void 0 ? void 0 : Date.now() + timeout;
@@ -15205,7 +15265,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15205
15265
  }
15206
15266
  if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflowResultChildren2(workflow.children, status, false), workflow: status.workflow, ...workflowCapabilityCeiling2 ? { admissionCapabilityCeiling: workflowCapabilityCeiling2 } : {}, ...workflowReceipt ? { workflowReceipt } : {}, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
15207
15267
  if (pendingResultPublication && !await pendingResultPublication) return;
15208
- persist();
15268
+ persist({ tolerateStatusWriteFailure: true });
15209
15269
  deps2.refreshResultDelivery?.();
15210
15270
  persistClosed = true;
15211
15271
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}, ...status.error ? { error: status.error } : {} });
@@ -15256,7 +15316,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15256
15316
  }
15257
15317
  if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? void 0 : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...terminalOutcome ? { terminalOutcome } : {}, results: workflowResultChildren2(partial.children, status, true), workflow: status.workflow, ...workflowCapabilityCeiling2 ? { admissionCapabilityCeiling: workflowCapabilityCeiling2 } : {}, ...workflowReceipt ? { workflowReceipt } : {}, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
15258
15318
  if (pendingResultPublication && !await pendingResultPublication) return;
15259
- persist();
15319
+ persist({ tolerateStatusWriteFailure: true });
15260
15320
  deps2.refreshResultDelivery?.();
15261
15321
  persistClosed = true;
15262
15322
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}, ...terminalOutcome ? { terminalOutcome } : {}, ...status.error ? { error: status.error } : {}, ...status.activityState ? { activityState: status.activityState } : {} });
@@ -16420,7 +16480,7 @@ ${item.text}` } : item)
16420
16480
  if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
16421
16481
  return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
16422
16482
  }
16423
- const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(runId);
16483
+ const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(effectiveAsync ? asyncRunId : runId);
16424
16484
  const artifactConfig = omitUndefinedProperties({
16425
16485
  ...DEFAULT_ARTIFACT_CONFIG,
16426
16486
  enabled: effectiveParams.artifacts !== false,
@@ -5,7 +5,7 @@ import {
5
5
  getProjectConfigDir,
6
6
  resolveLocalLaunchCwd,
7
7
  resolveRexLocalPlacement
8
- } from "./chunk-LWH7IGI3.js";
8
+ } from "./chunk-F4NSLXB2.js";
9
9
 
10
10
  // src/runs/shared/herdr-machine.ts
11
11
  import { spawnSync as spawnSync2 } from "node:child_process";
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7F6RKT6W.js";
4
4
  import {
5
5
  getAgentDir
6
- } from "./chunk-LWH7IGI3.js";
6
+ } from "./chunk-F4NSLXB2.js";
7
7
 
8
8
  // src/intercom/intercom-bridge.ts
9
9
  import * as fs from "node:fs";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  isTrustedRecordedSessionFile,
3
3
  resolveSubagentRunId
4
- } from "./chunk-464OJSDP.js";
4
+ } from "./chunk-XIQKWTFY.js";
5
5
  import {
6
6
  agentStreamOptions,
7
7
  opencodeSessionHeaders,
8
8
  resolveAsyncResumeTarget
9
- } from "./chunk-U753SUBC.js";
9
+ } from "./chunk-2LEBXCLU.js";
10
10
  import {
11
11
  ownsRun
12
12
  } from "./chunk-HXRB42AF.js";
@@ -18,12 +18,12 @@ import {
18
18
  reconcileAsyncRun,
19
19
  resolveAuthorityDecision,
20
20
  resolveMissionStoreLocation
21
- } from "./chunk-DHY5TY2Y.js";
21
+ } from "./chunk-SIB2GQHL.js";
22
22
  import {
23
23
  deliverInterruptRequest,
24
24
  queueRevivalBrief,
25
25
  requestAsyncSteer
26
- } from "./chunk-UUW7P6KJ.js";
26
+ } from "./chunk-37EJGDYO.js";
27
27
  import {
28
28
  formatShellCommand
29
29
  } from "./chunk-72334PEI.js";
@@ -34,10 +34,10 @@ import {
34
34
  tryLease,
35
35
  writeAtomicJson,
36
36
  writePrivateAtomicJson
37
- } from "./chunk-LWH7IGI3.js";
37
+ } from "./chunk-F4NSLXB2.js";
38
38
  import {
39
39
  DIRS
40
- } from "./chunk-JEZOSEWG.js";
40
+ } from "./chunk-SRWJIAIP.js";
41
41
  import {
42
42
  previewDisplayText,
43
43
  safeTerminalText