pi-subagents 0.64.0 → 0.65.1

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 (106) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +2 -2
  3. package/agents/reviewer.md +1 -1
  4. package/agents/scout.md +1 -1
  5. package/docs/agents.md +19 -17
  6. package/docs/configuration.md +23 -15
  7. package/docs/extension-api.md +18 -6
  8. package/docs/missions.md +2 -0
  9. package/docs/observability.md +10 -12
  10. package/docs/tool-reference.md +15 -8
  11. package/docs/watchdog.md +1 -1
  12. package/docs/workflows.md +13 -3
  13. package/package.json +5 -4
  14. package/runner-server-preload.mjs +13 -0
  15. package/skills/pi-subagents/SKILL.md +2 -1
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  17. package/skills/pi-subagents/references/execution-controls.md +7 -3
  18. package/skills/pi-subagents/references/multi-lane-orchestration.md +2 -0
  19. package/src/agents/agent-management.ts +47 -15
  20. package/src/api/capability-ceiling.ts +0 -1
  21. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  22. package/src/api/preflight.ts +7 -4
  23. package/src/extension/config.ts +4 -2
  24. package/src/extension/doctor.ts +2 -10
  25. package/src/extension/fanout-child.ts +9 -11
  26. package/src/extension/index.ts +58 -7
  27. package/src/extension/public-execution.ts +14 -0
  28. package/src/extension/rpc.ts +3 -2
  29. package/src/extension/schemas.ts +3 -2
  30. package/src/extension/tool-description.ts +13 -8
  31. package/src/integrations/pi-web-session-liveness.ts +73 -0
  32. package/src/intercom/native-supervisor-channel.ts +159 -95
  33. package/src/intercom/supervisor-ui.ts +244 -0
  34. package/src/missions/workflow-state.ts +37 -16
  35. package/src/runs/background/async-execution.ts +51 -25
  36. package/src/runs/background/async-job-tracker.ts +11 -0
  37. package/src/runs/background/async-resume.ts +14 -3
  38. package/src/runs/background/async-retention.ts +9 -0
  39. package/src/runs/background/control-channel.ts +2 -204
  40. package/src/runs/background/notify.ts +2 -0
  41. package/src/runs/background/process-terminal.ts +1 -1
  42. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  43. package/src/runs/background/run-child-session.ts +614 -0
  44. package/src/runs/background/run-status.ts +0 -1
  45. package/src/runs/background/runner-aliases.ts +152 -0
  46. package/src/runs/background/runner-child-sessions.ts +31 -0
  47. package/src/runs/background/scheduled-runs.ts +18 -4
  48. package/src/runs/background/subagent-runner.ts +203 -901
  49. package/src/runs/foreground/async-steering-action.ts +1 -17
  50. package/src/runs/foreground/execution.ts +204 -378
  51. package/src/runs/foreground/foreground-control.ts +4 -0
  52. package/src/runs/foreground/foreground-history.ts +3 -1
  53. package/src/runs/foreground/prompt-audit.ts +9 -5
  54. package/src/runs/foreground/subagent-executor.ts +161 -91
  55. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  56. package/src/runs/shared/abort-recovery.ts +3 -3
  57. package/src/runs/shared/acceptance.ts +14 -1
  58. package/src/runs/shared/capability-ceiling.ts +1 -2
  59. package/src/runs/shared/child-hooks.ts +25 -0
  60. package/src/runs/shared/child-identity.ts +13 -2
  61. package/src/runs/shared/child-launch.ts +314 -0
  62. package/src/runs/shared/child-lifecycle.ts +25 -0
  63. package/src/runs/shared/child-runtime-config.ts +126 -0
  64. package/src/runs/shared/child-session.ts +337 -0
  65. package/src/runs/shared/child-tool-plan.ts +530 -0
  66. package/src/runs/shared/claude-code-adapter.ts +5 -1
  67. package/src/runs/shared/completion-guard.ts +1 -1
  68. package/src/runs/shared/external-cli-preflight.ts +16 -0
  69. package/src/runs/shared/llm-intent-arbiter.ts +20 -11
  70. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -4
  71. package/src/runs/shared/model-exclusions.ts +84 -15
  72. package/src/runs/shared/model-fallback.ts +78 -6
  73. package/src/runs/shared/nested-events.ts +32 -48
  74. package/src/runs/shared/nested-path.ts +0 -14
  75. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  76. package/src/runs/shared/parallel-utils.ts +1 -2
  77. package/src/runs/shared/permissions.ts +0 -13
  78. package/src/runs/shared/process-signal.ts +4 -1
  79. package/src/runs/shared/run-fanout-budget.ts +0 -13
  80. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  81. package/src/runs/shared/structured-output.ts +17 -4
  82. package/src/runs/shared/subagent-control.ts +2 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +87 -384
  84. package/src/runs/shared/tool-availability.ts +18 -62
  85. package/src/runs/shared/tool-budget.ts +0 -14
  86. package/src/runs/shared/worktree-cleanup-plan.ts +31 -9
  87. package/src/runs/shared/worktree.ts +192 -40
  88. package/src/shared/child-session-name.ts +1 -1
  89. package/src/shared/jsonl-writer.ts +11 -0
  90. package/src/shared/model-response-aliases.ts +13 -0
  91. package/src/shared/thinking-ceiling.ts +0 -6
  92. package/src/shared/types.ts +63 -28
  93. package/src/shared/utils.ts +6 -4
  94. package/src/shared/watch-strategy.ts +2 -0
  95. package/src/slash/slash-commands.ts +0 -6
  96. package/src/tui/fleet-status.ts +1 -1
  97. package/src/tui/fleet.ts +0 -1
  98. package/src/tui/render.ts +254 -41
  99. package/src/watchdog/child-status.ts +0 -1
  100. package/src/watchdog/register-child.ts +12 -12
  101. package/src/workflows/scripted-workflow.ts +80 -7
  102. package/src/workflows/workflow-checklist.ts +4 -3
  103. package/src/runs/shared/child-protocol.ts +0 -415
  104. package/src/runs/shared/pi-args.ts +0 -1059
  105. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  106. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -46,7 +46,16 @@ import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template
