@xzzpig/pi-subagents 0.20.0 → 0.21.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 (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -17,8 +17,8 @@ import * as fs from "node:fs";
17
17
  import * as os from "node:os";
18
18
  import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
- import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
- import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
20
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
21
+ import { Box, Container, Spacer, Text, type Component } from "@earendil-works/pi-tui";
22
22
  import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
23
23
  import { resolveGlobalNpmRoot } from "../agents/global-npm-root.ts";
24
24
  import { buildAdvertisedAgentCatalog, buildAdvertisedAgentPrompt } from "../agents/advertised-agent-prompt.ts";
@@ -42,7 +42,7 @@ import { resolveDisabledFeatureSurface } from "../shared/disabled-features.ts";
42
42
  import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
43
43
  import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
44
44
  import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
45
- import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
45
+ import { cleanupResultIndexes, missionObserverResultCandidateFiles, resultFilePath } from "../runs/background/result-files.ts";
46
46
  import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
47
47
  import { createResultWatcher } from "../runs/background/result-watcher.ts";
48
48
  import { createResultDeliveryOwnership } from "../runs/background/result-delivery-ownership.ts";
@@ -52,14 +52,9 @@ import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template
52
52
  import { registerMainWatchdog } from "../watchdog/register-main.ts";
53
53
  import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
54
54
  import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
55
- import {
56
- renderSupervisorReply,
57
- renderSupervisorRequest,
58
- SUPERVISOR_REPLY_ENTRY_TYPE,
59
- SUPERVISOR_REQUEST_MESSAGE_TYPE,
60
- type SupervisorRequestMessageDetails,
61
- } from "../intercom/supervisor-ui.ts";
55
+ import { renderSubagentEntry, renderSubagentMessage, SUBAGENT_ENTRY_TYPES, SUBAGENT_MESSAGE_TYPES } from "../tui/subagent-messages.ts";
62
56
  import { registerHerdrStatusBridge, type HerdrStatusRun } from "../integrations/herdr-status.ts";
57
+ import { registerProgramStatusReporter } from "../integrations/program-status.ts";
63
58
  import { hasLiveSubagentWork, registerPiWebSessionLiveness } from "../integrations/pi-web-session-liveness.ts";
64
59
  import { createRetainedNestedRouteTracker } from "../runs/background/retained-nested-route-tracker.ts";
65
60
  import { listHerdrProjectPaneRoots, restoreHerdrProjectPaneSnapshots } from "../inspectors/herdr/project-panes.ts";
@@ -68,21 +63,22 @@ import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDet
68
63
  import { resolveWaitToolConfig } from "../runs/background/subagent-wait.ts";
69
64
  import { registerWaitTool } from "../runs/background/wait-tool.ts";
70
65
  import { registerSubagentToolActivation } from "./tool-activation.ts";
66
+ import { recordedPromptSection, registerPinnedTool } from "./declaration-pinning.ts";
71
67
  import { createWaitSubscriptionManager } from "../runs/background/wait-subscriptions.ts";
72
68
  import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
73
- import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
74
- import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
69
+ import registerSubagentNotify from "../runs/background/notify.ts";
70
+ import { createParentWake } from "../shared/parent-wake.ts";
71
+ import { handleSubagentSteeringNotice, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
75
72
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.ts";
76
73
  import { disposeChildSessions } from "../runs/shared/child-session.ts";
77
74
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
78
- import { formatDuration, shortenPath } from "../shared/formatters.ts";
79
75
  import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
80
76
  import { applyInjectionBlock, renderInjectionBlock, resolveInjectableAgents } from "./context-injection.ts";
81
77
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
82
78
  import { formatWorkflowPreflightSummary, normalizeWorkflowPreflight } from "../workflows/workflow-preflight.ts";
83
79
  import { runtimeReplacedAbortReason } from "../workflows/workflow-reuse.ts";
84
80
  import { finalizeToolResult } from "./tool-result.ts";
85
- import { removedModelWorkflowFieldError } from "./public-execution.ts";
81
+ import { flattenSubagentToolOptions } from "./subagent-options.ts";
86
82
  import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
87
83
  import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
88
84
  import { resolveMissionStoreLocation } from "../missions/store.ts";
@@ -90,6 +86,7 @@ import { listRetainedChildren } from "../runs/background/retained-children.ts";
90
86
  import {
91
87
  type Details,
92
88
  type MainWindowRendererConfig,
89
+ type AsyncJobState,
93
90
  type SubagentState,
94
91
  DIRS,
95
92
  DEFAULT_ARTIFACT_CONFIG,
@@ -104,9 +101,7 @@ import {
104
101
  resolveMaxSubagentSpawnsPerSession,
105
102
  } from "../shared/types.ts";
106
103
  import {
107
- formatSubagentControlNotice,
108
104
  handleSubagentControlNotice,
109
- SUBAGENT_CONTROL_MESSAGE_TYPE,
110
105
  type SubagentControlMessageDetails,
111
106
  } from "./control-notices.ts";
112
107
  import { showUpgradeNotice } from "./upgrade-notice.ts";
@@ -123,7 +118,7 @@ type SubagentExecutor = ReturnType<SubagentExecutorModule["createSubagentExecuto
123
118
  type SubagentExecutorDeps = Parameters<SubagentExecutorModule["createSubagentExecutor"]>[0];
124
119
 
125
120
  interface SubagentRuntimeEntry {
126
- cleanup(): void;
121
+ cleanup(shutdownReason?: string): void;
127
122
  sessionManager: object | null;
128
123
  visibleControlNotices: Set<string>;
129
124
  }
@@ -236,37 +231,6 @@ function createSlashResultComponent(
236
231
  return container;
237
232
  }
238
233
 
239
- class SubagentControlNoticeComponent implements Component {
240
- private readonly details: SubagentControlMessageDetails;
241
- private readonly theme: ExtensionContext["ui"]["theme"];
242
-
243
- constructor(details: SubagentControlMessageDetails, theme: ExtensionContext["ui"]["theme"]) {
244
- this.details = details;
245
- this.theme = theme;
246
- }
247
-
248
- invalidate(): void {}
249
-
250
- render(width: number): string[] {
251
- const eventLabel = this.details.event.type.replaceAll("_", " ");
252
- if (width < 3) return [truncateToWidth(`Subagent ${eventLabel}`, width)];
253
- const bodyWidth = Math.max(1, width - 2);
254
- const borderChar = "─";
255
- const header = ` ⚠ Subagent ${eventLabel}: ${this.details.event.agent} `;
256
- const headerText = truncateToWidth(header, bodyWidth, "");
257
- const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
258
- const lines = [this.theme.fg("accent", `╭${headerText}${borderChar.repeat(headerPadding)}╮`)];
259
-
260
- for (const line of wrapTextWithAnsi(formatSubagentControlNotice(this.details), bodyWidth)) {
261
- const text = truncateToWidth(line, bodyWidth, "");
262
- const padding = Math.max(0, bodyWidth - visibleWidth(text));
263
- lines.push(this.theme.fg("accent", `│${text}${" ".repeat(padding)}│`));
264
- }
265
- lines.push(this.theme.fg("accent", `╰${borderChar.repeat(bodyWidth)}╯`));
266
- return lines;
267
- }
268
- }
269
-
270
234
  export function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[] {
271
235
  const active = (status: string) => status === "queued" || status === "running";
272
236
  const foregroundChildrenByWorkflow = new Map<string, Array<{ agent: string; needsAttention: boolean }>>();
@@ -332,6 +296,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
332
296
  const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
333
297
  const asyncWidgetEnabled = config.asyncWidget !== false;
334
298
  const asyncWidgetCollapsed = config.asyncWidgetCollapsed === true;
299
+ const asyncWidgetLayout = config.asyncWidgetLayout ?? "adaptive";
335
300
  const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
336
301
  const tempArtifactsDir = getArtifactsDir(null);
337
302
  const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
@@ -382,14 +347,27 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
382
347
  }, run);
383
348
  };
384
349
 
350
+ // Every notice that wakes the parent goes through parentWake; the watchdog wakes only inside a run.
351
+ const parentWake = createParentWake(pi);
352
+ const wakingPi = { events: pi.events, sendMessage: parentWake.sendMessage, on: pi.on };
385
353
  const supervisorChannel = createNativeSupervisorChannel(pi, state, {
386
354
  // Owner states are created only by scheduled execution, which loads the executor first.
387
355
  getCurrentOwnerStates: () => executor?.getCurrentSupervisorOwnerStates() ?? [],
356
+ parentWake,
388
357
  });
389
- const waitSubscriptionManager = createWaitSubscriptionManager(pi, state);
358
+ const waitSubscriptionManager = createWaitSubscriptionManager(wakingPi, state);
390
359
  const mainWatchdog = registerMainWatchdog(pi);
391
360
  const resultDeliveryOwnership = createResultDeliveryOwnership(state);
392
- const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
361
+ const completionNotifier = registerSubagentNotify(wakingPi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
362
+ // Ended async runs whose result has not reached the notifier yet.
363
+ const owedResultRunIds = new Set<string>();
364
+ // Tracked runs whose result was already delivered, so a later terminal
365
+ // transition (the tracker can see the end after the result) holds nothing.
366
+ const deliveredRunIds = new Set<string>();
367
+ const holdOwedResult = (job: AsyncJobState) => {
368
+ if (!job.parentWorkflowRunId && !deliveredRunIds.has(job.asyncId) && job.sessionId
369
+ && resultDeliveryOwnership.owns(job.sessionId, job.completionOwnerId)) owedResultRunIds.add(job.asyncId);
370
+ };
393
371
  let retainedNestedRouteTracker: ReturnType<typeof createRetainedNestedRouteTracker> | undefined;
394
372
  const fleetStatus = fleetViewEnabled
395
373
  ? new SubagentFleetStatus(state, async (itemKey) => {
@@ -421,7 +399,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
421
399
  });
422
400
  let refreshResultDelivery = () => {};
423
401
  let advertisedAgents: AgentConfig[] = [];
424
- let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> | undefined;
402
+ let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> & { projectTrusted?: boolean } | undefined;
425
403
  let advertisementGeneration = 0;
426
404
  let globalRoot: string | null = null;
427
405
  let advertisementReady: Promise<void | { error: unknown }> = Promise.resolve();
@@ -439,7 +417,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
439
417
  advertisedAgents = [];
440
418
  if (!advertisedContext) return;
441
419
  clearAgentDiscoveryCache();
442
- advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider, { globalNpmRoot: globalRoot }).agents
420
+ advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider, { globalNpmRoot: globalRoot, projectTrusted: advertisedContext.projectTrusted }).agents
443
421
  .filter((agent) => agent.advertise === true);
444
422
  };
