@xzzpig/pi-subagents 0.19.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.
- package/CHANGELOG.md +214 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +86 -11
- package/docs/configuration.md +68 -7
- package/docs/extension-api.md +37 -12
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +48 -17
- package/docs/models.md +7 -3
- package/docs/observability.md +18 -8
- package/docs/tool-reference.md +138 -80
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +18 -9
- package/index.ts +5 -0
- package/package.json +5 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +224 -122
- package/src/api/preflight.ts +50 -5
- package/src/extension/config.ts +24 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +134 -145
- package/src/extension/public-execution.ts +3 -0
- package/src/extension/reply-workflow-script.ts +21 -12
- package/src/extension/rpc.ts +12 -7
- package/src/extension/schemas.ts +39 -33
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/native-supervisor-channel.ts +77 -4
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/goal-driver.ts +44 -31
- package/src/missions/store.ts +35 -6
- package/src/profiles/profiles.ts +29 -23
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +231 -44
- package/src/runs/background/async-job-tracker.ts +12 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +18 -11
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/control-channel.ts +43 -0
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +29 -8
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-aliases.ts +7 -4
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +282 -72
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +75 -16
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +109 -58
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +270 -89
- package/src/runs/shared/child-commands.ts +229 -0
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +131 -40
- package/src/runs/shared/child-tool-plan.ts +14 -27
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +39 -2
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +4 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/run-history.ts +87 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +33 -18
- package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/required-child-extensions.ts +39 -5
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +42 -3
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagent-cost.ts +9 -5
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +28 -20
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-receipt.ts +2 -2
- package/src/workflows/workflow-resources.ts +18 -4
package/src/extension/index.ts
CHANGED
|
@@ -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 {
|
|
21
|
-
import { Box, Container, Spacer, Text,
|
|
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
|
|
74
|
-
import {
|
|
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 {
|
|
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 }>>();
|
|
@@ -331,6 +295,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
331
295
|
const fleetViewEnabled = config.fleetView !== false;
|
|
332
296
|
const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
|
|
333
297
|
const asyncWidgetEnabled = config.asyncWidget !== false;
|
|
298
|
+
const asyncWidgetCollapsed = config.asyncWidgetCollapsed === true;
|
|
299
|
+
const asyncWidgetLayout = config.asyncWidgetLayout ?? "adaptive";
|
|
334
300
|
const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
|
|
335
301
|
const tempArtifactsDir = getArtifactsDir(null);
|
|
336
302
|
const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
|
|
@@ -381,14 +347,27 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
381
347
|
}, run);
|
|
382
348
|
};
|
|
383
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 };
|
|
384
353
|
const supervisorChannel = createNativeSupervisorChannel(pi, state, {
|
|
385
354
|
// Owner states are created only by scheduled execution, which loads the executor first.
|
|
386
355
|
getCurrentOwnerStates: () => executor?.getCurrentSupervisorOwnerStates() ?? [],
|
|
356
|
+
parentWake,
|
|
387
357
|
});
|
|
388
|
-
const waitSubscriptionManager = createWaitSubscriptionManager(
|
|
358
|
+
const waitSubscriptionManager = createWaitSubscriptionManager(wakingPi, state);
|
|
389
359
|
const mainWatchdog = registerMainWatchdog(pi);
|
|
390
360
|
const resultDeliveryOwnership = createResultDeliveryOwnership(state);
|
|
391
|
-
const completionNotifier = registerSubagentNotify(
|
|
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
|
+
};
|
|
392
371
|
let retainedNestedRouteTracker: ReturnType<typeof createRetainedNestedRouteTracker> | undefined;
|
|
393
372
|
const fleetStatus = fleetViewEnabled
|
|
394
373
|
? new SubagentFleetStatus(state, async (itemKey) => {
|
|
@@ -420,7 +399,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
420
399
|
});
|
|
421
400
|
let refreshResultDelivery = () => {};
|
|
422
401
|
let advertisedAgents: AgentConfig[] = [];
|
|
423
|
-
let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> | undefined;
|
|
402
|
+
let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> & { projectTrusted?: boolean } | undefined;
|
|
424
403
|
let advertisementGeneration = 0;
|
|
425
404
|
let globalRoot: string | null = null;
|
|
426
405
|
let advertisementReady: Promise<void | { error: unknown }> = Promise.resolve();
|
|
@@ -438,7 +417,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
438
417
|
advertisedAgents = [];
|
|
439
418
|
if (!advertisedContext) return;
|
|
440
419
|
clearAgentDiscoveryCache();
|
|
441
|
-
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
|
|
442
421
|
.filter((agent) => agent.advertise === true);
|
|
443
422
|
};
|
|
444
423
|
const beginAdvertisement = (ctx: ExtensionContext) => {
|
|
@@ -446,7 +425,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
446
425
|
notifySessionChange();
|
|
447
426
|
sessionChanged = new Promise<void>((resolve) => { notifySessionChange = resolve; });
|
|
448
427
|
advertisedAgents = [];
|
|
449
|
-
advertisedContext = { cwd: ctx.cwd, model: ctx.model };
|
|
428
|
+
advertisedContext = { cwd: ctx.cwd, model: ctx.model, projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined };
|
|
450
429
|
globalRoot = null;
|
|
451
430
|
advertisementReady = resolveGlobalNpmRoot().then((root) => {
|
|
452
431
|
if (generation !== advertisementGeneration) return;
|
|
@@ -460,14 +439,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
460
439
|
});
|
|
461
440
|
};
|
|
462
441
|
const hasResultDeliveryDemand = () => {
|
|
442
|
+
if (owedResultRunIds.size > 0) return true;
|
|
463
443
|
if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
|
|
464
444
|
if (state.foregroundControls.size > 0) return true;
|
|
465
445
|
if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
|
|
466
446
|
return missionObserverResultCandidateFiles(DIRS.results).length > 0;
|
|
467
447
|
};
|
|
468
|
-
const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
|
|
469
|
-
if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot });
|
|
470
|
-
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 });
|
|
471
451
|
const discovered = snapshot.effective;
|
|
472
452
|
const all = snapshot.all;
|
|
473
453
|
const configuredAgents: AgentConfig[] = [
|
|
@@ -476,17 +456,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
476
456
|
...all.user,
|
|
477
457
|
...all.project,
|
|
478
458
|
];
|
|
479
|
-
|
|
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 });
|
|
480
461
|
if (discovered.maxThinking === undefined) return merged;
|
|
481
462
|
return {
|
|
482
463
|
...merged,
|
|
483
464
|
agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
|
|
484
465
|
};
|
|
485
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
|
+
});
|
|
486
473
|
const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
|
|
487
474
|
widgetEnabled: asyncWidgetEnabled,
|
|
488
|
-
|
|
475
|
+
widgetCollapsed: asyncWidgetCollapsed,
|
|
476
|
+
widgetLayout: asyncWidgetLayout,
|
|
477
|
+
onJobTerminal: (job) => {
|
|
478
|
+
holdOwedResult(job);
|
|
479
|
+
refreshResultDelivery();
|
|
480
|
+
},
|
|
481
|
+
onJobCleanup: (asyncId) => deliveredRunIds.delete(asyncId),
|
|
489
482
|
supervisorRequestState: supervisorChannel.getSupervisorRequestState,
|
|
483
|
+
onJobsChanged: programStatus.sync,
|
|
490
484
|
});
|
|
491
485
|
const resultWatcher = createResultWatcher(
|
|
492
486
|
pi,
|
|
@@ -496,6 +490,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
496
490
|
{
|
|
497
491
|
notifier: completionNotifier,
|
|
498
492
|
ownership: resultDeliveryOwnership,
|
|
493
|
+
onResultDelivered: (runId) => {
|
|
494
|
+
owedResultRunIds.delete(runId);
|
|
495
|
+
if (state.asyncJobs.has(runId)) deliveredRunIds.add(runId);
|
|
496
|
+
},
|
|
499
497
|
observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
|
|
500
498
|
observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
|
|
501
499
|
hasDeliveryDemand: hasResultDeliveryDemand,
|
|
@@ -542,6 +540,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
542
540
|
|
|
543
541
|
const executorDeps: SubagentExecutorDeps = {
|
|
544
542
|
pi,
|
|
543
|
+
parentWake,
|
|
545
544
|
state,
|
|
546
545
|
config,
|
|
547
546
|
asyncByDefault,
|
|
@@ -593,15 +592,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
593
592
|
modulePreloadTimer.unref?.();
|
|
594
593
|
};
|
|
595
594
|
|
|
596
|
-
pi.registerMessageRenderer
|
|
595
|
+
for (const customType of SUBAGENT_MESSAGE_TYPES) pi.registerMessageRenderer(customType, renderSubagentMessage);
|
|
597
596
|
// SAFETY: `registerEntryRenderer` is not part of the typed ExtensionAPI in the
|
|
598
597
|
// pinned dependency version; this cast pins the runtime shape of the entry
|
|
599
598
|
// renderer registration surface, guarded below by a typeof check.
|
|
600
599
|
const registerEntryRenderer = (pi as unknown as {
|
|
601
|
-
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;
|
|
602
601
|
}).registerEntryRenderer;
|
|
603
602
|
if (typeof registerEntryRenderer === "function") {
|
|
604
|
-
registerEntryRenderer.call(pi,
|
|
603
|
+
for (const customType of SUBAGENT_ENTRY_TYPES) registerEntryRenderer.call(pi, customType, renderSubagentEntry);
|
|
605
604
|
}
|
|
606
605
|
|
|
607
606
|
pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
|
|
@@ -627,59 +626,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
627
626
|
return new Text(content, 0, 0);
|
|
628
627
|
});
|
|
629
628
|
|
|
630
|
-
pi.registerMessageRenderer<SubagentNotifyDetails>("subagent-notify", (message, options, theme) => {
|
|
631
|
-
const content = typeof message.content === "string" ? message.content : "";
|
|
632
|
-
const details = (message.details as SubagentNotifyDetails | undefined) ?? parseSubagentNotifyContent(content);
|
|
633
|
-
if (!details) return new Text(content, 0, 0);
|
|
634
|
-
const icon = details.status === "completed"
|
|
635
|
-
? theme.fg("success", "✓")
|
|
636
|
-
: details.status === "paused"
|
|
637
|
-
? theme.fg("warning", "■")
|
|
638
|
-
: theme.fg("error", "✗");
|
|
639
|
-
const parts: string[] = [];
|
|
640
|
-
if (details.taskInfo) parts.push(details.taskInfo);
|
|
641
|
-
if (details.durationMs !== undefined) parts.push(formatDuration(details.durationMs));
|
|
642
|
-
let text = `${icon} ${theme.bold(details.agent)} ${theme.fg("dim", details.status)}`;
|
|
643
|
-
if (parts.length > 0) text += ` ${theme.fg("dim", "·")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `)}`;
|
|
644
|
-
const trimmedPreview = details.resultPreview.trim();
|
|
645
|
-
const previewLines = options.expanded
|
|
646
|
-
? trimmedPreview.split("\n").filter((line) => line.trim())
|
|
647
|
-
: [trimmedPreview.split("\n", 1)[0] ?? ""].filter((line) => line.trim());
|
|
648
|
-
for (const line of previewLines.length > 0 ? previewLines : ["(no output)"]) {
|
|
649
|
-
text += `\n ${theme.fg("dim", `⎿ ${line}`)}`;
|
|
650
|
-
}
|
|
651
|
-
if (!options.expanded && trimmedPreview.includes("\n")) {
|
|
652
|
-
const expandKey = keyText("app.tools.expand");
|
|
653
|
-
text += `\n ${theme.fg("dim", `${expandKey} full notification`)}`;
|
|
654
|
-
}
|
|
655
|
-
if (details.workflowRunId) {
|
|
656
|
-
text += `\n ${theme.fg("muted", `workflow: ${details.workflowRunId}`)}`;
|
|
657
|
-
}
|
|
658
|
-
if (details.childRuns?.length) {
|
|
659
|
-
text += `\n ${theme.fg("muted", `children: ${details.childRuns.map((child) => `${child.workflowKey ?? child.agent ?? "child"}=${child.runId}`).join(", ")}`)}`;
|
|
660
|
-
}
|
|
661
|
-
if (details.reconciledFromDetachedChild) {
|
|
662
|
-
text += `\n ${theme.fg("muted", `reconciled child: ${details.reconciledFromDetachedChild}`)}`;
|
|
663
|
-
}
|
|
664
|
-
if (details.sessionLabel && details.sessionValue) {
|
|
665
|
-
text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
|
|
666
|
-
}
|
|
667
|
-
return new Text(text, 0, 0);
|
|
668
|
-
});
|
|
669
|
-
|
|
670
|
-
pi.registerMessageRenderer<SubagentSteeringMessageDetails>(SUBAGENT_STEERING_MESSAGE_TYPE, (message, _options, theme) => {
|
|
671
|
-
const details = message.details as SubagentSteeringMessageDetails | undefined;
|
|
672
|
-
if (!details) return undefined;
|
|
673
|
-
return new Text(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
|
|
674
|
-
});
|
|
675
|
-
|
|
676
|
-
pi.registerMessageRenderer<SubagentControlMessageDetails>(SUBAGENT_CONTROL_MESSAGE_TYPE, (message, _options, theme) => {
|
|
677
|
-
const details = message.details as SubagentControlMessageDetails | undefined;
|
|
678
|
-
if (!details?.event) return undefined;
|
|
679
|
-
const content = typeof message.content === "string" ? message.content : undefined;
|
|
680
|
-
return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
|
|
681
|
-
});
|
|
682
|
-
|
|
683
629
|
const executeSubagentReady = async (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
|
|
684
630
|
await waitForAdvertisement();
|
|
685
631
|
return (await getExecutor()).executePublic(id, params, signal, onUpdate, ctx);
|
|
@@ -728,9 +674,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
728
674
|
parameters,
|
|
729
675
|
|
|
730
676
|
async execute(id, params, signal, onUpdate, ctx) {
|
|
731
|
-
|
|
732
|
-
if (removedField) throw new Error(removedField);
|
|
733
|
-
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));
|
|
734
678
|
},
|
|
735
679
|
|
|
736
680
|
renderCall(args, theme) {
|
|
@@ -743,9 +687,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
743
687
|
0, 0,
|
|
744
688
|
);
|
|
745
689
|
}
|
|
690
|
+
const preflight = args.options?.preflight ?? (args as { preflight?: unknown }).preflight;
|
|
746
691
|
if (args.workflow !== undefined)
|
|
747
692
|
return new Text(
|
|
748
|
-
`${title}${gap}${theme.fg("accent", args.workflow === true ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${
|
|
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))}` : ""}`,
|
|
749
694
|
0,
|
|
750
695
|
0,
|
|
751
696
|
);
|
|
@@ -767,15 +712,22 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
767
712
|
|
|
768
713
|
};
|
|
769
714
|
|
|
770
|
-
pi
|
|
715
|
+
registerPinnedTool(pi, tool);
|
|
771
716
|
|
|
772
|
-
pi.on("before_agent_start", (event) => {
|
|
717
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
773
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
|
+
}
|
|
774
725
|
const next = applyInjectionBlock({
|
|
775
726
|
systemPrompt: event.systemPrompt,
|
|
776
727
|
block: state.contextInjectionBlock ?? "",
|
|
728
|
+
replaceExisting: !projectTrusted || trustChanged,
|
|
777
729
|
});
|
|
778
|
-
return next ? { systemPrompt: next } : undefined;
|
|
730
|
+
return next !== undefined ? { systemPrompt: next } : undefined;
|
|
779
731
|
});
|
|
780
732
|
|
|
781
733
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
@@ -785,30 +737,38 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
785
737
|
// Structured sections let Pi append a transcript delta instead of replacing the
|
|
786
738
|
// cached system prompt. Set the section on every turn it applies: Pi rebuilds the
|
|
787
739
|
// options each turn, and an unset turn records a removal.
|
|
788
|
-
const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId));
|
|
740
|
+
const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId), recordedPromptSection(pi, "advertised_subagents"));
|
|
789
741
|
if (catalog) event.systemPromptOptions.sections.advertised_subagents = catalog;
|
|
790
742
|
});
|
|
791
743
|
|
|
792
744
|
registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager, waitToolConfig.defaultTimeoutMs, undefined, supervisorChannel.hasPendingRequests);
|
|
793
745
|
|
|
794
746
|
pi.on("agent_end", async (_event, ctx) => {
|
|
795
|
-
if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
|
|
796
|
-
const ownerSessionId = state.currentSessionId;
|
|
797
|
-
if (!ownerSessionId) return;
|
|
798
|
-
goalTurnId += 1;
|
|
799
747
|
try {
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
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);
|
|
752
|
+
} finally {
|
|
753
|
+
// Deliver notices after a failed drain without suppressing its rejection.
|
|
754
|
+
const ownerSessionId = state.currentSessionId;
|
|
755
|
+
if (ownerSessionId) {
|
|
756
|
+
goalTurnId += 1;
|
|
757
|
+
try {
|
|
758
|
+
const location = resolveMissionStoreLocation({ projectRoot: state.baseCwd, ...(config.missions ? { config: config.missions } : {}) });
|
|
759
|
+
const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
|
|
760
|
+
for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
|
|
761
|
+
handleSubagentControlNotice({
|
|
762
|
+
pi: parentWake,
|
|
763
|
+
state,
|
|
764
|
+
visibleControlNotices: new Set(),
|
|
765
|
+
details: { source: "goal", event: notice.event, noticeText: notice.message },
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
} catch (error) {
|
|
769
|
+
console.error("Failed to evaluate goal missions:", error);
|
|
770
|
+
}
|
|
809
771
|
}
|
|
810
|
-
} catch (error) {
|
|
811
|
-
console.error("Failed to evaluate goal missions:", error);
|
|
812
772
|
}
|
|
813
773
|
});
|
|
814
774
|
|
|
@@ -830,14 +790,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
830
790
|
});
|
|
831
791
|
const controlEventHandler = (payload: unknown) => {
|
|
832
792
|
handleSubagentControlNotice({
|
|
833
|
-
pi,
|
|
793
|
+
pi: parentWake,
|
|
834
794
|
state,
|
|
835
795
|
visibleControlNotices,
|
|
836
796
|
details: payload as SubagentControlMessageDetails,
|
|
837
797
|
});
|
|
838
798
|
};
|
|
839
799
|
const steeringNoticeHandler = (payload: unknown) => {
|
|
840
|
-
handleSubagentSteeringNotice({ pi, state, details: payload as SubagentSteeringMessageDetails });
|
|
800
|
+
handleSubagentSteeringNotice({ pi: parentWake, state, details: payload as SubagentSteeringMessageDetails });
|
|
841
801
|
};
|
|
842
802
|
const asyncStartedHandler = (payload: unknown) => {
|
|
843
803
|
handleStarted(payload);
|
|
@@ -847,6 +807,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
847
807
|
};
|
|
848
808
|
const asyncCompleteHandler = (payload: unknown) => {
|
|
849
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);
|
|
850
815
|
refreshResultDelivery();
|
|
851
816
|
refreshActiveAsyncCapacity();
|
|
852
817
|
scheduledRunManager.handleAsyncCompletion(payload);
|
|
@@ -927,6 +892,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
927
892
|
state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
|
|
928
893
|
state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
|
|
929
894
|
transitionResultDelivery();
|
|
895
|
+
owedResultRunIds.clear();
|
|
896
|
+
deliveredRunIds.clear();
|
|
930
897
|
state.parentSessionFile = ctx.sessionManager.getSessionFile();
|
|
931
898
|
state.trustedSessionFileRoot = state.parentSessionFile ? path.join(getAgentDir(), "sessions") : undefined;
|
|
932
899
|
state.trustedSessionRoots = [...new Set([
|
|
@@ -989,6 +956,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
989
956
|
// Snapshot the injectable-agent advertisement once per session so the
|
|
990
957
|
// appended `<available_subagents>` block stays byte-identical across turns
|
|
991
958
|
// and provider prompt caching is never invalidated mid-session.
|
|
959
|
+
let contextInjectionProjectTrusted: boolean | undefined;
|
|
992
960
|
const refreshContextInjectionSnapshot = (ctx: ExtensionContext) => {
|
|
993
961
|
if (process.env[SUBAGENT_CHILD_ENV] === "1") return;
|
|
994
962
|
try {
|
|
@@ -998,7 +966,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
998
966
|
state.contextInjectionUnknownNames = [];
|
|
999
967
|
return;
|
|
1000
968
|
}
|
|
1001
|
-
|
|
969
|
+
contextInjectionProjectTrusted = typeof ctx.isProjectTrusted !== "function" || ctx.isProjectTrusted() !== false;
|
|
970
|
+
const discovery = discoverAgentsAll(cwd, undefined, { projectTrusted: contextInjectionProjectTrusted });
|
|
1002
971
|
const mergedAgents = mergeAgentsForScope("both", discovery.user, discovery.project, discovery.builtin, discovery.package);
|
|
1003
972
|
const resolved = resolveInjectableAgents({
|
|
1004
973
|
agents: mergedAgents,
|
|
@@ -1019,11 +988,21 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1019
988
|
const runtimeEntry: SubagentRuntimeEntry = {
|
|
1020
989
|
sessionManager: null,
|
|
1021
990
|
visibleControlNotices,
|
|
1022
|
-
cleanup() {
|
|
991
|
+
cleanup(shutdownReason) {
|
|
1023
992
|
if (runtimeCleaned) return;
|
|
1024
993
|
runtimeCleaned = true;
|
|
994
|
+
programStatus.dispose(shutdownReason);
|
|
1025
995
|
releaseHostSessionLiveness();
|
|
1026
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
|
+
}
|
|
1027
1006
|
// Workflow continuations retain their launch context; abort them before
|
|
1028
1007
|
// teardown so a reload cannot launch through a stale context.
|
|
1029
1008
|
for (const controller of state.workflowControllers?.values() ?? []) {
|
|
@@ -1115,12 +1094,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1115
1094
|
};
|
|
1116
1095
|
|
|
1117
1096
|
pi.on("agent_start", () => {
|
|
1097
|
+
parentWake.agentStarted();
|
|
1118
1098
|
resumeWidgetsAfterCompaction();
|
|
1119
1099
|
herdrStatusBridge.agentStarted();
|
|
1100
|
+
programStatus.agentStarted();
|
|
1120
1101
|
});
|
|
1121
1102
|
|
|
1103
|
+
pi.on("message_start", (event) => completionNotifier.messageStarted(event.message));
|
|
1104
|
+
|
|
1122
1105
|
pi.on("agent_settled", () => {
|
|
1123
1106
|
resumeWidgetsAfterCompaction();
|
|
1107
|
+
programStatus.agentSettled();
|
|
1124
1108
|
});
|
|
1125
1109
|
|
|
1126
1110
|
pi.on("session_before_compact", (event) => {
|
|
@@ -1131,7 +1115,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1131
1115
|
if (event.reason !== "manual") return;
|
|
1132
1116
|
const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
|
|
1133
1117
|
if (!hasActiveAsyncWork || !withLastUiContext(() => true)) return;
|
|
1134
|
-
|
|
1118
|
+
parentWake.sendMessage(
|
|
1135
1119
|
{
|
|
1136
1120
|
customType: "subagent-compaction-resume",
|
|
1137
1121
|
content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
|
|
@@ -1142,6 +1126,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1142
1126
|
});
|
|
1143
1127
|
|
|
1144
1128
|
pi.on("session_start", (event, ctx) => {
|
|
1129
|
+
parentWake.bindSession(ctx);
|
|
1130
|
+
completionNotifier.bindSession(ctx.sessionManager);
|
|
1145
1131
|
installRuntime(ctx);
|
|
1146
1132
|
startSessionMaintenance();
|
|
1147
1133
|
scheduleModulePreload();
|
|
@@ -1155,7 +1141,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1155
1141
|
? registerPiWebSessionLiveness({
|
|
1156
1142
|
sessionId,
|
|
1157
1143
|
...(sessionFile ? { sessionFile } : {}),
|
|
1158
|
-
isActive: () => hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery(),
|
|
1144
|
+
isActive: () => owedResultRunIds.size > 0 || hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery() || parentWake.isPending(),
|
|
1159
1145
|
})
|
|
1160
1146
|
: { registered: false, release: () => {} };
|
|
1161
1147
|
releaseHostSessionLiveness = liveness.release;
|
|
@@ -1167,13 +1153,16 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
1167
1153
|
hasUI: ctx.hasUI === true,
|
|
1168
1154
|
runs: activeHerdrRuns(),
|
|
1169
1155
|
});
|
|
1156
|
+
programStatus.sessionStarted({ hasUI: ctx.hasUI === true, mode: ctx.mode });
|
|
1170
1157
|
rpcBridge.emitReady(ctx);
|
|
1171
1158
|
supervisorChannel.start();
|
|
1172
1159
|
supervisorChannel.activateTransport();
|
|
1173
1160
|
});
|
|
1174
1161
|
|
|
1175
|
-
pi.on("session_shutdown", async () => {
|
|
1176
|
-
|
|
1162
|
+
pi.on("session_shutdown", async (event) => {
|
|
1163
|
+
completionNotifier.sessionShutdown(event?.reason);
|
|
1164
|
+
parentWake.sessionShutdown(event?.reason);
|
|
1165
|
+
runtimeEntry.cleanup(event?.reason);
|
|
1177
1166
|
try {
|
|
1178
1167
|
await disposeChildSessions();
|
|
1179
1168
|
} catch (error) {
|
|
@@ -101,6 +101,9 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
|
|
|
101
101
|
if (params.workflowScriptPath !== undefined) {
|
|
102
102
|
return { ok: false, error: REMOVED_WORKFLOW_SCRIPT_PATH, mode: params.action === undefined ? "workflow" : "management" };
|
|
103
103
|
}
|
|
104
|
+
// Some MCP clients send the boolean branch of the workflow union as the string "true" (#2600).
|
|
105
|
+
// Coerce it here so no path can resolve it as a named resource or script file called "true".
|
|
106
|
+
if (params.workflow === "true") params = { ...params, workflow: true };
|
|
104
107
|
const workflow = params.workflow;
|
|
105
108
|
if (workflow !== undefined && workflow !== true && (typeof workflow !== "string" || !workflow.trim())) {
|
|
106
109
|
return { ok: false, error: "workflow must be true (the ```js workflow block in this reply), a script path containing '/', or a named workflow resource.", mode: "workflow" };
|