46
46
  import { registerMainWatchdog } from "../watchdog/register-main.ts";
47
47
  import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
48
48
  import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
49
+ import {
50
+ renderSupervisorReply,
51
+ renderSupervisorRequest,
52
+ SUPERVISOR_REPLY_ENTRY_TYPE,
53
+ SUPERVISOR_REQUEST_MESSAGE_TYPE,
54
+ type SupervisorRequestMessageDetails,
55
+ } from "../intercom/supervisor-ui.ts";
49
56
  import { registerHerdrStatusBridge, type HerdrStatusRun } from "../integrations/herdr-status.ts";
57
+ import { hasLiveSubagentWork, registerPiWebSessionLiveness } from "../integrations/pi-web-session-liveness.ts";
58
+ import { createRetainedNestedRouteTracker } from "../runs/background/retained-nested-route-tracker.ts";
50
59
  import { listHerdrProjectPaneRoots, restoreHerdrProjectPaneSnapshots } from "../inspectors/herdr/project-panes.ts";
51
60
  import { registerSubagentRpcBridge } from "./rpc.ts";
52
61
  import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "../slash/slash-live-state.ts";
@@ -56,7 +65,8 @@ import { createWaitSubscriptionManager } from "../runs/background/wait-subscript
56
65
  import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
57
66
  import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
58
67
  import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
59
- import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/pi-args.ts";
68
+ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.ts";
69
+ import { disposeChildSessions } from "../runs/shared/child-session.ts";
60
70
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
61
71
  import { formatDuration, shortenPath } from "../shared/formatters.ts";