445
423
  const beginAdvertisement = (ctx: ExtensionContext) => {
@@ -447,7 +425,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
447
425
  notifySessionChange();
448
426
  sessionChanged = new Promise<void>((resolve) => { notifySessionChange = resolve; });
449
427
  advertisedAgents = [];
450
- advertisedContext = { cwd: ctx.cwd, model: ctx.model };
428
+ advertisedContext = { cwd: ctx.cwd, model: ctx.model, projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined };
451
429
  globalRoot = null;
452
430
  advertisementReady = resolveGlobalNpmRoot().then((root) => {
453
431
  if (generation !== advertisementGeneration) return;
@@ -461,14 +439,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
461
439
  });
462
440
  };
463
441
  const hasResultDeliveryDemand = () => {
442
+ if (owedResultRunIds.size > 0) return true;
464
443
  if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
465
444
  if (state.foregroundControls.size > 0) return true;
466
445
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
467
446
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
468
447
  };
469
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
470
- if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot });
471
- const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false, globalNpmRoot: globalRoot });
448
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string, options: { projectTrusted?: boolean } = {}) => {
449
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot, projectTrusted: options.projectTrusted });
450
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false, globalNpmRoot: globalRoot, projectTrusted: options.projectTrusted });
472
451
  const discovered = snapshot.effective;
