@xzzpig/pi-subagents 0.4.2 → 0.6.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 +172 -1
- package/README.md +8 -0
- package/agents/oracle.md +3 -1
- package/agents/reviewer.md +1 -0
- package/agents/scout.md +2 -2
- package/agents/worker.md +2 -1
- package/async-retention-discovery-worker.mjs +180 -0
- package/docs/agents.md +79 -2
- package/docs/configuration.md +42 -14
- package/docs/extension-api.md +45 -2
- package/docs/models.md +2 -0
- package/docs/observability.md +41 -5
- package/docs/tool-reference.md +38 -39
- package/docs/workflows.md +173 -3
- package/package.json +13 -10
- package/prompts/council.md +48 -0
- package/skills/council-mode/SKILL.md +230 -0
- package/skills/pi-subagents/SKILL.md +8 -4
- package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
- package/skills/pi-subagents/references/execution-controls.md +40 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
- package/src/agents/agent-management.ts +158 -357
- package/src/agents/agent-serializer.ts +4 -0
- package/src/agents/agents.ts +227 -53
- package/src/agents/builtin-names.ts +9 -0
- package/src/agents/runtime-agent-registry.ts +422 -0
- package/src/agents/skills.ts +1 -1
- package/src/api/agents.ts +7 -0
- package/src/api/external-job-provider.ts +186 -0
- package/src/api/preflight.ts +37 -9
- package/src/api/shared-types.ts +2 -0
- package/src/extension/config.ts +6 -3
- package/src/extension/context-injection.ts +118 -0
- package/src/extension/doctor.ts +15 -6
- package/src/extension/fanout-child.ts +2 -2
- package/src/extension/index.ts +224 -90
- package/src/extension/public-execution.ts +31 -2
- package/src/extension/rpc.ts +41 -1
- package/src/extension/schemas.ts +17 -37
- package/src/extension/tool-description.ts +35 -24
- package/src/inspectors/herdr/actions.ts +2 -2
- package/src/inspectors/herdr/inspector-runner.ts +2 -1
- package/src/inspectors/herdr/project-panes.ts +2 -2
- package/src/intercom/native-supervisor-channel.ts +32 -10
- package/src/missions/lifecycle.ts +6 -1
- package/src/missions/store.ts +4 -9
- package/src/missions/workflow-state.ts +2 -2
- package/src/profiles/profiles.ts +3 -1
- package/src/runs/background/active-run-index.ts +31 -8
- package/src/runs/background/async-execution.ts +70 -41
- package/src/runs/background/async-job-tracker.ts +24 -7
- package/src/runs/background/async-resume.ts +49 -16
- package/src/runs/background/async-retention.ts +886 -0
- package/src/runs/background/async-status-snapshot.ts +14 -5
- package/src/runs/background/async-status.ts +39 -53
- package/src/runs/background/auto-drain.ts +1 -0
- package/src/runs/background/chain-append.ts +3 -33
- package/src/runs/background/completion-dedupe.ts +5 -1
- package/src/runs/background/completion-replay.ts +22 -12
- package/src/runs/background/control-channel.ts +14 -68
- package/src/runs/background/fleet-view.ts +68 -19
- package/src/runs/background/index-segment.ts +59 -0
- package/src/runs/background/inspect-rpc.ts +443 -0
- package/src/runs/background/notify.ts +31 -5
- package/src/runs/background/result-files.ts +158 -90
- package/src/runs/background/result-watcher.ts +124 -20
- package/src/runs/background/resume-guidance.ts +8 -5
- package/src/runs/background/retained-children.ts +13 -3
- package/src/runs/background/run-id-query.ts +7 -0
- package/src/runs/background/run-id-resolver.ts +11 -9
- package/src/runs/background/run-status.ts +27 -18
- package/src/runs/background/scheduled-runs.ts +24 -4
- package/src/runs/background/stale-run-reconciler.ts +6 -3
- package/src/runs/background/steering.ts +11 -1
- package/src/runs/background/subagent-runner.ts +260 -144
- package/src/runs/background/subagent-wait.ts +17 -13
- package/src/runs/background/terminal-run-index.ts +138 -0
- package/src/runs/background/wait-completions.ts +21 -4
- package/src/runs/background/wait-subscriptions.ts +81 -2
- package/src/runs/background/wait-tool.ts +1 -0
- package/src/runs/foreground/async-steering-action.ts +21 -14
- package/src/runs/foreground/execution.ts +8 -2
- package/src/runs/foreground/subagent-executor.ts +816 -1593
- package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
- package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
- package/src/runs/shared/acceptance.ts +48 -5
- package/src/runs/shared/chain-outputs.ts +1 -3
- package/src/runs/shared/external-job-bridge.ts +444 -0
- package/src/runs/shared/external-job-runner.ts +286 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
- package/src/runs/shared/model-exclusions.ts +242 -0
- package/src/runs/shared/model-fallback.ts +153 -40
- package/src/runs/shared/orca-progress-tabs.ts +84 -22
- package/src/runs/shared/parallel-handoff.ts +46 -4
- package/src/runs/shared/parallel-utils.ts +4 -15
- package/src/runs/shared/permissions.ts +5 -1
- package/src/runs/shared/pi-args.ts +8 -1
- package/src/runs/shared/session-lease.ts +0 -6
- package/src/runs/shared/subagent-control.ts +51 -7
- package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
- package/src/runs/shared/workflow-graph.ts +1 -23
- package/src/runs/shared/worktree.ts +14 -2
- package/src/shared/atomic-json.ts +22 -2
- package/src/shared/capacity-resilient-json.ts +102 -0
- package/src/shared/completion-owner.ts +14 -0
- package/src/shared/file-system-retry.ts +49 -1
- package/src/shared/fork-context.ts +59 -1
- package/src/shared/model-info.ts +20 -0
- package/src/shared/prompt-resources.ts +0 -40
- package/src/shared/settings.ts +5 -29
- package/src/shared/types.ts +110 -26
- package/src/shared/utils.ts +8 -0
- package/src/shared/watch-strategy.ts +10 -0
- package/src/slash/slash-bridge.ts +2 -1
- package/src/slash/slash-commands.ts +47 -7
- package/src/slash/slash-live-state.ts +3 -3
- package/src/tui/fleet-status.ts +86 -1
- package/src/tui/fleet.ts +117 -16
- package/src/tui/render.ts +73 -3
- package/src/watchdog/change-signature.ts +1 -1
- package/src/watchdog/lsp-diagnostics.ts +1 -0
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +320 -79
- package/src/workflows/workflow-receipt.ts +140 -0
- package/src/runs/foreground/chain-clarify.ts +0 -1354
- package/src/runs/foreground/chain-execution.ts +0 -1581
package/src/extension/index.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
|
|
10
10
|
*
|
|
11
11
|
* Config file: ~/.pi/agent/extensions/subagent/config.json
|
|
12
|
-
* { "asyncByDefault": true, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
|
|
12
|
+
* { "asyncByDefault": true, "defaultSubagentContext": "fork", "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
@@ -19,10 +19,13 @@ import * as path from "node:path";
|
|
|
19
19
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
20
20
|
import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
21
21
|
import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
|
|
22
|
-
import { discoverAgents } from "../agents/agents.ts";
|
|
22
|
+
import { discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
|
|
23
|
+
import { mergeAgentsForScope } from "../agents/agent-selection.ts";
|
|
24
|
+
import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
|
|
23
25
|
import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
|
|
24
26
|
import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
|
|
25
27
|
import { resolveCurrentSessionId } from "../shared/session-identity.ts";
|
|
28
|
+
import { currentCompletionOwnerId } from "../shared/completion-owner.ts";
|
|
26
29
|
import { cleanupOldChainDirs } from "../shared/settings.ts";
|
|
27
30
|
import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
|
|
28
31
|
import { openSubagentFleet } from "../tui/fleet.ts";
|
|
@@ -31,7 +34,8 @@ import { createSubagentParamsSchema } from "./schemas.ts";
|
|
|
31
34
|
import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
32
35
|
import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
|
|
33
36
|
import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
|
|
34
|
-
import { cleanupResultIndexes } from "../runs/background/result-files.ts";
|
|
37
|
+
import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
|
|
38
|
+
import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
|
|
35
39
|
import { createResultWatcher } from "../runs/background/result-watcher.ts";
|
|
36
40
|
import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
|
|
37
41
|
import { registerSlashCommands } from "../slash/slash-commands.ts";
|
|
@@ -53,7 +57,8 @@ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/
|
|
|
53
57
|
import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
|
|
54
58
|
import { formatDuration, shortenPath } from "../shared/formatters.ts";
|
|
55
59
|
import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
|
|
56
|
-
import {
|
|
60
|
+
import { applyInjectionBlock, renderInjectionBlock, resolveInjectableAgents, SUBAGENT_INJECTION_MARKER } from "./context-injection.ts";
|
|
61
|
+
import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
|
|
57
62
|
import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
|
|
58
63
|
import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
|
|
59
64
|
import { resolveMissionStoreLocation } from "../missions/store.ts";
|
|
@@ -84,6 +89,37 @@ import {
|
|
|
84
89
|
export { loadConfig, resolveAsyncByDefault } from "./config.ts";
|
|
85
90
|
|
|
86
91
|
const SLOW_RELOAD_PHASE_MS = 250;
|
|
92
|
+
const RUNTIME_REGISTRY_STORE_KEY = "__piSubagentRuntimeRegistry";
|
|
93
|
+
|
|
94
|
+
interface SubagentRuntimeEntry {
|
|
95
|
+
cleanup(): void;
|
|
96
|
+
sessionManager: object | null;
|
|
97
|
+
visibleControlNotices: Set<string>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface SubagentRuntimeRegistry {
|
|
101
|
+
bySessionManager: WeakMap<object, SubagentRuntimeEntry>;
|
|
102
|
+
visibleControlNoticesBySessionManager: WeakMap<object, Set<string>>;
|
|
103
|
+
activeEntries: Set<SubagentRuntimeEntry>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getRuntimeRegistry(): SubagentRuntimeRegistry {
|
|
107
|
+
const globalStore = globalThis as Record<string, unknown>;
|
|
108
|
+
const existing = globalStore[RUNTIME_REGISTRY_STORE_KEY] as Partial<SubagentRuntimeRegistry> | undefined;
|
|
109
|
+
if (existing?.bySessionManager instanceof WeakMap && existing.activeEntries instanceof Set) {
|
|
110
|
+
if (!(existing.visibleControlNoticesBySessionManager instanceof WeakMap)) {
|
|
111
|
+
existing.visibleControlNoticesBySessionManager = new WeakMap();
|
|
112
|
+
}
|
|
113
|
+
return existing as SubagentRuntimeRegistry;
|
|
114
|
+
}
|
|
115
|
+
const registry: SubagentRuntimeRegistry = {
|
|
116
|
+
bySessionManager: new WeakMap(),
|
|
117
|
+
visibleControlNoticesBySessionManager: new WeakMap(),
|
|
118
|
+
activeEntries: new Set(),
|
|
119
|
+
};
|
|
120
|
+
globalStore[RUNTIME_REGISTRY_STORE_KEY] = registry;
|
|
121
|
+
return registry;
|
|
122
|
+
}
|
|
87
123
|
|
|
88
124
|
function logSlowPhase(label: string, startedAt: number): void {
|
|
89
125
|
const elapsed = Date.now() - startedAt;
|
|
@@ -358,16 +394,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
358
394
|
if (process.env[SUBAGENT_CHILD_ENV] === "1") {
|
|
359
395
|
return;
|
|
360
396
|
}
|
|
361
|
-
const
|
|
362
|
-
const runtimeCleanupStoreKey = "__piSubagentRuntimeCleanup";
|
|
363
|
-
const previousRuntimeCleanup = globalStore[runtimeCleanupStoreKey];
|
|
364
|
-
if (typeof previousRuntimeCleanup === "function") {
|
|
365
|
-
try {
|
|
366
|
-
previousRuntimeCleanup();
|
|
367
|
-
} catch {
|
|
368
|
-
// Best effort cleanup for stale timers from an older reload.
|
|
369
|
-
}
|
|
370
|
-
}
|
|
397
|
+
const runtimeRegistry = getRuntimeRegistry();
|
|
371
398
|
|
|
372
399
|
DIRS.results = ensureAccessibleDir(DIRS.results);
|
|
373
400
|
DIRS.async = ensureAccessibleDir(DIRS.async);
|
|
@@ -395,6 +422,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
395
422
|
const state: SubagentState = {
|
|
396
423
|
baseCwd: "",
|
|
397
424
|
currentSessionId: null,
|
|
425
|
+
completionOwnerId: currentCompletionOwnerId(),
|
|
398
426
|
artifactDirPreference: config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
|
|
399
427
|
...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
|
|
400
428
|
...(config.missions ? { missionStoreConfig: config.missions } : {}),
|
|
@@ -440,6 +468,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
440
468
|
: undefined;
|
|
441
469
|
let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
|
|
442
470
|
let goalTurnId = 0;
|
|
471
|
+
let parentSessionEnvValue: string | null = null;
|
|
443
472
|
const scheduledStoreRoot = config.scheduledRuns?.storeRoot === undefined ? undefined : resolveScheduledStoreRoot(config.scheduledRuns.storeRoot);
|
|
444
473
|
const scheduledRunManager = createScheduledRunManager({
|
|
445
474
|
config,
|
|
@@ -456,10 +485,30 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
456
485
|
},
|
|
457
486
|
resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
|
|
458
487
|
});
|
|
488
|
+
let refreshResultDelivery = () => {};
|
|
489
|
+
const hasResultDeliveryDemand = () => {
|
|
490
|
+
if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
|
|
491
|
+
if (state.foregroundControls.size > 0) return true;
|
|
492
|
+
if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
|
|
493
|
+
return missionObserverResultCandidateFiles(DIRS.results).length > 0;
|
|
494
|
+
};
|
|
495
|
+
const discoverAgentsForRuntime = (cwd: string, scope: AgentScope) => {
|
|
496
|
+
const discovered = discoverAgents(cwd, scope);
|
|
497
|
+
if (listRuntimeAgentConfigs(pi).length === 0) return discovered;
|
|
498
|
+
const all = discoverAgentsAll(cwd);
|
|
499
|
+
const configuredAgents: AgentConfig[] = [
|
|
500
|
+
...all.builtin,
|
|
501
|
+
...all.package,
|
|
502
|
+
...all.user,
|
|
503
|
+
...all.project,
|
|
504
|
+
];
|
|
505
|
+
return mergeRuntimeAgents(pi, discovered, configuredAgents);
|
|
506
|
+
};
|
|
459
507
|
const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
|
|
460
508
|
widgetEnabled: asyncWidgetEnabled,
|
|
509
|
+
onJobTerminal: () => refreshResultDelivery(),
|
|
461
510
|
});
|
|
462
|
-
const
|
|
511
|
+
const resultWatcher = createResultWatcher(
|
|
463
512
|
pi,
|
|
464
513
|
state,
|
|
465
514
|
DIRS.results,
|
|
@@ -468,23 +517,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
468
517
|
notifier: completionNotifier,
|
|
469
518
|
observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
|
|
470
519
|
observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
|
|
520
|
+
hasDeliveryDemand: hasResultDeliveryDemand,
|
|
471
521
|
deliverIntercomResults: config.intercomBridge?.resultDelivery === true,
|
|
522
|
+
resultScanLogging: config.resultScanLogging ?? "all",
|
|
472
523
|
},
|
|
473
524
|
);
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
525
|
+
const { startResultWatcher, primeExistingResults, stopResultWatcher } = resultWatcher;
|
|
526
|
+
refreshResultDelivery = resultWatcher.refreshResultDelivery;
|
|
527
|
+
const asyncRetentionAbort = new AbortController();
|
|
528
|
+
const asyncRetentionTimer = setTimeout(async () => {
|
|
529
|
+
try {
|
|
530
|
+
await cleanupAsyncRetention({
|
|
531
|
+
asyncDirRoot: DIRS.async,
|
|
532
|
+
resultsDir: DIRS.results,
|
|
533
|
+
signal: asyncRetentionAbort.signal,
|
|
534
|
+
protectedRunIds: new Set([
|
|
535
|
+
...state.asyncJobs.keys(),
|
|
536
|
+
...(state.workflowControllers?.keys() ?? []),
|
|
537
|
+
...scheduledRunManager.referencedAsyncRunIds(),
|
|
538
|
+
]),
|
|
539
|
+
});
|
|
540
|
+
} catch (error) {
|
|
541
|
+
console.error("Failed to clean retained async subagent state:", error);
|
|
542
|
+
}
|
|
543
|
+
}, ASYNC_RETENTION_DELAY_MS);
|
|
544
|
+
asyncRetentionTimer.unref?.();
|
|
488
545
|
|
|
489
546
|
const executor = createSubagentExecutor({
|
|
490
547
|
pi,
|
|
@@ -497,7 +554,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
497
554
|
tempArtifactsDir,
|
|
498
555
|
getSubagentSessionRoot,
|
|
499
556
|
expandTilde,
|
|
500
|
-
discoverAgents,
|
|
557
|
+
discoverAgents: discoverAgentsForRuntime,
|
|
558
|
+
activateSupervisorTransport: () => supervisorChannel.activateTransport(),
|
|
559
|
+
refreshResultDelivery: () => refreshResultDelivery(),
|
|
501
560
|
});
|
|
502
561
|
executorScheduled = executor.executeScheduled;
|
|
503
562
|
|
|
@@ -568,6 +627,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
568
627
|
|
|
569
628
|
const slashBridge = registerSlashSubagentBridge({
|
|
570
629
|
events: pi.events,
|
|
630
|
+
asyncByDefault,
|
|
571
631
|
getContext: () => state.lastUiContext,
|
|
572
632
|
execute: (id, params, signal, onUpdate, ctx) =>
|
|
573
633
|
executeSubagentCollapsed(id, params, signal, onUpdate, ctx),
|
|
@@ -592,11 +652,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
592
652
|
});
|
|
593
653
|
|
|
594
654
|
|
|
595
|
-
const parameters = createSubagentParamsSchema(
|
|
655
|
+
const parameters = createSubagentParamsSchema();
|
|
596
656
|
const tool: ToolDefinition<typeof parameters, Details> = {
|
|
597
657
|
name: "subagent",
|
|
598
658
|
label: "Subagent",
|
|
599
659
|
description: buildSubagentToolDescription(config),
|
|
660
|
+
...buildSubagentToolPromptMetadata(config),
|
|
600
661
|
parameters,
|
|
601
662
|
|
|
602
663
|
execute(id, params, signal, onUpdate, ctx) {
|
|
@@ -607,7 +668,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
607
668
|
const gap = " ".repeat(config.mainWindowRenderer?.horizontalSpacing ?? 1);
|
|
608
669
|
const title = theme.fg("toolTitle", theme.bold("subagent"));
|
|
609
670
|
if (args.action) {
|
|
610
|
-
const target = args.agent ||
|
|
671
|
+
const target = args.agent || "";
|
|
611
672
|
return new Text(
|
|
612
673
|
`${title}${gap}${args.action}${target ? `${gap}${theme.fg("accent", target)}` : ""}`,
|
|
613
674
|
0, 0,
|
|
@@ -667,22 +728,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
667
728
|
foregroundDetachShortcut: config.foregroundDetachShortcut,
|
|
668
729
|
});
|
|
669
730
|
|
|
670
|
-
|
|
671
|
-
const controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices";
|
|
672
|
-
const previousEventUnsubscribes = globalStore[eventUnsubscribeStoreKey];
|
|
673
|
-
if (Array.isArray(previousEventUnsubscribes)) {
|
|
674
|
-
for (const unsubscribe of previousEventUnsubscribes) {
|
|
675
|
-
if (typeof unsubscribe !== "function") continue;
|
|
676
|
-
try {
|
|
677
|
-
unsubscribe();
|
|
678
|
-
} catch {
|
|
679
|
-
// Best effort cleanup for stale handlers from an older reload.
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
const existingVisibleControlNotices = globalStore[controlNoticeSeenStoreKey];
|
|
684
|
-
const visibleControlNotices = existingVisibleControlNotices instanceof Set ? existingVisibleControlNotices as Set<string> : new Set<string>();
|
|
685
|
-
globalStore[controlNoticeSeenStoreKey] = visibleControlNotices;
|
|
731
|
+
let visibleControlNotices = new Set<string>();
|
|
686
732
|
const activeHerdrRuns = () => projectActiveHerdrRuns(state);
|
|
687
733
|
const herdrStatusBridge = registerHerdrStatusBridge({
|
|
688
734
|
events: pi.events,
|
|
@@ -704,10 +750,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
704
750
|
};
|
|
705
751
|
const asyncStartedHandler = (payload: unknown) => {
|
|
706
752
|
handleStarted(payload);
|
|
753
|
+
supervisorChannel.activateTransport();
|
|
754
|
+
refreshResultDelivery();
|
|
707
755
|
fleetStatus?.refresh();
|
|
708
756
|
};
|
|
709
757
|
const asyncCompleteHandler = (payload: unknown) => {
|
|
710
758
|
handleComplete(payload);
|
|
759
|
+
refreshResultDelivery();
|
|
711
760
|
refreshActiveAsyncCapacity();
|
|
712
761
|
scheduledRunManager.handleAsyncCompletion(payload);
|
|
713
762
|
fleetStatus?.refresh();
|
|
@@ -724,7 +773,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
724
773
|
herdrStatusBridge.dispose,
|
|
725
774
|
rpcBridge.dispose,
|
|
726
775
|
];
|
|
727
|
-
globalStore[eventUnsubscribeStoreKey] = eventUnsubscribes;
|
|
728
776
|
|
|
729
777
|
pi.on("tool_result", (event, ctx) => {
|
|
730
778
|
if (event.toolName !== "subagent") return;
|
|
@@ -802,6 +850,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
802
850
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
803
851
|
if (sessionId) {
|
|
804
852
|
process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId;
|
|
853
|
+
parentSessionEnvValue = sessionId;
|
|
805
854
|
}
|
|
806
855
|
}
|
|
807
856
|
state.lastUiContext = ctx;
|
|
@@ -840,6 +889,119 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
840
889
|
fleetStatus?.setContext(ctx);
|
|
841
890
|
};
|
|
842
891
|
|
|
892
|
+
// Snapshot the injectable-agent advertisement once per session so the
|
|
893
|
+
// appended `<available_subagents>` block stays byte-identical across turns
|
|
894
|
+
// and provider prompt caching is never invalidated mid-session.
|
|
895
|
+
const refreshContextInjectionSnapshot = (ctx: ExtensionContext) => {
|
|
896
|
+
if (process.env[SUBAGENT_CHILD_ENV] === "1") return;
|
|
897
|
+
try {
|
|
898
|
+
const cwd = ctx.cwd || state.baseCwd;
|
|
899
|
+
if (!cwd) {
|
|
900
|
+
state.contextInjectionBlock = "";
|
|
901
|
+
state.contextInjectionUnknownNames = [];
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
const discovery = discoverAgentsAll(cwd);
|
|
905
|
+
const mergedAgents = mergeAgentsForScope("both", discovery.user, discovery.project, discovery.builtin, discovery.package);
|
|
906
|
+
const resolved = resolveInjectableAgents({
|
|
907
|
+
agents: mergedAgents,
|
|
908
|
+
injectAgents: discovery.injectAgents,
|
|
909
|
+
capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(state.currentSessionId ?? undefined),
|
|
910
|
+
});
|
|
911
|
+
state.contextInjectionBlock = renderInjectionBlock(resolved.agents);
|
|
912
|
+
state.contextInjectionUnknownNames = resolved.unknownNames;
|
|
913
|
+
} catch (error) {
|
|
914
|
+
// Injection is a best-effort convenience; never break session startup.
|
|
915
|
+
state.contextInjectionBlock = "";
|
|
916
|
+
state.contextInjectionUnknownNames = [];
|
|
917
|
+
console.error("Failed to snapshot injectable subagents:", error);
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
let runtimeCleaned = false;
|
|
922
|
+
const runtimeEntry: SubagentRuntimeEntry = {
|
|
923
|
+
sessionManager: null,
|
|
924
|
+
visibleControlNotices,
|
|
925
|
+
cleanup() {
|
|
926
|
+
if (runtimeCleaned) return;
|
|
927
|
+
runtimeCleaned = true;
|
|
928
|
+
const shuttingDownParentSession = parentSessionEnvValue;
|
|
929
|
+
clearRuntimeAgentsForPi(pi);
|
|
930
|
+
clearTimeout(resultIndexCleanupTimer);
|
|
931
|
+
clearTimeout(asyncRetentionTimer);
|
|
932
|
+
asyncRetentionAbort.abort();
|
|
933
|
+
stopResultWatcher();
|
|
934
|
+
completionNotifier.dispose();
|
|
935
|
+
mainWatchdog.dispose();
|
|
936
|
+
scheduledRunManager.stop();
|
|
937
|
+
supervisorChannel.dispose();
|
|
938
|
+
waitSubscriptionManager.dispose();
|
|
939
|
+
fleetStatus?.dispose();
|
|
940
|
+
disposeAsyncJobTracker();
|
|
941
|
+
for (const timer of state.cleanupTimers.values()) clearTimeout(timer);
|
|
942
|
+
state.cleanupTimers.clear();
|
|
943
|
+
state.asyncJobs.clear();
|
|
944
|
+
for (const unsubscribe of eventUnsubscribes) {
|
|
945
|
+
try {
|
|
946
|
+
unsubscribe();
|
|
947
|
+
} catch {
|
|
948
|
+
// Best effort cleanup during shutdown or reload.
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
slashBridge.cancelAll();
|
|
952
|
+
slashBridge.dispose();
|
|
953
|
+
promptTemplateBridge.cancelAll();
|
|
954
|
+
promptTemplateBridge.dispose();
|
|
955
|
+
state.widgetsSuspended = false;
|
|
956
|
+
state.currentSessionId = null;
|
|
957
|
+
state.parentSessionFile = null;
|
|
958
|
+
parentSessionEnvValue = null;
|
|
959
|
+
if (shuttingDownParentSession && process.env[SUBAGENT_PARENT_SESSION_ENV] === shuttingDownParentSession) {
|
|
960
|
+
delete process.env[SUBAGENT_PARENT_SESSION_ENV];
|
|
961
|
+
}
|
|
962
|
+
if (runtimeEntry.sessionManager && runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
|
|
963
|
+
runtimeRegistry.bySessionManager.delete(runtimeEntry.sessionManager);
|
|
964
|
+
}
|
|
965
|
+
runtimeRegistry.activeEntries.delete(runtimeEntry);
|
|
966
|
+
if (runtimeRegistry.activeEntries.size === 0) clearSlashSnapshots();
|
|
967
|
+
try {
|
|
968
|
+
if (state.lastUiContext?.hasUI) state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
|
|
969
|
+
} catch (error) {
|
|
970
|
+
if (!isStaleExtensionContextError(error)) throw error;
|
|
971
|
+
}
|
|
972
|
+
state.lastUiContext = null;
|
|
973
|
+
},
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
const installRuntime = (ctx: ExtensionContext) => {
|
|
977
|
+
if (runtimeCleaned) {
|
|
978
|
+
throw new Error("Cannot restart a cleaned pi-subagents extension runtime; register a new extension instance.");
|
|
979
|
+
}
|
|
980
|
+
const sessionManager = ctx.sessionManager as object;
|
|
981
|
+
const previousRuntime = runtimeRegistry.bySessionManager.get(sessionManager);
|
|
982
|
+
const existingVisibleControlNotices = runtimeRegistry.visibleControlNoticesBySessionManager.get(sessionManager);
|
|
983
|
+
if (existingVisibleControlNotices) {
|
|
984
|
+
visibleControlNotices = existingVisibleControlNotices;
|
|
985
|
+
} else {
|
|
986
|
+
runtimeRegistry.visibleControlNoticesBySessionManager.set(sessionManager, visibleControlNotices);
|
|
987
|
+
}
|
|
988
|
+
runtimeEntry.visibleControlNotices = visibleControlNotices;
|
|
989
|
+
if (runtimeEntry.sessionManager && runtimeEntry.sessionManager !== sessionManager
|
|
990
|
+
&& runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
|
|
991
|
+
runtimeRegistry.bySessionManager.delete(runtimeEntry.sessionManager);
|
|
992
|
+
}
|
|
993
|
+
runtimeEntry.sessionManager = sessionManager;
|
|
994
|
+
runtimeRegistry.bySessionManager.set(sessionManager, runtimeEntry);
|
|
995
|
+
runtimeRegistry.activeEntries.add(runtimeEntry);
|
|
996
|
+
if (previousRuntime && previousRuntime !== runtimeEntry) {
|
|
997
|
+
try {
|
|
998
|
+
previousRuntime.cleanup();
|
|
999
|
+
} catch {
|
|
1000
|
+
// Best effort cleanup for stale resources from the replaced runtime.
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
|
|
843
1005
|
pi.on("agent_start", () => {
|
|
844
1006
|
resumeWidgetsAfterCompaction();
|
|
845
1007
|
herdrStatusBridge.agentStarted();
|
|
@@ -867,58 +1029,30 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
867
1029
|
});
|
|
868
1030
|
|
|
869
1031
|
pi.on("session_start", (event, ctx) => {
|
|
1032
|
+
installRuntime(ctx);
|
|
870
1033
|
const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
|
|
871
1034
|
resetSessionState(ctx, recovering);
|
|
1035
|
+
refreshContextInjectionSnapshot(ctx);
|
|
872
1036
|
herdrStatusBridge.sessionStarted({
|
|
873
1037
|
hasUI: ctx.hasUI === true,
|
|
874
1038
|
runs: activeHerdrRuns(),
|
|
875
1039
|
});
|
|
876
1040
|
rpcBridge.emitReady(ctx);
|
|
877
1041
|
supervisorChannel.start();
|
|
1042
|
+
supervisorChannel.activateTransport();
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
pi.on("before_agent_start", (event) => {
|
|
1046
|
+
if (process.env[SUBAGENT_CHILD_ENV] === "1") return undefined;
|
|
1047
|
+
const next = applyInjectionBlock({
|
|
1048
|
+
systemPrompt: event.systemPrompt,
|
|
1049
|
+
block: state.contextInjectionBlock ?? "",
|
|
1050
|
+
});
|
|
1051
|
+
return next ? { systemPrompt: next } : undefined;
|
|
878
1052
|
});
|
|
879
1053
|
|
|
880
1054
|
pi.on("session_shutdown", async () => {
|
|
881
|
-
|
|
882
|
-
clearTimeout(resultIndexCleanupTimer);
|
|
883
|
-
stopResultWatcher();
|
|
884
|
-
state.currentSessionId = null;
|
|
885
|
-
state.parentSessionFile = null;
|
|
886
|
-
completionNotifier.dispose();
|
|
887
|
-
delete process.env[SUBAGENT_PARENT_SESSION_ENV];
|
|
888
|
-
for (const unsubscribe of eventUnsubscribes) {
|
|
889
|
-
try {
|
|
890
|
-
unsubscribe();
|
|
891
|
-
} catch {
|
|
892
|
-
// Best effort cleanup during shutdown.
|
|
893
|
-
}
|
|
894
|
-
}
|
|
895
|
-
if (globalStore[eventUnsubscribeStoreKey] === eventUnsubscribes) {
|
|
896
|
-
delete globalStore[eventUnsubscribeStoreKey];
|
|
897
|
-
}
|
|
898
|
-
scheduledRunManager.stop();
|
|
899
|
-
disposeAsyncJobTracker();
|
|
900
|
-
for (const timer of state.cleanupTimers.values()) {
|
|
901
|
-
clearTimeout(timer);
|
|
902
|
-
}
|
|
903
|
-
state.cleanupTimers.clear();
|
|
904
|
-
state.asyncJobs.clear();
|
|
905
|
-
clearSlashSnapshots();
|
|
906
|
-
slashBridge.cancelAll();
|
|
907
|
-
slashBridge.dispose();
|
|
908
|
-
promptTemplateBridge.cancelAll();
|
|
909
|
-
promptTemplateBridge.dispose();
|
|
910
|
-
supervisorChannel.dispose();
|
|
911
|
-
fleetStatus?.dispose();
|
|
912
|
-
if (globalStore[runtimeCleanupStoreKey] === runtimeCleanup) {
|
|
913
|
-
delete globalStore[runtimeCleanupStoreKey];
|
|
914
|
-
}
|
|
915
|
-
try {
|
|
916
|
-
if (state.lastUiContext?.hasUI) {
|
|
917
|
-
state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
|
|
918
|
-
}
|
|
919
|
-
} catch (error) {
|
|
920
|
-
if (!isStaleExtensionContextError(error)) throw error;
|
|
921
|
-
}
|
|
1055
|
+
runtimeEntry.cleanup();
|
|
922
1056
|
await herdrStatusBridge.flush();
|
|
923
1057
|
});
|
|
924
1058
|
}
|
|
@@ -8,7 +8,12 @@ export interface PublicSubagentExecutionParams {
|
|
|
8
8
|
parallel?: unknown;
|
|
9
9
|
concurrency?: unknown;
|
|
10
10
|
chainDir?: unknown;
|
|
11
|
+
chainName?: unknown;
|
|
12
|
+
config?: unknown;
|
|
11
13
|
workflowScript?: unknown;
|
|
14
|
+
isolation?: unknown;
|
|
15
|
+
worktree?: unknown;
|
|
16
|
+
async?: unknown;
|
|
12
17
|
output?: unknown;
|
|
13
18
|
resume?: unknown;
|
|
14
19
|
clarify?: unknown;
|
|
@@ -26,7 +31,18 @@ export type PublicSubagentExecutionNormalization<T> =
|
|
|
26
31
|
* Enforce the public execution cutover before requests reach the executor.
|
|
27
32
|
* Internal runs.run children and structured owned delegation bypass this boundary.
|
|
28
33
|
*/
|
|
29
|
-
export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T): PublicSubagentExecutionNormalization<T> {
|
|
34
|
+
export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T, options: { asyncByDefault?: boolean } = {}): PublicSubagentExecutionNormalization<T> {
|
|
35
|
+
if (params.isolation !== undefined) {
|
|
36
|
+
if (params.isolation !== "none" && params.isolation !== "worktree") {
|
|
37
|
+
return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
|
|
38
|
+
}
|
|
39
|
+
const isolationWorktree = params.isolation === "worktree";
|
|
40
|
+
if (params.worktree !== undefined && params.worktree !== isolationWorktree) {
|
|
41
|
+
return { ok: false, error: `isolation '${params.isolation}' conflicts with worktree: ${String(params.worktree)}.`, mode: params.workflowScript !== undefined ? "workflow" : "management" };
|
|
42
|
+
}
|
|
43
|
+
const { isolation: _isolation, ...normalizedParams } = params;
|
|
44
|
+
params = { ...normalizedParams, worktree: isolationWorktree } as T;
|
|
45
|
+
}
|
|
30
46
|
if (params.runFanoutBudget !== undefined || params.runFanoutAdmitted !== undefined) {
|
|
31
47
|
return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
|
|
32
48
|
}
|
|
@@ -38,6 +54,12 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
|
|
|
38
54
|
if (params.clarify !== undefined) {
|
|
39
55
|
return { ok: false, error: "Public workflowScript execution does not support clarify UI.", mode: "workflow" };
|
|
40
56
|
}
|
|
57
|
+
if (params.chainName !== undefined) {
|
|
58
|
+
return { ok: false, error: "Durable chain management was removed; use workflowScript or /prompt-workflow for repeatable workflows.", mode: "management" };
|
|
59
|
+
}
|
|
60
|
+
if (params.config && typeof params.config === "object" && !Array.isArray(params.config) && Object.prototype.hasOwnProperty.call(params.config, "steps")) {
|
|
61
|
+
return { ok: false, error: "Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", mode: "management" };
|
|
62
|
+
}
|
|
41
63
|
if (params.resume !== undefined) {
|
|
42
64
|
return { ok: false, error: "Top-level resume execution is not available. Put resume on a workflowScript runs.run/runs.all item.", mode: "workflow" };
|
|
43
65
|
}
|
|
@@ -47,6 +69,12 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
|
|
|
47
69
|
}
|
|
48
70
|
if (normalizedAction !== undefined) {
|
|
49
71
|
const legacyAction = normalizedAction.toLowerCase();
|
|
72
|
+
if (legacyAction === "append-step") {
|
|
73
|
+
return { ok: false, error: "Legacy append-step control was removed from the public subagent tool; use current workflowScript orchestration.", mode: "management" };
|
|
74
|
+
}
|
|
75
|
+
if (legacyAction === "approve-checkpoint" || legacyAction === "reject-checkpoint") {
|
|
76
|
+
return { ok: false, error: "Legacy checkpoint approval controls were removed from the public subagent tool; use current workflowScript orchestration.", mode: "management" };
|
|
77
|
+
}
|
|
50
78
|
if (legacyAction === "single") {
|
|
51
79
|
return { ok: false, error: "action='single' is not supported. Omit action and pass { agent, task } for one child.", mode: "workflow" };
|
|
52
80
|
}
|
|
@@ -71,7 +99,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
|
|
|
71
99
|
return { ok: true, params: { ...params, action: normalizedAction } };
|
|
72
100
|
}
|
|
73
101
|
if (params.step !== undefined) {
|
|
74
|
-
return { ok: false, error: "step is
|
|
102
|
+
return { ok: false, error: "step is not a public execution field; use workflowScript for orchestration.", mode: "workflow" };
|
|
75
103
|
}
|
|
76
104
|
if (params.workflowScript !== undefined && (params.agent !== undefined || params.task !== undefined)) {
|
|
77
105
|
return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript.", mode: "workflow" };
|
|
@@ -93,6 +121,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
|
|
|
93
121
|
ok: true,
|
|
94
122
|
params: {
|
|
95
123
|
...workflowDefaults,
|
|
124
|
+
...(params.async === undefined && options.asyncByDefault === false ? { async: false } : {}),
|
|
96
125
|
workflowScript: `console.info("Converted structured single-child request to workflow runs.run('main', ...)."); return runs.run("main", ${JSON.stringify(child)})`,
|
|
97
126
|
} as T,
|
|
98
127
|
};
|
package/src/extension/rpc.ts
CHANGED
|
@@ -27,7 +27,7 @@ export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
|
|
|
27
27
|
export const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
|
|
28
28
|
export const SUBAGENT_RPC_REPLY_EVENT_PREFIX = "subagents:rpc:v1:reply:";
|
|
29
29
|
|
|
30
|
-
export const SUBAGENT_RPC_METHODS = ["ping", "status", "spawn", "steer", "interrupt", "stop", "resume"] as const;
|
|
30
|
+
export const SUBAGENT_RPC_METHODS = ["ping", "status", "manage", "spawn", "steer", "interrupt", "stop", "resume"] as const;
|
|
31
31
|
export type SubagentRpcMethod = typeof SUBAGENT_RPC_METHODS[number];
|
|
32
32
|
|
|
33
33
|
export interface SubagentRpcRequestEnvelope {
|
|
@@ -58,6 +58,18 @@ export type SubagentRpcReplyEnvelope<T = unknown> = {
|
|
|
58
58
|
};
|
|
59
59
|
};
|
|
60
60
|
|
|
61
|
+
export const SUBAGENT_RPC_MANAGEMENT_ACTIONS = [
|
|
62
|
+
"schedule.list",
|
|
63
|
+
"schedule.show",
|
|
64
|
+
"schedule.history",
|
|
65
|
+
"schedule.pause",
|
|
66
|
+
"schedule.resume",
|
|
67
|
+
"schedule.run",
|
|
68
|
+
"schedule.delete",
|
|
69
|
+
] as const;
|
|
70
|
+
|
|
71
|
+
type SubagentRpcManagementAction = typeof SUBAGENT_RPC_MANAGEMENT_ACTIONS[number];
|
|
72
|
+
|
|
61
73
|
type SubagentRpcErrorCode =
|
|
62
74
|
| "invalid_request"
|
|
63
75
|
| "invalid_params"
|
|
@@ -375,6 +387,7 @@ function pingData(ctx: ExtensionContext | null) {
|
|
|
375
387
|
methods: [...SUBAGENT_RPC_METHODS],
|
|
376
388
|
capabilities: {
|
|
377
389
|
status: true,
|
|
390
|
+
managementActions: [...SUBAGENT_RPC_MANAGEMENT_ACTIONS],
|
|
378
391
|
fleetStatus: { version: 1 },
|
|
379
392
|
asyncStatusSnapshot: { kind: ASYNC_STATUS_SNAPSHOT_KIND, version: ASYNC_STATUS_SNAPSHOT_VERSION },
|
|
380
393
|
asyncSpawn: true,
|
|
@@ -412,6 +425,30 @@ async function executeChecked(
|
|
|
412
425
|
return dataFromToolResult(result);
|
|
413
426
|
}
|
|
414
427
|
|
|
428
|
+
function manageParams(params: unknown): SubagentParamsLike {
|
|
429
|
+
const input = assertRecordParams(params, "manage");
|
|
430
|
+
if (typeof input.action !== "string" || !(SUBAGENT_RPC_MANAGEMENT_ACTIONS as readonly string[]).includes(input.action)) {
|
|
431
|
+
throw new SubagentRpcError(
|
|
432
|
+
"invalid_params",
|
|
433
|
+
`RPC manage action must be one of: ${SUBAGENT_RPC_MANAGEMENT_ACTIONS.join(", ")}.`,
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
if (input.id !== undefined && (typeof input.id !== "string" || !input.id.trim())) {
|
|
437
|
+
throw new SubagentRpcError("invalid_params", "RPC manage id must be a non-empty string.");
|
|
438
|
+
}
|
|
439
|
+
const action = input.action as SubagentRpcManagementAction;
|
|
440
|
+
const requiresId = action !== "schedule.list";
|
|
441
|
+
if (requiresId && typeof input.id !== "string") {
|
|
442
|
+
throw new SubagentRpcError("invalid_params", `RPC manage ${action} requires id.`);
|
|
443
|
+
}
|
|
444
|
+
const output: SubagentParamsLike = {
|
|
445
|
+
action,
|
|
446
|
+
...(typeof input.id === "string" ? { id: input.id.trim() } : {}),
|
|
447
|
+
};
|
|
448
|
+
assertSubagentParams(output, "RPC manage params");
|
|
449
|
+
return output;
|
|
450
|
+
}
|
|
451
|
+
|
|
415
452
|
function spawnParams(params: unknown): SubagentParamsLike {
|
|
416
453
|
const input = assertRecordParams(params, "spawn");
|
|
417
454
|
const normalized = normalizePublicSubagentExecution(input);
|
|
@@ -535,6 +572,9 @@ async function handleRequest(
|
|
|
535
572
|
if (request.method === "ping") return pingData(ctx);
|
|
536
573
|
if (!ctx) throw new SubagentRpcError("no_active_session", "No active extension context for subagent RPC.");
|
|
537
574
|
|
|
575
|
+
if (request.method === "manage") {
|
|
576
|
+
return executeChecked(options, ctx, request.requestId, request.method, manageParams(request.params));
|
|
577
|
+
}
|
|
538
578
|
if (request.method === "spawn") {
|
|
539
579
|
return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params));
|
|
540
580
|
}
|