62
72
  import { applyModelExclusionsConfig, loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
@@ -484,6 +494,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
484
494
  const mainWatchdog = registerMainWatchdog(pi);
485
495
  const resultDeliveryOwnership = createResultDeliveryOwnership(state);
486
496
  const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
497
+ let retainedNestedRouteTracker: ReturnType<typeof createRetainedNestedRouteTracker> | undefined;
487
498
  const fleetStatus = fleetViewEnabled
488
499
  ? new SubagentFleetStatus(state, async (itemKey) => {
489
500
  const ctx = withLastUiContext((current) => current);
@@ -502,6 +513,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
502
513
  let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
503
514
  let goalTurnId = 0;
504
515
  let parentSessionEnvValue: string | null = null;
516
+ let releaseHostSessionLiveness = () => {};
505
517
  const scheduledStoreRoot = config.scheduledRuns?.storeRoot === undefined ? undefined : resolveScheduledStoreRoot(config.scheduledRuns.storeRoot);
506
518
  const scheduledRunManager = createScheduledRunManager({
507
519
  config,
@@ -546,6 +558,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
546
558
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
547
559
  widgetEnabled: asyncWidgetEnabled,
548
560
  onJobTerminal: () => refreshResultDelivery(),
561
+ supervisorRequestState: supervisorChannel.getSupervisorRequestState,
549
562
  });
550
563
  const resultWatcher = createResultWatcher(
551
564
  pi,
@@ -583,7 +596,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
583
596
  }, ASYNC_RETENTION_DELAY_MS);
584
597
  asyncRetentionTimer.unref?.();
585
598
 
586
- const executor = createSubagentExecutor({
599
+ const executorDeps: Parameters<typeof createSubagentExecutor>[0] = {
587
600
  pi,
588
601
  state,
589
602
  config,
@@ -598,9 +611,19 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
598
611
  discoverAgents: discoverAgentsForRuntime,
599
612
  activateSupervisorTransport: () => supervisorChannel.activateTransport(),
600
613
  refreshResultDelivery: () => refreshResultDelivery(),
601
- });
614
+ trackRetainedNestedRoute: undefined,
615
+ };
616
+ const executor = createSubagentExecutor(executorDeps);
602
617
  executorScheduled = executor.executeScheduled;
603
618
 
619
+ pi.registerMessageRenderer<SupervisorRequestMessageDetails>(SUPERVISOR_REQUEST_MESSAGE_TYPE, renderSupervisorRequest);
620
+ const registerEntryRenderer = (pi as unknown as {
621
+ registerEntryRenderer?: (customType: string, renderer: (entry: { data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
622
+ }).registerEntryRenderer;
623
+ if (typeof registerEntryRenderer === "function") {
624
+ registerEntryRenderer.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, renderSupervisorReply);
625
+ }
626
+
604
627
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
605
628
  const details = resolveSlashMessageDetails(message.details);
606
629
  if (!details) return undefined;
@@ -906,10 +929,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
906
929
  const projectPaneOwnerRoot = path.resolve(ctx.cwd);
907
930
  restoreHerdrProjectPaneSnapshots(state, [...new Set([...(state.herdrProjectPanes?.keys() ?? []), ...listHerdrProjectPaneRoots(projectPaneOwnerRoot), projectPaneOwnerRoot])]);
908
931
  // Set PI_SUBAGENT_PARENT_SESSION for permission-system forwarding.
909
- // Only set in the root session (the interactive UI session), not in
910
- // child subagent processes — children inherit the parent's value
911
- // through the process environment at spawn time and must not overwrite
912
- // it with their own session identity.
932
+ // Only set in the root session (the interactive UI session), not in a
933
+ // child host: the runner process inherits the parent's value through
934
+ // its environment at spawn time and must not overwrite it with a child
935
+ // session's identity.
913
936
  if (!process.env[SUBAGENT_CHILD_ENV]) {
914
937
  const sessionId = ctx.sessionManager.getSessionId();
915
938
  if (sessionId) {
@@ -925,6 +948,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
925
948
  cleanupSessionArtifacts(ctx);
926
949
  logSlowPhase("session-artifact-cleanup", phaseStartedAt);
927
950
  state.foregroundControls.clear();
951
+ retainedNestedRouteTracker?.clear();
952
+ retainedNestedRouteTracker = undefined;
953
+ executorDeps.trackRetainedNestedRoute = undefined;
928
954
  state.lastForegroundControlId = null;
929
955
  phaseStartedAt = Date.now();
930
956
  resetJobs(ctx);
@@ -961,6 +987,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
961
987
  if (runtimeCleaned) return;
962
988
  runtimeCleaned = true;
963
989
  const shuttingDownParentSession = parentSessionEnvValue;
990
+ releaseHostSessionLiveness();
991
+ releaseHostSessionLiveness = () => {};
964
992
  // Workflow continuations retain their launch context; abort them before
965
993
  // teardown so a reload cannot launch through a stale context.
966
994
  for (const controller of state.workflowControllers?.values() ?? []) {
@@ -984,6 +1012,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
984
1012
  for (const timer of state.cleanupTimers.values()) clearTimeout(timer);
985
1013
  state.cleanupTimers.clear();
986
1014
  state.asyncJobs.clear();
1015
+ retainedNestedRouteTracker?.clear();
1016
+ retainedNestedRouteTracker = undefined;
1017
+ executorDeps.trackRetainedNestedRoute = undefined;
987
1018
  for (const unsubscribe of eventUnsubscribes) {
988
1019
  try {
989
1020
  unsubscribe();
@@ -1077,6 +1108,21 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1077
1108
  installRuntime(ctx);
1078
1109
  const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
1079
1110
  resetSessionState(ctx, recovering, event.previousSessionFile);
1111
+ releaseHostSessionLiveness();
1112
+ const sessionId = ctx.sessionManager.getSessionId();
1113
+ const sessionFile = ctx.sessionManager.getSessionFile();
1114
+ const liveness = sessionId
1115
+ ? registerPiWebSessionLiveness({
1116
+ sessionId,
1117
+ ...(sessionFile ? { sessionFile } : {}),
1118
+ isActive: () => hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery(),
1119
+ })
1120
+ : { registered: false, release: () => {} };
1121
+ releaseHostSessionLiveness = liveness.release;
1122
+ if (liveness.registered) {
1123
+ retainedNestedRouteTracker = createRetainedNestedRouteTracker(state);
1124
+ executorDeps.trackRetainedNestedRoute = retainedNestedRouteTracker.track;
1125
+ }
1080
1126
  herdrStatusBridge.sessionStarted({
1081
1127
  hasUI: ctx.hasUI === true,
1082
1128
  runs: activeHerdrRuns(),
@@ -1088,6 +1134,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1088
1134
 
1089
1135
  pi.on("session_shutdown", async () => {
1090
1136
  runtimeEntry.cleanup();
1137
+ try {
1138
+ await disposeChildSessions();
1139
+ } catch (error) {
1140
+ console.error("Failed to dispose in-process child sessions:", error);
1141
+ }
1091
1142
  await herdrStatusBridge.flush();
1092
1143
  });
1093
1144
  }
@@ -1,3 +1,5 @@
1
+ import { normalizeWorktreeBaseRef } from "../runs/shared/worktree.ts";
2
+
1
3
  export interface PublicSubagentExecutionParams {
2
4
  action?: unknown;
3
5
  capabilities?: unknown;
@@ -28,6 +30,7 @@ export interface PublicSubagentExecutionParams {
28
30
  preflight?: unknown;
29
31
  isolation?: unknown;
30
32
  worktree?: unknown;
33
+ baseRef?: unknown;
31
34
  lane?: unknown;
32
35
  async?: unknown;
33
36
  output?: unknown;
@@ -69,6 +72,14 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
69
72
  return { ok: false, error: "Public execution does not accept workflow resource provenance or permit fields.", mode: params.action === undefined ? "workflow" : "management" };
70
73
  }
71
74
  }
75
+ if (params.baseRef !== undefined) {
76
+ if (typeof params.baseRef !== "string") return { ok: false, error: "baseRef must be a valid Git ref.", mode: params.action === undefined ? "workflow" : "management" };
77
+ try {
78
+ normalizeWorktreeBaseRef(params.baseRef);
79
+ } catch (error) {
80
+ return { ok: false, error: error instanceof Error ? error.message : String(error), mode: params.action === undefined ? "workflow" : "management" };
81
+ }
82
+ }
72
83
  if (params.workflowScript !== undefined && params.workflowScriptPath !== undefined) {
73
84
  return { ok: false, error: "workflowScript and workflowScriptPath are mutually exclusive.", mode: "workflow" };
74
85
  }
@@ -122,6 +133,9 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
122
133
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflowScript.", mode: "management" };
123
134
  }
124
135
  const normalizedAction = typeof action === "string" ? action.trim() : undefined;
136
+ if (params.baseRef !== undefined && normalizedAction !== undefined && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
137
+ return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
138
+ }
125
139
  if (normalizedAction !== undefined && hasNamedWorkflow) {
126
140
  return { ok: false, error: "Named workflow resource execution must omit action.", mode: "management" };
127
141
  }
@@ -24,7 +24,7 @@ import { readStatus } from "../shared/utils.ts";
24
24
  import { SubagentParams } from "./schemas.ts";
25
25
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
26
26
  import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
27
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
27
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
28
28
 
29
29
  export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
30
30
  export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
@@ -616,8 +616,8 @@ function stopAsyncRun(
616
616
  }
617
617
  }
618
618
  if (initialStatus.mode === "workflow" && initialStatus.state === "running") {
619
+ const stopChild = options.state?.workflowChildStops?.get(initialRunId);
619
620
  if (child) {
620
- const stopChild = options.state?.workflowChildStops?.get(initialRunId);
621
621
  if (stopChild) {
622
622
  if (!stopChild(child.id, `Workflow child '${child.id}' stopped by RPC.`)) throw new SubagentRpcError("invalid_state", `Child '${childId}' in workflow ${initialRunId} is not available to stop.`);
623
623
  emitChildStopping(initialRunId, location.asyncDir, child);
@@ -633,6 +633,7 @@ function stopAsyncRun(
633
633
  }
634
634
  const workflowController = options.state?.workflowControllers?.get(initialRunId);
635
635
  if (workflowController && !child) {
636
+ stopStoppableAsyncStatusChildren(initialStatus, stopChild, "Workflow stopped by RPC.");
636
637
  workflowController.abort(new Error("Workflow stopped by RPC."));
637
638
  return {
638
639
  runId: initialRunId,
@@ -343,7 +343,7 @@ const SubagentParamProperties = {
343
343
  })),
344
344
  workflow: Type.Optional(Type.String({ minLength: 1, description: "Extension-owned workflow resource; resolves its script and authority internally." })),
345
345
  args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; resource validation applies." })),
346
- workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Inline JavaScript statement body with unknown resource provenance. Normally async unless asyncByDefault:false; set async:true when async matters. Use async:false only when the parent must block until completion, never for reviews or gates. Use explicit return for output. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. Use await runs.run(key, {agent, task, worktree?, gate?}) or runs.run(key, {resume, task}), where resume is a retained run id or {workflowRunId,key,latest:true} from a durable async workflow receipt. Each workflow key identifies one result lane: use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected. Use runs.all([...]), runs.host(key,{kind:'command',command,timeoutMs,output?,role?,provider?}), await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}), runs.status(id), runs.ref(s), emit(value), console, and return. For bounded parallel sequential chains, use runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task},...]}]); first stages run together, later stages sequence per lane, and the bounded board reports lane-local failures. Only an explicit structuredOutput.verdict === 'blocked' blocks a successful stage; reviewer prose is not parsed. For ordinary parallel fanout, use await runs.all([{key, agent, task}, ...]); it resolves to an ordered array, not a key map, so use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout, and each must later be observed with direct await, Promise.race, or Promise.all. runs.steer targets a prior stable child key, never a raw run id, and must be awaited or returned. Mission workflows also have async state.get(key) and state.set(key, JSONValue). Compose sequential and parallel phases dynamically. Set worktree:true at workflow or child level for a separate managed worktree; child fields override workflow defaults. gate is one host-run command and cannot be combined with acceptance. runs.run accepts one child only. No filesystem, shell, Pi tools, or host globals except through runs.host." })),
346
+ workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Inline JavaScript statement body with unknown resource provenance. Normally async unless asyncByDefault:false; set async:true for async workflows and async:false only when the parent must block. Use explicit return, top-level await, plain helper functions, or explicit Promise chains. Nested async function, arrow, and method helpers are rejected. Globals: runs, emit, console, and mission state when enabled. No filesystem, shell, Pi tools, or host globals except through runs.host." })),
347
347
  workflowScriptPath: Type.Optional(Type.String({ minLength: 1, description: "Path to a JavaScript workflow file with unknown resource provenance. Mutually exclusive with workflowScript and workflow. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts." })),
348
348
  globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
349
349
  maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
@@ -351,6 +351,7 @@ const SubagentParamProperties = {
351
351
  chatProgress: Type.Optional(Type.String({ enum: ["auto", "off", "live-card"], description: "WorkflowScript chat progress projection. auto shows a live in-chat card only for watched foreground workflows in the same Git repository; it is off otherwise. Explicit live-card requires same-repository async:false; async workflows should omit chatProgress or use auto/off." })),
352
352
  isolation: Type.Optional(Type.String({ enum: ["none", "worktree"], description: "Workflow child isolation. none runs in the shared cwd; worktree requires managed git worktree isolation." })),
353
353
  worktree: Type.Optional(Type.Boolean({ description: "Managed child isolation. true gives each workflow child a separate git worktree; an individual runs.run/runs.all item can override a workflow default with worktree:false." })),
354
+ baseRef: Type.Optional(Type.String()),
354
355
  lane: Type.Optional(WorkflowLaneMetadata),
355
356
  context: Type.Optional(Type.String({
356
357
  enum: ["fresh", "fork", "profile"],
@@ -386,7 +387,7 @@ const SubagentParamProperties = {
386
387
  outputSchema: Type.Optional(JsonSchemaObject),
387
388
  agentContract: Type.Optional(AgentContractOverride),
388
389
  acceptance: Type.Optional(AcceptanceOverride),
389
- gate: Type.Optional(Type.String({ minLength: 1, description: "Host gate command. Cannot be combined with acceptance." })),
390
+ gate: Type.Optional(Type.String({ minLength: 1, description: "Host gate command. Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted." })),
390
391
  };
391
392
 
392
393
  const SubagentParamsSchema = Type.Object(SubagentParamProperties);
@@ -6,6 +6,8 @@ import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
6
6
  const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
7
7
  const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
8
8
  const EXTERNAL_CLI_RUNNER_GUIDANCE = "External CLI agents (codex-exec, codex-exec-writer, claude-code, claude-code-writer, cursor-agent, cursor-agent-writer) use their own runner contract and do not support native Pi child options such as model override, structured output, acceptance/agent contract, tool budget, fast mode, fork context, skills, or native Pi tools unless the runner explicitly implements them.";
9
+ const SUBAGENT_FAILURE_RECOVERY_GUIDANCE = "If a subagent workflow, child launch, prompt runtime, extension load, or child tooling setup fails, treat it as a lane infrastructure blocker—not permission to change execution mode. Stop and report the exact failure, run/status, and repo/cwd/worktree/branch/ref state; verify the worktree is clean or capture a partial diff before retrying or asking the owner. Retry or fix the subagent path only through a clear same-protocol retry. Do not silently switch to interactive_shell, pi -ne, Codex/Claude/Cursor CLI, a foreground agent, or another external mode. For backlog lanes and other subagent-governed workflows, external/foreground/CLI fallback requires explicit owner approval. Pi core may print a generic pi -ne extension-load hint; that out-of-repo hint is not protocol-approved fallback. interactive_shell remains valid when the user explicitly requests foreground/CLI work or the task is outside the governed subagent protocol.";
10
+ const AGENT_SELECTION_GUIDANCE = "Before execution, call { action: \"list\", capabilities: true } and run only executable, non-disabled agents; for external-cli rows, also require runner.available === true. This is a passive PATH/PATHEXT/X_OK lookup, not authentication, version, or launch proof; launch preflight remains authoritative.";
9
11
  const WORKFLOW_RESUME_KEY_GUIDANCE = "Each workflow key identifies one result lane: use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected.";
10
12
  const WORKFLOW_OUTPUT_BINDING_GUIDANCE = "For durable workflow child files, set output on runs.run/runs.all; task filename prose is not an output declaration, and return the child's outputReference, outputPathMapping, or artifactPaths instead of inventing a literal path.";
11
13
  const WORKFLOW_LANES_GUIDANCE = "For bounded parallel sequential chains, use runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task},...]}]); first stages run together, later stages sequence per lane, and the bounded board reports lane-local failures. Only an explicit structuredOutput.verdict === 'blocked' blocks a successful stage; reviewer prose is not parsed.";
@@ -13,12 +15,12 @@ const WORKFLOW_SCRIPT_PORTABILITY_GUIDANCE = "workflowScript rejects nested asyn
13
15
  const WORKFLOW_RESOURCE_GUIDANCE = "For permission/policy-extension interoperability, use an extension-owned named resource such as {workflow:'review',args:{task:'...'}} or {workflow:'run-ci',args:{command:'npm test'}}. The host resolves the script and authority internally so policy can distinguish it from raw workflowScript/workflowScriptPath; args are bounded plain data, and do not combine workflow with agent, task, workflowScript, or workflowScriptPath.";
14
16
  const WORKFLOW_HOST_GUIDANCE = "For permission-sensitive host calls, use an extension-owned resource such as {workflow:'run-ci',args:{command:'npm test'}}; raw workflowScript/workflowScriptPath have unknown resource provenance and cannot use runs.host. In a resource that grants it, await runs.host(key,{kind:'command',command,timeoutMs,output?,role?,provider?}). runs.host has no per-step cwd: commands and relative output paths use the workflow cwd; set cwd on the outer subagent request instead (for example, {cwd:'/path/to/worktree',workflowScript:'...'}), or put a trusted directory change in the command (for example, 'cd /path/to/worktree && npm test'). v1 supports only command steps; output is bounded and command failure fails the workflow.";
15
17
 
16
- export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child, workflowScript for inline orchestration, workflowScriptPath to load a script from the request cwd, or a named workflow resource for permission/policy-aware execution. ${WORKFLOW_RESOURCE_GUIDANCE} The script inputs are mutually exclusive. Use action:'validate' with either script input to check it without launching children. For multi-step or parallel work, make exactly one top-level subagent call with async:true; launch children only inside that workflow and do not make another top-level call for them. Use runs.run('key',{agent,task}) for one child, await runs.all([{key:'a',agent:'reviewer',task:'...'},{key:'b',agent:'reviewer',task:'...'}]) for ordinary parallel children, and read its ordered array result with indexes, destructuring, or .map(...), not by key property. ${WORKFLOW_SCRIPT_PORTABILITY_GUIDANCE} ${WORKFLOW_LANES_GUIDANCE} ${WORKFLOW_HOST_GUIDANCE} ${EXTERNAL_CLI_RUNNER_GUIDANCE} Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
18
+ export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child, workflowScript for inline orchestration, workflowScriptPath to load a script from the request cwd, or a named workflow resource for permission/policy-aware execution. ${WORKFLOW_RESOURCE_GUIDANCE} ${AGENT_SELECTION_GUIDANCE} The script inputs are mutually exclusive. Use action:'validate' with either script input to check it without launching children. For multi-step or parallel work, make exactly one top-level subagent call with async:true; launch children only inside that workflow and do not make another top-level call for them. Use runs.run('key',{agent,task}) for one child, await runs.all([{key:'a',agent:'reviewer',task:'...'},{key:'b',agent:'reviewer',task:'...'}]) for ordinary parallel children, and read its ordered array result with indexes, destructuring, or .map(...), not by key property. ${WORKFLOW_SCRIPT_PORTABILITY_GUIDANCE} ${WORKFLOW_LANES_GUIDANCE} ${WORKFLOW_HOST_GUIDANCE} ${EXTERNAL_CLI_RUNNER_GUIDANCE} ${SUBAGENT_FAILURE_RECOVERY_GUIDANCE} Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
17
19
 
18
20
  export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate to subagents; orchestrate in one workflowScript call.";
19
21
 
20
22
  export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
21
- 'Use subagent only when delegation is needed. Before execution, call { action: "list" } and run only executable, non-disabled agents.',
23
+ `Use subagent only when delegation is needed. ${AGENT_SELECTION_GUIDANCE}`,
22
24
  'Omit action for execution; use { agent, task? } for one child. For multi-step or parallel work, make exactly one top-level { workflowScript, async: true } call and launch children only inside it. Use action only for management/control.',
23
25
  "workflowScript rejects nested async function, arrow, and method helpers; use top-level await, plain helper functions, or explicit Promise chains.",
24
26
  "Inside workflowScript, use runs.run/runs.all and await their results. runs.all returns an ordered array, not a key map; stored runs.run promises must later be observed with direct await, Promise.race, or Promise.all.",
@@ -26,7 +28,8 @@ export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
26
28
  ];
27
29
 
28
30
  export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
29
- • Use { action: "list" } before execution and only run executable/non-disabled agents.
31
+ • ${AGENT_SELECTION_GUIDANCE}
32
+ • ${SUBAGENT_FAILURE_RECOVERY_GUIDANCE}
30
33
  • Keep execution and management separate: omit action for structured single-child or workflowScript execution; use action only for management/control.
31
34
  • Async/background runs are the normal default unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Use async:false only when the parent must block until completion. Async mode still shows progress. Final reviews and gate checks stay async; needing a result is not a blocking reason. After an async launch, continue independent work only until its next dependency barrier; consume the result before work that depends on it. Ordinary async subagents notify this session natively, so return control and do not call bg_wait merely to get a completion wake. Do not sleep or poll status just to wait; use bg_wait only for provider, detached, or other background work without a native notification when this turn must receive its result.
32
35
  • ${WORKFLOW_RESUME_KEY_GUIDANCE}
@@ -43,10 +46,10 @@ ${WORKFLOW_RESOURCE_GUIDANCE}
43
46
 
44
47
  EXECUTION:
45
48
  • ${EXTERNAL_CLI_RUNNER_GUIDANCE}
46
- • Before executing, use { action: "list" } and run only executable/non-disabled configured agents.
49
+ • ${AGENT_SELECTION_GUIDANCE}
47
50
  • When passing an explicit model to a child (on the call or a runs.run/runs.all item), first call { action: "models" } and copy an exact provider/id; bare ids resolve only when unique in the registry, and agent names (e.g. gpt-pro, advisor) are not model ids. Set per-run thinking with a suffix on the model string (e.g. provider/id:high; off/minimal/low/medium/high/xhigh/max); the suffix wins over the agent's thinking default. The thinking field only applies to action='watchdog.configure' and is ignored on dispatch.
48
51
  • SINGLE CHILD: { agent:"worker", task:"..." }. This structured form starts exactly one direct child. Fields such as model, context, cwd, worktree, output, budgets, acceptance, and async apply to that child. Do not combine agent/task with action, workflowScript, or workflowScriptPath.
49
- • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel children. runs.all resolves to an ordered array, not a key map, so use results[0], array destructuring, or results.map((result) => result.output), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. Ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Scripts normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Pass async:false only when the parent must block until completion, never for final reviews or gates. Same-repo blocking workflows default to a live in-chat card; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use {action:"children.list"} to list recent retained workflow children with resumable/not-resumable reasons. Resume only rows reported resumable. For a simple follow-up or implementation challenge, use {action:"resume", id:"run-id", message:"..."}. Resume keeps the stored agent/model/tool contract. If no resumable child is listed, launch a same-role fallback challenge and label it as fallback. Inside workflowScript, continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); workflow resumes wait for completed output, and loops must continue from each latest returned runId. Await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}) to guide a prior keyed child without exposing its run id; receipts are queued, delivered, missed, or failed. Always await or return runs.steer. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.steer, runs.status, runs.ref/refs, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
52
+ • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel children. runs.all resolves to an ordered array, not a key map, so use results[0], array destructuring, or results.map((result) => result.output), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. Ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Scripts normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Pass async:false only when the parent must block until completion, never for final reviews or gates. Same-repo blocking workflows default to a live in-chat card; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use {action:"children.list"} to list recent retained workflow children with resumable/not-resumable reasons. Resume only rows reported resumable. For a simple follow-up or implementation challenge, use {action:"resume", id:"run-id", message:"..."}. Resume keeps the stored agent/model/tool contract. If no resumable child is listed, launch a same-role fallback challenge and label it as fallback. Inside workflowScript, continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); workflow resumes wait for completed output, and loops must continue from each latest returned runId. Await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}) to guide a prior keyed child without exposing its run id; receipts are queued, delivered, missed, or failed. Always await or return runs.steer. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. Set baseRef to a safe Git ref (default HEAD) to choose the managed worktree starting commit; the source checkout must still be clean. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.steer, runs.status, runs.ref/refs, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
50
53
  • ${WORKFLOW_LANES_GUIDANCE}
51
54
  • FILE SCRIPT: { workflowScriptPath:"workflows/review.js" }. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts. Do not combine this field with workflowScript.
52
55
  • Sequential example: { workflowScript: "const a = await runs.run('analyze', {agent:'agent-a', task:'Analyze the request'}); return (await runs.run('plan', {agent:'agent-b', task:'Plan from: '+a.output})).output" }
@@ -57,7 +60,7 @@ EXECUTION:
57
60
  MANAGEMENT / CONTROL (use action; omit execution fields):
58
61
  • validate checks workflowScript or workflowScriptPath syntax and statically decidable structure without launching children. list, get, models, guide, children.list, create, update, delete, eject, disable, enable, reset, status, debug.run, doctor, grant-spawn-budget, worktree.discard, worktree.cleanup (plan-only), lane.status, lane.recordMerge, lane.recordSupersession, refine/refine.show/refine.rollback, mission.create/list/show/update/resolve-decision/attach-run/close, inspector.open/status/close, project.open/status/close, and watchdog actions remain available. Use {action:"guide", topic:"overview"} for packaged current-version help; topics are overview, workflows, agents, missions, observability, tool-reference, configuration, models, watchdog, and extension-api.
59
62
  • status, interrupt, stop, resume, and steer manage live or persisted runs. Use status view:"fleet" for an overview or view:"transcript" with id and optional index to tail output.
60
- • Create durable project schedules with { action:"schedule.create", id?, name?, sessionOnly?:true, at:"+10m" | ISO, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" }, or use workflowScriptPath instead. With sessionOnly:true, the schedule records the creating session file and only that session can restore or execute it; omitted/false preserves project-wide behavior. Manage them with schedule.list/show/history/pause/resume/run/run-due/delete. This first slice supports fixed intervals; calendar schedules and schedule mission attachment are deferred.
63
+ • Create durable project schedules with { action:"schedule.create", id?, name?, sessionOnly?:true, at:"+10m" | ISO, baseRef?, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" }, or use workflowScriptPath instead. An optional baseRef selects the safe Git ref used by managed worktrees (default HEAD); the source checkout must still be clean. With sessionOnly:true, the schedule records the creating session file and only that session can restore or execute it; omitted/false preserves project-wide behavior. Manage them with schedule.list/show/history/pause/resume/run/run-due/delete. This first slice supports fixed intervals; calendar schedules and schedule mission attachment are deferred.
61
64
 
62
65
  ${SUBAGENT_SAFETY_GUIDANCE}`;
63
66
 
@@ -67,10 +70,10 @@ ${WORKFLOW_RESOURCE_GUIDANCE}
67
70
 
68
71
  EXECUTE:
69
72
  • ${EXTERNAL_CLI_RUNNER_GUIDANCE}
70
- • Call { action:"list" } first and use only executable/non-disabled agents.
73
+ • ${AGENT_SELECTION_GUIDANCE}
71
74
  • Passing an explicit model? Call {action:"models"} first and copy an exact provider/id; bare ids resolve only when unique in the registry; agent names (e.g. gpt-pro, advisor) are not model ids. Per-run thinking is a suffix on the model string (provider/id:high; off/minimal/low/medium/high/xhigh/max), and the suffix wins over the agent's thinking default; the thinking field only applies to action='watchdog.configure' and is ignored on dispatch.
72
75
  • SINGLE {agent:"worker",task:"..."} starts exactly one direct child. Fields apply to that child. Do not combine agent/task with action, workflowScript, or workflowScriptPath.
73
- • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel work. runs.all resolves to an ordered array, not a key map; use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. Await runs.steer(key,message,options?) to guide a prior keyed child; it returns queued, delivered, missed, or failed and never accepts a raw run id. Always await or return steering calls. Use {action:"children.list"} for recent retained workflow children and resume only rows reported resumable. Use {action:"resume",id:"run-id",message:"..."} for a simple follow-up or challenge; resume keeps the stored agent/model/tool contract. If none is resumable, launch a same-role fallback challenge and label it as fallback. Inside workflowScript use runs.run(key,{resume:"run-id",task:"follow-up"}) when the script must wait for completion and continue from the latest returned runId. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation. Scripts normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. async:false blocks the parent until completion and auto-enables a same-repo live chat card unless chatProgress is off; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off.
76
+ • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel work. runs.all resolves to an ordered array, not a key map; use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. Await runs.steer(key,message,options?) to guide a prior keyed child; it returns queued, delivered, missed, or failed and never accepts a raw run id. Always await or return steering calls. Use {action:"children.list"} for recent retained workflow children and resume only rows reported resumable. Use {action:"resume",id:"run-id",message:"..."} for a simple follow-up or challenge; resume keeps the stored agent/model/tool contract. If none is resumable, launch a same-role fallback challenge and label it as fallback. Inside workflowScript use runs.run(key,{resume:"run-id",task:"follow-up"}) when the script must wait for completion and continue from the latest returned runId. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation; set baseRef to a safe Git ref (default HEAD) to choose the managed worktree starting commit. The source checkout must still be clean. Scripts normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. async:false blocks the parent until completion and auto-enables a same-repo live chat card unless chatProgress is off; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off.
74
77
  • ${WORKFLOW_LANES_GUIDANCE}
75
78
  • FILE SCRIPT {workflowScriptPath:"workflows/review.js"} loads the script on the host relative to the request cwd before sandbox execution. Do not combine it with workflowScript.
76
79
  • Example: {workflowScript:"const [a,b]=await runs.all([{key:'a',agent:'agent-a',task:'Implement A',worktree:true},{key:'b',agent:'agent-b',task:'Implement B',worktree:true}]); return [a.output,b.output]"}
@@ -81,6 +84,7 @@ MANAGE / CONTROL:
81
84
  • A mission object needs exactly one non-empty title or summary; objective and labels are optional. goal may only be true and requires budget:{tokens}.
82
85
 
83
86
  ASYNC / SAFETY:
87
+ • ${SUBAGENT_FAILURE_RECOVERY_GUIDANCE}
84
88
  • Omitted async follows asyncByDefault config; set async:true explicitly when async behavior matters. Continue independent work only until its next dependency barrier; consume the result before work that depends on it. Ordinary async subagents notify this session natively, so return control and do not call bg_wait merely to get a completion wake. Do not sleep or poll merely to wait; use bg_wait only for provider, detached, or other background work without a native notification when this turn must receive its result.
85
89
  • ${WORKFLOW_RESUME_KEY_GUIDANCE}
86
90
  • ${WORKFLOW_OUTPUT_BINDING_GUIDANCE}
@@ -196,6 +200,7 @@ function loadCustomToolDescription(options?: ToolDescriptionOptions): string | u
196
200
  function withMandatorySafetyGuidance(description: string): string {
197
201
  const customDescription = description
198
202
  .split(SUBAGENT_SAFETY_GUIDANCE)
203
+ .flatMap((part) => part.split(SUBAGENT_FAILURE_RECOVERY_GUIDANCE))
199
204
  .map((part) => part.trim())
200
205
  .filter(Boolean)
201
206
  .join("\n\n");
@@ -0,0 +1,73 @@
1
+ import { hasLiveNestedDescendants, projectNestedEvents } from "../runs/shared/nested-events.ts";
2
+ import type { NestedRouteInfo, SubagentState } from "../shared/types.ts";
3
+
4
+ export const PI_WEB_SESSION_LIVENESS_REGISTRY_KEY = "@agegr/pi-web/session-liveness/v1";
5
+ const PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION = 1;
6
+
7
+ interface PiWebSessionLivenessProvider {
8
+ name: string;
9
+ sessionId: string;
10
+ sessionFile?: string;
11
+ isActive(): boolean;
12
+ }
13
+
14
+ interface PiWebSessionLivenessRegistry {
15
+ version: typeof PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION;
16
+ register(provider: PiWebSessionLivenessProvider): () => void;
17
+ }
18
+
19
+ type SessionLivenessRegistration = Omit<PiWebSessionLivenessProvider, "name">;
20
+
21
+ export interface PiWebSessionLivenessHandle {
22
+ /** True only when the compatible host accepted the provider registration. */
23
+ registered: boolean;
24
+ release: () => void;
25
+ }
26
+
27
+ type LiveWorkState = Pick<SubagentState, "asyncJobs" | "foregroundControls" | "retainedForegroundNestedRoutes">;
28
+
29
+ function resolveRegistry(): PiWebSessionLivenessRegistry | null {
30
+ const value = (globalThis as Record<PropertyKey, unknown>)[Symbol.for(PI_WEB_SESSION_LIVENESS_REGISTRY_KEY)];
31
+ if (!value || typeof value !== "object") return null;
32
+ const registry = value as Partial<PiWebSessionLivenessRegistry>;
33
+ if (registry.version !== PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION || typeof registry.register !== "function") return null;
34
+ return registry as PiWebSessionLivenessRegistry;
35
+ }
36
+
37
+ export function retainLiveForegroundNestedRoute(state: Pick<SubagentState, "retainedForegroundNestedRoutes">, route: NestedRouteInfo): boolean {
38
+ const nested = projectNestedEvents(route);
39
+ if (!hasLiveNestedDescendants(nested.children)) return false;
40
+ state.retainedForegroundNestedRoutes ??= new Map();
41
+ state.retainedForegroundNestedRoutes.set(route.rootRunId, route);
42
+ return true;
43
+ }
44
+
45
+ export function hasLiveSubagentWork(state: LiveWorkState): boolean {
46
+ for (const job of state.asyncJobs.values()) {
47
+ if (job.status === "queued" || job.status === "running" || hasLiveNestedDescendants(job.nestedChildren)) return true;
48
+ }
49
+ for (const control of state.foregroundControls.values()) {
50
+ if ((control.schedulingOwners ?? 0) > 0
51
+ || (control.activeChildren?.size ?? 0) > 0
52
+ || hasLiveNestedDescendants(control.nestedChildren)) return true;
53
+ }
54
+ return (state.retainedForegroundNestedRoutes?.size ?? 0) > 0;
55
+ }
56
+
57
+ export function registerPiWebSessionLiveness(registration: SessionLivenessRegistration): PiWebSessionLivenessHandle {
58
+ const registry = resolveRegistry();
59
+ if (!registry) return { registered: false, release: () => {} };
60
+ try {
61
+ const release = registry.register({
62
+ name: "pi-subagents",
63
+ sessionId: registration.sessionId,
64
+ ...(registration.sessionFile ? { sessionFile: registration.sessionFile } : {}),
65
+ isActive: registration.isActive,
66
+ });
67
+ if (typeof release === "function") return { registered: true, release };
68
+ console.error("Failed to register pi-web session liveness: host registry returned no release function.");
69
+ } catch (error) {
70
+ console.error("Failed to register pi-web session liveness:", error);
71
+ }
72
+ return { registered: false, release: () => {} };
73
+ }