473
452
  const all = snapshot.all;
474
453
  const configuredAgents: AgentConfig[] = [
@@ -477,18 +456,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
477
456
  ...all.user,
478
457
  ...all.project,
479
458
  ];
480
- const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope, preferredModelProvider });
459
+ // Runtime agents take model settings from the scope discovery actually used.
460
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope: discovered.scope, preferredModelProvider, projectTrusted: options.projectTrusted });
481
461
  if (discovered.maxThinking === undefined) return merged;
482
462
  return {
483
463
  ...merged,
484
464
  agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
485
465
  };
486
466
  };
467
+ const programStatus = registerProgramStatusReporter({
468
+ enabled: config.programStatus !== false,
469
+ // Fleet history keeps recent finished runs after the widget drops them.
470
+ getJobs: () => new Map([...(state.fleetJobs ?? []), ...state.asyncJobs]).values(),
471
+ getPendingRequests: () => supervisorChannel.pending.values(),
472
+ });
487
473
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
488
474
  widgetEnabled: asyncWidgetEnabled,
489
475
  widgetCollapsed: asyncWidgetCollapsed,
490
- onJobTerminal: () => refreshResultDelivery(),
476
+ widgetLayout: asyncWidgetLayout,
477
+ onJobTerminal: (job) => {
478
+ holdOwedResult(job);
479
+ refreshResultDelivery();
480
+ },
481
+ onJobCleanup: (asyncId) => deliveredRunIds.delete(asyncId),
491
482
  supervisorRequestState: supervisorChannel.getSupervisorRequestState,
483
+ onJobsChanged: programStatus.sync,
492
484
  });
493
485
  const resultWatcher = createResultWatcher(
494
486
  pi,
@@ -498,6 +490,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
498
490
  {
499
491
  notifier: completionNotifier,
500
492
  ownership: resultDeliveryOwnership,
493
+ onResultDelivered: (runId) => {
494
+ owedResultRunIds.delete(runId);
495
+ if (state.asyncJobs.has(runId)) deliveredRunIds.add(runId);
496
+ },
501
497
  observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
502
498
  observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
503
499
  hasDeliveryDemand: hasResultDeliveryDemand,
@@ -544,6 +540,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
544
540
 
545
541
  const executorDeps: SubagentExecutorDeps = {
546
542
  pi,
543
+ parentWake,
547
544
  state,
548
545
  config,
549
546
  asyncByDefault,
@@ -595,15 +592,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
595
592
  modulePreloadTimer.unref?.();
596
593
  };
597
594
 
598
- pi.registerMessageRenderer<SupervisorRequestMessageDetails>(SUPERVISOR_REQUEST_MESSAGE_TYPE, renderSupervisorRequest);
595
+ for (const customType of SUBAGENT_MESSAGE_TYPES) pi.registerMessageRenderer(customType, renderSubagentMessage);
599
596
  // SAFETY: `registerEntryRenderer` is not part of the typed ExtensionAPI in the
600
597
  // pinned dependency version; this cast pins the runtime shape of the entry
601
598
  // renderer registration surface, guarded below by a typeof check.
602
599
  const registerEntryRenderer = (pi as unknown as {
603
- registerEntryRenderer?: (customType: string, renderer: (entry: { data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
600
+ registerEntryRenderer?: (customType: string, renderer: (entry: { customType: string; data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
604
601
  }).registerEntryRenderer;
605
602
  if (typeof registerEntryRenderer === "function") {
606
- registerEntryRenderer.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, renderSupervisorReply);
603
+ for (const customType of SUBAGENT_ENTRY_TYPES) registerEntryRenderer.call(pi, customType, renderSubagentEntry);
607
604
  }
608
605
 
609
606
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
@@ -629,59 +626,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
629
626
  return new Text(content, 0, 0);
630
627
  });
631
628
 
632
- pi.registerMessageRenderer<SubagentNotifyDetails>("subagent-notify", (message, options, theme) => {
633
- const content = typeof message.content === "string" ? message.content : "";
634
- const details = (message.details as SubagentNotifyDetails | undefined) ?? parseSubagentNotifyContent(content);
635
- if (!details) return new Text(content, 0, 0);
636
- const icon = details.status === "completed"
637
- ? theme.fg("success", "✓")
638
- : details.status === "paused"
639
- ? theme.fg("warning", "■")
640
- : theme.fg("error", "✗");
641
- const parts: string[] = [];
642
- if (details.taskInfo) parts.push(details.taskInfo);
643
- if (details.durationMs !== undefined) parts.push(formatDuration(details.durationMs));
644
- let text = `${icon} ${theme.bold(details.agent)} ${theme.fg("dim", details.status)}`;
645
- if (parts.length > 0) text += ` ${theme.fg("dim", "·")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `)}`;
646
- const trimmedPreview = details.resultPreview.trim();
647
- const previewLines = options.expanded
648
- ? trimmedPreview.split("\n").filter((line) => line.trim())
649
- : [trimmedPreview.split("\n", 1)[0] ?? ""].filter((line) => line.trim());
650
- for (const line of previewLines.length > 0 ? previewLines : ["(no output)"]) {
651
- text += `\n ${theme.fg("dim", `⎿ ${line}`)}`;
652
- }
653
- if (!options.expanded && trimmedPreview.includes("\n")) {
654
- const expandKey = keyText("app.tools.expand");
655
- text += `\n ${theme.fg("dim", `${expandKey} full notification`)}`;
656
- }
657
- if (details.workflowRunId) {
658
- text += `\n ${theme.fg("muted", `workflow: ${details.workflowRunId}`)}`;
659
- }
660
- if (details.childRuns?.length) {
661
- text += `\n ${theme.fg("muted", `children: ${details.childRuns.map((child) => `${child.workflowKey ?? child.agent ?? "child"}=${child.runId}`).join(", ")}`)}`;
662
- }
663
- if (details.reconciledFromDetachedChild) {
664
- text += `\n ${theme.fg("muted", `reconciled child: ${details.reconciledFromDetachedChild}`)}`;
665
- }
666
- if (details.sessionLabel && details.sessionValue) {
667
- text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
668
- }
669
- return new Text(text, 0, 0);
670
- });
671
-
672
- pi.registerMessageRenderer<SubagentSteeringMessageDetails>(SUBAGENT_STEERING_MESSAGE_TYPE, (message, _options, theme) => {
673
- const details = message.details as SubagentSteeringMessageDetails | undefined;
674
- if (!details) return undefined;
675
- return new Text(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
676
- });
677
-
678
- pi.registerMessageRenderer<SubagentControlMessageDetails>(SUBAGENT_CONTROL_MESSAGE_TYPE, (message, _options, theme) => {
679
- const details = message.details as SubagentControlMessageDetails | undefined;
680
- if (!details?.event) return undefined;
681
- const content = typeof message.content === "string" ? message.content : undefined;
682
- return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
683
- });
684
-
685
629
  const executeSubagentReady = async (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
686
630
  await waitForAdvertisement();
687
631
  return (await getExecutor()).executePublic(id, params, signal, onUpdate, ctx);
@@ -730,9 +674,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
730
674
  parameters,
731
675
 
732
676
  async execute(id, params, signal, onUpdate, ctx) {
733
- const removedField = removedModelWorkflowFieldError(params);
734
- if (removedField) throw new Error(removedField);
735
- return finalizeToolResult(await executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
677
+ return finalizeToolResult(await executeSubagentCollapsed(id, flattenSubagentToolOptions(params, disabledFeatures), signal ?? new AbortController().signal, onUpdate, ctx));
736
678
  },
737
679
 
738
680
  renderCall(args, theme) {
@@ -745,9 +687,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
745
687
  0, 0,
746
688
  );
747
689
  }
690
+ const preflight = args.options?.preflight ?? (args as { preflight?: unknown }).preflight;
748
691
  if (args.workflow !== undefined)
749
692
  return new Text(
750
- `${title}${gap}${theme.fg("accent", args.workflow === true || args.workflow === "true" ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${args.preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(args.preflight))}` : ""}`,
693
+ `${title}${gap}${theme.fg("accent", args.workflow === true || args.workflow === "true" ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(preflight))}` : ""}`,
751
694
  0,
752
695
  0,
753
696
  );
@@ -769,15 +712,22 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
769
712
 
770
713
  };
771
714
 
772
- pi.registerTool(tool);
715
+ registerPinnedTool(pi, tool);
773
716
 
774
- pi.on("before_agent_start", (event) => {
717
+ pi.on("before_agent_start", (event, ctx) => {
775
718
  if (process.env[SUBAGENT_CHILD_ENV] === "1") return undefined;
719
+ const projectTrusted = typeof ctx.isProjectTrusted !== "function" || ctx.isProjectTrusted() !== false;
720
+ const trustChanged = contextInjectionProjectTrusted !== projectTrusted;
721
+ if (trustChanged) {
722
+ refreshContextInjectionSnapshot(ctx);
723
+ beginAdvertisement(ctx);
724
+ }
776
725
  const next = applyInjectionBlock({
777
726
  systemPrompt: event.systemPrompt,
778
727
  block: state.contextInjectionBlock ?? "",
728
+ replaceExisting: !projectTrusted || trustChanged,
779
729
  });
780
- return next ? { systemPrompt: next } : undefined;
730
+ return next !== undefined ? { systemPrompt: next } : undefined;
781
731
  });
782
732
 
783
733
  pi.on("before_agent_start", async (event, ctx) => {
@@ -787,7 +737,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
787
737
  // Structured sections let Pi append a transcript delta instead of replacing the
788
738
  // cached system prompt. Set the section on every turn it applies: Pi rebuilds the
789
739
  // options each turn, and an unset turn records a removal.
790
- const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId));
740
+ const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId), recordedPromptSection(pi, "advertised_subagents"));
791
741
  if (catalog) event.systemPromptOptions.sections.advertised_subagents = catalog;
792
742
  });
793
743
 
@@ -795,7 +745,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
795
745
 
796
746
  pi.on("agent_end", async (_event, ctx) => {
797
747
  try {
798
- if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
748
+ // A headless host may dispose the session as soon as this turn settles, so hand
749
+ // finished results to Pi now; Pi runs the queued completion turn after agent_end.
750
+ // A failed drain rejects without this step so its deadline stays exact.
751
+ if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests }).then(resultWatcher.deliverPendingResults);
799
752
  } finally {
800
753
  // Deliver notices after a failed drain without suppressing its rejection.
801
754
  const ownerSessionId = state.currentSessionId;
@@ -806,7 +759,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
806
759
  const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
807
760
  for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
808
761
  handleSubagentControlNotice({
809
- pi,
762
+ pi: parentWake,
810
763
  state,
811
764
  visibleControlNotices: new Set(),
812
765
  details: { source: "goal", event: notice.event, noticeText: notice.message },
@@ -837,14 +790,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
837
790
  });
838
791
  const controlEventHandler = (payload: unknown) => {
839
792
  handleSubagentControlNotice({
840
- pi,
793
+ pi: parentWake,
841
794
  state,
842
795
  visibleControlNotices,
843
796
  details: payload as SubagentControlMessageDetails,
844
797
  });
845
798
  };
846
799
  const steeringNoticeHandler = (payload: unknown) => {
847
- handleSubagentSteeringNotice({ pi, state, details: payload as SubagentSteeringMessageDetails });
800
+ handleSubagentSteeringNotice({ pi: parentWake, state, details: payload as SubagentSteeringMessageDetails });
848
801
  };
849
802
  const asyncStartedHandler = (payload: unknown) => {
850
803
  handleStarted(payload);
@@ -854,6 +807,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
854
807
  };
855
808
  const asyncCompleteHandler = (payload: unknown) => {
856
809
  handleComplete(payload);
810
+ // Detached-workflow reconciliation publishes the result, then ends the job
811
+ // with this event; the next status refresh sees it already terminal.
812
+ const job = state.asyncJobs.get((payload as { id?: string } | null)?.id ?? "");
813
+ if (job && job.status !== "queued" && job.status !== "running"
814
+ && fs.existsSync(resultFilePath(DIRS.results, job.asyncId))) holdOwedResult(job);
857
815
  refreshResultDelivery();
858
816
  refreshActiveAsyncCapacity();
859
817
  scheduledRunManager.handleAsyncCompletion(payload);
@@ -934,6 +892,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
934
892
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
935
893
  state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
936
894
  transitionResultDelivery();
895
+ owedResultRunIds.clear();
896
+ deliveredRunIds.clear();
937
897
  state.parentSessionFile = ctx.sessionManager.getSessionFile();
938
898
  state.trustedSessionFileRoot = state.parentSessionFile ? path.join(getAgentDir(), "sessions") : undefined;
939
899
  state.trustedSessionRoots = [...new Set([
@@ -996,6 +956,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
996
956
  // Snapshot the injectable-agent advertisement once per session so the
997
957
  // appended `<available_subagents>` block stays byte-identical across turns
998
958
  // and provider prompt caching is never invalidated mid-session.
959
+ let contextInjectionProjectTrusted: boolean | undefined;
999
960
  const refreshContextInjectionSnapshot = (ctx: ExtensionContext) => {
1000
961
  if (process.env[SUBAGENT_CHILD_ENV] === "1") return;
1001
962
  try {
@@ -1005,7 +966,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1005
966
  state.contextInjectionUnknownNames = [];
1006
967
  return;
1007
968
  }
1008
- const discovery = discoverAgentsAll(cwd);
969
+ contextInjectionProjectTrusted = typeof ctx.isProjectTrusted !== "function" || ctx.isProjectTrusted() !== false;
970
+ const discovery = discoverAgentsAll(cwd, undefined, { projectTrusted: contextInjectionProjectTrusted });
1009
971
  const mergedAgents = mergeAgentsForScope("both", discovery.user, discovery.project, discovery.builtin, discovery.package);
1010
972
  const resolved = resolveInjectableAgents({
1011
973
  agents: mergedAgents,
@@ -1026,11 +988,21 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1026
988
  const runtimeEntry: SubagentRuntimeEntry = {
1027
989
  sessionManager: null,
1028
990
  visibleControlNotices,
1029
- cleanup() {
991
+ cleanup(shutdownReason) {
1030
992
  if (runtimeCleaned) return;
1031
993
  runtimeCleaned = true;
994
+ programStatus.dispose(shutdownReason);
1032
995
  releaseHostSessionLiveness();
1033
996
  releaseHostSessionLiveness = () => {};
997
+ // Detached foreground children run in this runtime's memory, and the next runtime
998
+ // cannot see or control them, so stop each one and record it as stopped.
999
+ for (const control of state.foregroundControls.values()) {
1000
+ try {
1001
+ control.stopForRuntimeReplacement?.();
1002
+ } catch (error) {
1003
+ console.error(`Failed to stop detached foreground run ${control.runId}:`, error);
1004
+ }
1005
+ }
1034
1006
  // Workflow continuations retain their launch context; abort them before
1035
1007
  // teardown so a reload cannot launch through a stale context.
1036
1008
  for (const controller of state.workflowControllers?.values() ?? []) {
@@ -1122,12 +1094,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1122
1094
  };
1123
1095
 
1124
1096
  pi.on("agent_start", () => {
1097
+ parentWake.agentStarted();
1125
1098
  resumeWidgetsAfterCompaction();
1126
1099
  herdrStatusBridge.agentStarted();
1100
+ programStatus.agentStarted();
1127
1101
  });
1128
1102
 
1103
+ pi.on("message_start", (event) => completionNotifier.messageStarted(event.message));
1104
+
1129
1105
  pi.on("agent_settled", () => {
1130
1106
  resumeWidgetsAfterCompaction();
1107
+ programStatus.agentSettled();
1131
1108
  });
1132
1109
 
1133
1110
  pi.on("session_before_compact", (event) => {
@@ -1138,7 +1115,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1138
1115
  if (event.reason !== "manual") return;
1139
1116
  const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
1140
1117
  if (!hasActiveAsyncWork || !withLastUiContext(() => true)) return;
1141
- pi.sendMessage(
1118
+ parentWake.sendMessage(
1142
1119
  {
1143
1120
  customType: "subagent-compaction-resume",
1144
1121
  content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
@@ -1149,6 +1126,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1149
1126
  });
1150
1127
 
1151
1128
  pi.on("session_start", (event, ctx) => {
1129
+ parentWake.bindSession(ctx);
1130
+ completionNotifier.bindSession(ctx.sessionManager);
1152
1131
  installRuntime(ctx);
1153
1132
  startSessionMaintenance();
1154
1133
  scheduleModulePreload();
@@ -1162,7 +1141,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1162
1141
  ? registerPiWebSessionLiveness({
1163
1142
  sessionId,
1164
1143
  ...(sessionFile ? { sessionFile } : {}),
1165
- isActive: () => hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery(),
1144
+ isActive: () => owedResultRunIds.size > 0 || hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery() || parentWake.isPending(),
1166
1145
  })
1167
1146
  : { registered: false, release: () => {} };
1168
1147
  releaseHostSessionLiveness = liveness.release;
@@ -1174,13 +1153,16 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1174
1153
  hasUI: ctx.hasUI === true,
1175
1154
  runs: activeHerdrRuns(),
1176
1155
  });
1156
+ programStatus.sessionStarted({ hasUI: ctx.hasUI === true, mode: ctx.mode });
1177
1157
  rpcBridge.emitReady(ctx);
1178
1158
  supervisorChannel.start();
1179
1159
  supervisorChannel.activateTransport();
1180
1160
  });
1181
1161
 
1182
- pi.on("session_shutdown", async () => {
1183
- runtimeEntry.cleanup();
1162
+ pi.on("session_shutdown", async (event) => {
1163
+ completionNotifier.sessionShutdown(event?.reason);
1164
+ parentWake.sessionShutdown(event?.reason);
1165
+ runtimeEntry.cleanup(event?.reason);
1184
1166
  try {
1185
1167
  await disposeChildSessions();
1186
1168
  } catch (error) {
@@ -2,8 +2,10 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
 
4
4
  const WORKFLOW_FENCE = /^```(?:js|javascript) workflow[ \t]*$/;
5
+ const PLAIN_JS_FENCE = /^```(?:js|javascript)[ \t]*$/;
5
6
  const OPEN_FENCE = /^(`{3,}|~{3,})/;
6
7
  const CLOSE_FENCE = /^(`{3,}|~{3,})[ \t]*$/;
8
+ const FILE_FALLBACK = "Or write the script to a file and pass its path, such as workflow: \"./script.js\".";
7
9
 
8
10
  export type ReplyWorkflowScript = { script: string } | { error: string };
9
11
 
@@ -28,31 +30,38 @@ function scriptFromReply(content: AssistantMessage["content"]): ReplyWorkflowScr
28
30
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
31
  && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
30
32
  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.` };
33
+ if (!content.some((block) => block.type === "text")) return { error: "The assistant message that issued this call has no text in the session, so the reply's visible text, including any ```js workflow block, never reached it. Write the script to a file and pass its path, such as workflow: \"./script.js\"." };
31
34
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
32
- const { blocks, unclosed } = workflowBlocks(text);
33
- if (unclosed) return { error: "The ```js workflow block in this reply is not closed." };
34
- if (blocks.length !== 1) return { error: `workflow: true requires exactly one \`\`\`js workflow fenced block in the same reply as the tool call; found ${blocks.length}.` };
35
+ const { tagged, plain, unclosed } = workflowBlocks(text);
36
+ if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
37
+ // Models often drop the workflow tag, so a lone plain js block is unambiguous enough to run.
38
+ const blocks = tagged.length > 0 ? tagged : plain.length === 1 ? plain : [];
39
+ if (blocks.length !== 1) {
40
+ const untagged = tagged.length === 0 && plain.length > 1 ? ` This reply has ${plain.length} untagged js blocks; open the script's block with the line "\`\`\`js workflow".` : "";
41
+ return { error: `workflow: true needs one fenced block in the same reply as the tool call, opened with the exact line "\`\`\`js workflow" and closed with "\`\`\`"; found ${tagged.length}.${untagged} ${FILE_FALLBACK}` };
42
+ }
35
43
  const script = blocks[0]!;
36
- if (!script.trim()) return { error: "The ```js workflow block in this reply is empty." };
44
+ if (!script.trim()) return { error: "The script's fenced block in this reply is empty." };
37
45
  return { script };
38
46
  }
39
47
 
40
- /** Collects ```js workflow / ```javascript workflow fenced blocks, skipping the bodies of other fences. */
41
- function workflowBlocks(text: string): { blocks: string[]; unclosed: boolean } {
48
+ /** Collects tagged (```js workflow) and plain (```js) fenced blocks, skipping the bodies of other fences. */
49
+ function workflowBlocks(text: string): { tagged: string[]; plain: string[]; unclosed: boolean } {
42
50
  const lines = text.split("\n");
43
- const blocks: string[] = [];
44
- let fence: { marker: string; tagged: boolean; start: number } | undefined;
51
+ const tagged: string[] = [];
52
+ const plain: string[] = [];
53
+ let fence: { marker: string; kind: "tagged" | "plain" | undefined; start: number } | undefined;
45
54
  for (let index = 0; index < lines.length; index++) {
46
55
  const line = lines[index]!.replace(/\r$/, "");
47
56
  if (!fence) {
48
57
  const open = OPEN_FENCE.exec(line);
49
- if (open) fence = { marker: open[1]!, tagged: WORKFLOW_FENCE.test(line), start: index + 1 };
58
+ if (open) fence = { marker: open[1]!, kind: WORKFLOW_FENCE.test(line) ? "tagged" : PLAIN_JS_FENCE.test(line) ? "plain" : undefined, start: index + 1 };
50
59
  continue;
51
60
  }
52
61
  const close = CLOSE_FENCE.exec(line);
53
62
  if (!close || close[1]![0] !== fence.marker[0] || close[1]!.length < fence.marker.length) continue;
54
- if (fence.tagged) blocks.push(lines.slice(fence.start, index).join("\n"));
63
+ if (fence.kind) (fence.kind === "tagged" ? tagged : plain).push(lines.slice(fence.start, index).join("\n"));
55
64
  fence = undefined;
56
65
  }
57
- return { blocks, unclosed: fence?.tagged === true };
66
+ return { tagged, plain, unclosed: fence?.kind === "tagged" || (fence?.kind === "plain" && tagged.length === 0) };
58
67
  }