@xzzpig/pi-subagents 0.4.1 → 0.5.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 +175 -0
- package/README.md +4 -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 +41 -3
- package/docs/configuration.md +41 -13
- package/docs/extension-api.md +65 -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 +14 -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 +471 -377
- package/src/agents/agent-serializer.ts +2 -0
- package/src/agents/agents.ts +186 -44
- package/src/agents/builtin-names.ts +9 -0
- package/src/agents/runtime-agent-registry.ts +418 -0
- package/src/agents/skills.ts +1 -1
- package/src/api/agent-management.ts +9 -0
- package/src/api/agents.ts +7 -0
- package/src/api/external-job-provider.ts +186 -0
- package/src/api/preflight.ts +45 -13
- package/src/api/shared-types.ts +2 -0
- package/src/extension/config.ts +6 -3
- package/src/extension/doctor.ts +4 -6
- package/src/extension/fanout-child.ts +2 -2
- package/src/extension/index.ts +183 -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 +104 -71
- 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 +106 -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/api/preflight.ts
CHANGED
|
@@ -2,11 +2,11 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { discoverAgents, discoverAgentsAll, resolveAgentName, type AgentConfig, type AgentScope, type AgentSource } from "../agents/agents.ts";
|
|
5
|
+
import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, resolveAgentName, type AgentConfig, type AgentScope, type AgentSource } from "../agents/agents.ts";
|
|
6
6
|
import { resolveExecutionAgentScope } from "../agents/agent-scope.ts";
|
|
7
7
|
import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../agents/skills.ts";
|
|
8
8
|
import { buildAgentMemoryInjection } from "../agents/agent-memory.ts";
|
|
9
|
-
import { buildModelCandidates, resolveEffectiveSubagentModel, type AvailableModelInfo, type ParentModel } from "../runs/shared/model-fallback.ts";
|
|
9
|
+
import { buildModelCandidates, inheritsParentModel, resolveEffectiveSubagentModel, type AvailableModelInfo, type ParentModel } from "../runs/shared/model-fallback.ts";
|
|
10
10
|
import { applyThinkingSuffix, resolvePiLaunchToolPlan, type PiLaunchToolPlan } from "../runs/shared/pi-args.ts";
|
|
11
11
|
import { injectOutputPathSystemPrompt, normalizeSingleOutputOverride, resolveSingleOutputPath } from "../runs/shared/single-output.ts";
|
|
12
12
|
import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
|
|
@@ -17,6 +17,8 @@ import { appendTurnBudgetSystemPrompt } from "../runs/shared/turn-budget.ts";
|
|
|
17
17
|
import type { ResolvedTurnBudget } from "../shared/types.ts";
|
|
18
18
|
import type { ResolvedMcpDirectToolSelection } from "../runs/shared/mcp-direct-tool-allowlist.ts";
|
|
19
19
|
import { resolveStepBehavior } from "../shared/settings.ts";
|
|
20
|
+
import { canPreferForkFromSnapshot, resolveSubagentLaunchContext } from "../shared/fork-context.ts";
|
|
21
|
+
import { loadConfig } from "../extension/config.ts";
|
|
20
22
|
import { agentDefinitionDigest, AGENT_DEFINITION_PROJECTION_VERSION, launchBindingDigest } from "../shared/launch-contract.ts";
|
|
21
23
|
import { DIRS, TEMP_ROOT_DIR } from "../shared/types.ts";
|
|
22
24
|
import { processTerminalCandidatePath, processTerminalPath } from "../runs/background/process-terminal.ts";
|
|
@@ -60,6 +62,8 @@ export interface SubagentLaunchContractInput {
|
|
|
60
62
|
artifacts?: boolean;
|
|
61
63
|
artifactDir?: ArtifactDirPreference;
|
|
62
64
|
parentSessionFile?: string | null;
|
|
65
|
+
/** Current parent leaf required before an implicit `defaultContext: fork` stays `fork`. */
|
|
66
|
+
parentLeafId?: string | null;
|
|
63
67
|
sessionRoot?: string;
|
|
64
68
|
sessionDir?: string;
|
|
65
69
|
runId?: string;
|
|
@@ -163,11 +167,15 @@ export type SubagentLaunchContractResult =
|
|
|
163
167
|
|
|
164
168
|
function packageVersion(): string {
|
|
165
169
|
const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
170
|
+
try {
|
|
171
|
+
const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
|
|
172
|
+
if (typeof parsed.version !== "string" || !parsed.version.trim()) {
|
|
173
|
+
throw new Error("version must be a non-empty string.");
|
|
174
|
+
}
|
|
175
|
+
return parsed.version;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
throw new Error(`Invalid package version in '${packagePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
169
178
|
}
|
|
170
|
-
return parsed.version;
|
|
171
179
|
}
|
|
172
180
|
|
|
173
181
|
function stableJson(value: unknown): string {
|
|
@@ -190,6 +198,18 @@ function normalizeAvailableModels(models: SubagentLaunchContractInput["available
|
|
|
190
198
|
return (models ?? []).map((model) => ({ ...model, fullId: model.fullId ?? `${model.provider}/${model.id}` }));
|
|
191
199
|
}
|
|
192
200
|
|
|
201
|
+
function resolveLaunchContractContext(input: SubagentLaunchContractInput, agent: AgentConfig): "fresh" | "fork" {
|
|
202
|
+
return resolveSubagentLaunchContext({
|
|
203
|
+
explicitContext: input.context,
|
|
204
|
+
agentDefaultContext: agent.defaultContext,
|
|
205
|
+
defaultSubagentContext: loadConfig().defaultSubagentContext,
|
|
206
|
+
canUseImplicitFork: canPreferForkFromSnapshot({
|
|
207
|
+
parentSessionFile: input.parentSessionFile,
|
|
208
|
+
leafId: input.parentLeafId,
|
|
209
|
+
}),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
193
213
|
function candidateList(inputAgent: string, selected: AgentConfig | undefined, cwd: string): SubagentLaunchContractAgentCandidate[] {
|
|
194
214
|
const all = discoverAgentsAll(cwd);
|
|
195
215
|
return [...all.builtin, ...all.package, ...all.user, ...all.project]
|
|
@@ -222,12 +242,17 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
222
242
|
if (input.artifactDir !== undefined && input.artifactDir !== "project" && input.artifactDir !== "session" && input.artifactDir !== "temp") {
|
|
223
243
|
return { ok: false, code: "invalid_artifact_dir", message: `Unsupported artifactDir '${String(input.artifactDir)}'; expected 'project', 'session', or 'temp'.`, diagnostics };
|
|
224
244
|
}
|
|
225
|
-
if (input.context === "fork") {
|
|
226
|
-
diagnostics.push({ code: "host_required", severity: "host-required", message: "Exact fork session branching and fork-thinking downgrade checks require Pi host session and model-registry snapshots." });
|
|
227
|
-
}
|
|
228
245
|
const scope = resolveExecutionAgentScope(input.agentScope);
|
|
229
246
|
const discovered = discoverAgents(effectiveCwd, scope);
|
|
230
247
|
const resolvedAgent = resolveAgentName(input.agent, discovered.agents);
|
|
248
|
+
const ambiguousCandidates = resolvedAgent.error
|
|
249
|
+
? discovered.agents.filter((agent) => resolveAgentName(input.agent, [agent]).agent)
|
|
250
|
+
: resolvedAgent.agent;
|
|
251
|
+
const invalidAgent = findBlockingAgentDiagnostic(input.agent, ambiguousCandidates, discovered.agentDiagnostics);
|
|
252
|
+
if (invalidAgent) {
|
|
253
|
+
const message = `Agent '${input.agent}' has invalid configuration: ${invalidAgent.error}`;
|
|
254
|
+
return { ok: false, code: "missing_agent", message, diagnostics: [{ code: "missing_agent", severity: "error", message }] };
|
|
255
|
+
}
|
|
231
256
|
if (resolvedAgent.error) {
|
|
232
257
|
return { ok: false, code: "ambiguous_agent", message: resolvedAgent.error, diagnostics };
|
|
233
258
|
}
|
|
@@ -235,6 +260,10 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
235
260
|
return { ok: false, code: "missing_agent", message: `Unknown agent: ${input.agent}`, diagnostics };
|
|
236
261
|
}
|
|
237
262
|
const agent = resolvedAgent.agent;
|
|
263
|
+
const context = resolveLaunchContractContext(input, agent);
|
|
264
|
+
if (context === "fork") {
|
|
265
|
+
diagnostics.push({ code: "host_required", severity: "host-required", message: "Exact fork session branching and fork-thinking downgrade checks require Pi host session and model-registry snapshots." });
|
|
266
|
+
}
|
|
238
267
|
const effectiveCapabilityCeiling = intersectSubagentCapabilityCeilings(input.capabilityCeiling, input.inheritedCapabilityCeiling);
|
|
239
268
|
const restrictionMessage = capabilityCeilingAgentRestrictionMessage(agent.name, effectiveCapabilityCeiling);
|
|
240
269
|
if (restrictionMessage) return { ok: false, code: "restricted_agent", message: restrictionMessage, diagnostics };
|
|
@@ -260,7 +289,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
260
289
|
}
|
|
261
290
|
if (resolvedSkills.missing.length > 0) diagnostics.push({ code: "missing_skill", severity: "error", message: `Missing skills: ${resolvedSkills.missing.join(", ")}` });
|
|
262
291
|
|
|
263
|
-
const externalRunner = agent.runner?.type === "external-cli";
|
|
292
|
+
const externalRunner = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job";
|
|
264
293
|
const availableModels = normalizeAvailableModels(input.availableModels);
|
|
265
294
|
const preferredProvider = input.preferredProvider ?? input.parentModel?.provider;
|
|
266
295
|
const primaryModel = externalRunner
|
|
@@ -270,7 +299,10 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
270
299
|
const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinkingConfig, input.thinking !== undefined);
|
|
271
300
|
const modelCandidates = externalRunner
|
|
272
301
|
? []
|
|
273
|
-
: buildModelCandidates(primaryModel, agent.fallbackModels, availableModels, preferredProvider, {
|
|
302
|
+
: buildModelCandidates(primaryModel, agent.fallbackModels, availableModels, preferredProvider, {
|
|
303
|
+
scope: discovered.modelScope,
|
|
304
|
+
primaryModelFromParent: inheritsParentModel(input.model, agent.model, input.parentModel),
|
|
305
|
+
})
|
|
274
306
|
.map((candidate) => applyThinkingSuffix(candidate, effectiveThinkingConfig, input.thinking !== undefined) ?? candidate);
|
|
275
307
|
let toolPlan: PiLaunchToolPlan;
|
|
276
308
|
try {
|
|
@@ -335,7 +367,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
335
367
|
definitionDigest,
|
|
336
368
|
shadowedCandidates,
|
|
337
369
|
},
|
|
338
|
-
context
|
|
370
|
+
context,
|
|
339
371
|
...(model ? { model } : {}),
|
|
340
372
|
modelCandidates,
|
|
341
373
|
...(resolveEffectiveThinking(model, effectiveThinkingConfig) ? { thinking: resolveEffectiveThinking(model, effectiveThinkingConfig) } : {}),
|
|
@@ -401,7 +433,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
|
|
|
401
433
|
extensions: toolPlan.extensionArgs,
|
|
402
434
|
mcpDirectTools: toolPlan.effectiveMcpTools,
|
|
403
435
|
...(outputPath ? { outputPath } : {}),
|
|
404
|
-
outputMode:
|
|
436
|
+
outputMode: behavior.outputMode,
|
|
405
437
|
...(input.outputSchema ? { structuredOutputSchema: input.outputSchema } : {}),
|
|
406
438
|
}),
|
|
407
439
|
};
|
package/src/api/shared-types.ts
CHANGED
package/src/extension/config.ts
CHANGED
|
@@ -94,6 +94,9 @@ function validateMainWindowRendererConfig(value: unknown): void {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
function validateConfig(config: Record<string, unknown>): void {
|
|
97
|
+
if (config.defaultSubagentContext !== undefined && config.defaultSubagentContext !== "fresh" && config.defaultSubagentContext !== "fork") {
|
|
98
|
+
throw new Error('config.defaultSubagentContext must be "fresh" or "fork"');
|
|
99
|
+
}
|
|
97
100
|
if (config.foregroundDetachShortcut !== undefined
|
|
98
101
|
&& (typeof config.foregroundDetachShortcut !== "string" || !isValidKeyId(config.foregroundDetachShortcut))) {
|
|
99
102
|
throw new Error("config.foregroundDetachShortcut must be a valid keybinding string such as \"ctrl+b\"");
|
|
@@ -101,15 +104,15 @@ function validateConfig(config: Record<string, unknown>): void {
|
|
|
101
104
|
if (config.artifactDir !== undefined && !ARTIFACT_DIR_PREFERENCES.has(config.artifactDir as ArtifactDirPreference)) {
|
|
102
105
|
throw new Error(`config.artifactDir must be "project", "session", or "temp"`);
|
|
103
106
|
}
|
|
104
|
-
if (config.legacyChainControls !== undefined && typeof config.legacyChainControls !== "boolean") {
|
|
105
|
-
throw new Error("config.legacyChainControls must be a boolean");
|
|
106
|
-
}
|
|
107
107
|
if (config.maxActiveAsyncRunsPerSession !== undefined
|
|
108
108
|
&& (typeof config.maxActiveAsyncRunsPerSession !== "number"
|
|
109
109
|
|| !Number.isInteger(config.maxActiveAsyncRunsPerSession)
|
|
110
110
|
|| config.maxActiveAsyncRunsPerSession < 0)) {
|
|
111
111
|
throw new Error("config.maxActiveAsyncRunsPerSession must be a non-negative integer");
|
|
112
112
|
}
|
|
113
|
+
if (config.resultScanLogging !== undefined && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
|
|
114
|
+
throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
|
|
115
|
+
}
|
|
113
116
|
validateMissionStoreConfig(config.missions);
|
|
114
117
|
validateAuthorityPolicy(config.authorityPolicy);
|
|
115
118
|
validatePermissionConfig(config.permissions);
|
package/src/extension/doctor.ts
CHANGED
|
@@ -134,21 +134,19 @@ function formatSessionLines(input: DoctorReportInput): string[] {
|
|
|
134
134
|
|
|
135
135
|
function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
|
|
136
136
|
return [
|
|
137
|
-
lineFromCheck("agents
|
|
137
|
+
lineFromCheck("agents", () => {
|
|
138
138
|
const discovered = deps.discoverAgentsAll(input.cwd);
|
|
139
139
|
const agentCounts = {
|
|
140
140
|
builtin: discovered.builtin.length,
|
|
141
141
|
package: discovered.package?.length ?? 0,
|
|
142
142
|
user: discovered.user.length,
|
|
143
143
|
project: discovered.project.length,
|
|
144
|
+
runtime: 0,
|
|
144
145
|
};
|
|
145
|
-
const
|
|
146
|
-
counts[chain.source] += 1;
|
|
147
|
-
return counts;
|
|
148
|
-
}, { builtin: 0, package: 0, user: 0, project: 0 });
|
|
146
|
+
const diagnostics = discovered.agentDiagnostics ?? [];
|
|
149
147
|
return [
|
|
150
148
|
`- agents: total ${agentCounts.builtin + agentCounts.package + agentCounts.user + agentCounts.project} (${formatSourceCounts(agentCounts)})`,
|
|
151
|
-
`-
|
|
149
|
+
...diagnostics.map((diagnostic) => `- invalid agent ${diagnostic.name ?? diagnostic.filePath} (${diagnostic.source}): ${diagnostic.error}`),
|
|
152
150
|
].join("\n");
|
|
153
151
|
}),
|
|
154
152
|
lineFromCheck("skills", () => {
|
|
@@ -171,13 +171,13 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI):
|
|
|
171
171
|
allowMutatingManagementActions: false,
|
|
172
172
|
});
|
|
173
173
|
|
|
174
|
-
const params = createSubagentParamsSchema(
|
|
174
|
+
const params = createSubagentParamsSchema();
|
|
175
175
|
const tool: ToolDefinition<typeof params, Details> = {
|
|
176
176
|
name: "subagent",
|
|
177
177
|
label: "Subagent",
|
|
178
178
|
description: [
|
|
179
179
|
"Delegate to subagents from child-safe fanout mode.",
|
|
180
|
-
|
|
180
|
+
"Allowed management/control actions: list, get, status, interrupt, resume, steer, doctor.",
|
|
181
181
|
"Mutating management actions (create, update, delete, eject, disable, enable, reset, grant-spawn-budget) are blocked in this mode.",
|
|
182
182
|
].join("\n"),
|
|
183
183
|
parameters: params,
|
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,12 @@ 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 { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
|
|
23
24
|
import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
|
|
24
25
|
import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
|
|
25
26
|
import { resolveCurrentSessionId } from "../shared/session-identity.ts";
|
|
27
|
+
import { currentCompletionOwnerId } from "../shared/completion-owner.ts";
|
|
26
28
|
import { cleanupOldChainDirs } from "../shared/settings.ts";
|
|
27
29
|
import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
|
|
28
30
|
import { openSubagentFleet } from "../tui/fleet.ts";
|
|
@@ -31,7 +33,8 @@ import { createSubagentParamsSchema } from "./schemas.ts";
|
|
|
31
33
|
import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
32
34
|
import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
|
|
33
35
|
import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
|
|
34
|
-
import { cleanupResultIndexes } from "../runs/background/result-files.ts";
|
|
36
|
+
import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
|
|
37
|
+
import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
|
|
35
38
|
import { createResultWatcher } from "../runs/background/result-watcher.ts";
|
|
36
39
|
import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
|
|
37
40
|
import { registerSlashCommands } from "../slash/slash-commands.ts";
|
|
@@ -53,7 +56,7 @@ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/
|
|
|
53
56
|
import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
|
|
54
57
|
import { formatDuration, shortenPath } from "../shared/formatters.ts";
|
|
55
58
|
import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
|
|
56
|
-
import { buildSubagentToolDescription } from "./tool-description.ts";
|
|
59
|
+
import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
|
|
57
60
|
import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
|
|
58
61
|
import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
|
|
59
62
|
import { resolveMissionStoreLocation } from "../missions/store.ts";
|
|
@@ -84,6 +87,37 @@ import {
|
|
|
84
87
|
export { loadConfig, resolveAsyncByDefault } from "./config.ts";
|
|
85
88
|
|
|
86
89
|
const SLOW_RELOAD_PHASE_MS = 250;
|
|
90
|
+
const RUNTIME_REGISTRY_STORE_KEY = "__piSubagentRuntimeRegistry";
|
|
91
|
+
|
|
92
|
+
interface SubagentRuntimeEntry {
|
|
93
|
+
cleanup(): void;
|
|
94
|
+
sessionManager: object | null;
|
|
95
|
+
visibleControlNotices: Set<string>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface SubagentRuntimeRegistry {
|
|
99
|
+
bySessionManager: WeakMap<object, SubagentRuntimeEntry>;
|
|
100
|
+
visibleControlNoticesBySessionManager: WeakMap<object, Set<string>>;
|
|
101
|
+
activeEntries: Set<SubagentRuntimeEntry>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function getRuntimeRegistry(): SubagentRuntimeRegistry {
|
|
105
|
+
const globalStore = globalThis as Record<string, unknown>;
|
|
106
|
+
const existing = globalStore[RUNTIME_REGISTRY_STORE_KEY] as Partial<SubagentRuntimeRegistry> | undefined;
|
|
107
|
+
if (existing?.bySessionManager instanceof WeakMap && existing.activeEntries instanceof Set) {
|
|
108
|
+
if (!(existing.visibleControlNoticesBySessionManager instanceof WeakMap)) {
|
|
109
|
+
existing.visibleControlNoticesBySessionManager = new WeakMap();
|
|
110
|
+
}
|
|
111
|
+
return existing as SubagentRuntimeRegistry;
|
|
112
|
+
}
|
|
113
|
+
const registry: SubagentRuntimeRegistry = {
|
|
114
|
+
bySessionManager: new WeakMap(),
|
|
115
|
+
visibleControlNoticesBySessionManager: new WeakMap(),
|
|
116
|
+
activeEntries: new Set(),
|
|
117
|
+
};
|
|
118
|
+
globalStore[RUNTIME_REGISTRY_STORE_KEY] = registry;
|
|
119
|
+
return registry;
|
|
120
|
+
}
|
|
87
121
|
|
|
88
122
|
function logSlowPhase(label: string, startedAt: number): void {
|
|
89
123
|
const elapsed = Date.now() - startedAt;
|
|
@@ -358,16 +392,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
358
392
|
if (process.env[SUBAGENT_CHILD_ENV] === "1") {
|
|
359
393
|
return;
|
|
360
394
|
}
|
|
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
|
-
}
|
|
395
|
+
const runtimeRegistry = getRuntimeRegistry();
|
|
371
396
|
|
|
372
397
|
DIRS.results = ensureAccessibleDir(DIRS.results);
|
|
373
398
|
DIRS.async = ensureAccessibleDir(DIRS.async);
|
|
@@ -395,6 +420,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
395
420
|
const state: SubagentState = {
|
|
396
421
|
baseCwd: "",
|
|
397
422
|
currentSessionId: null,
|
|
423
|
+
completionOwnerId: currentCompletionOwnerId(),
|
|
398
424
|
artifactDirPreference: config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
|
|
399
425
|
...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
|
|
400
426
|
...(config.missions ? { missionStoreConfig: config.missions } : {}),
|
|
@@ -440,6 +466,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
440
466
|
: undefined;
|
|
441
467
|
let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
|
|
442
468
|
let goalTurnId = 0;
|
|
469
|
+
let parentSessionEnvValue: string | null = null;
|
|
443
470
|
const scheduledStoreRoot = config.scheduledRuns?.storeRoot === undefined ? undefined : resolveScheduledStoreRoot(config.scheduledRuns.storeRoot);
|
|
444
471
|
const scheduledRunManager = createScheduledRunManager({
|
|
445
472
|
config,
|
|
@@ -456,10 +483,30 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
456
483
|
},
|
|
457
484
|
resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
|
|
458
485
|
});
|
|
486
|
+
let refreshResultDelivery = () => {};
|
|
487
|
+
const hasResultDeliveryDemand = () => {
|
|
488
|
+
if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
|
|
489
|
+
if (state.foregroundControls.size > 0) return true;
|
|
490
|
+
if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
|
|
491
|
+
return missionObserverResultCandidateFiles(DIRS.results).length > 0;
|
|
492
|
+
};
|
|
493
|
+
const discoverAgentsForRuntime = (cwd: string, scope: AgentScope) => {
|
|
494
|
+
const discovered = discoverAgents(cwd, scope);
|
|
495
|
+
if (listRuntimeAgentConfigs(pi).length === 0) return discovered;
|
|
496
|
+
const all = discoverAgentsAll(cwd);
|
|
497
|
+
const configuredAgents: AgentConfig[] = [
|
|
498
|
+
...all.builtin,
|
|
499
|
+
...all.package,
|
|
500
|
+
...all.user,
|
|
501
|
+
...all.project,
|
|
502
|
+
];
|
|
503
|
+
return mergeRuntimeAgents(pi, discovered, configuredAgents);
|
|
504
|
+
};
|
|
459
505
|
const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
|
|
460
506
|
widgetEnabled: asyncWidgetEnabled,
|
|
507
|
+
onJobTerminal: () => refreshResultDelivery(),
|
|
461
508
|
});
|
|
462
|
-
const
|
|
509
|
+
const resultWatcher = createResultWatcher(
|
|
463
510
|
pi,
|
|
464
511
|
state,
|
|
465
512
|
DIRS.results,
|
|
@@ -468,23 +515,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
468
515
|
notifier: completionNotifier,
|
|
469
516
|
observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
|
|
470
517
|
observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
|
|
518
|
+
hasDeliveryDemand: hasResultDeliveryDemand,
|
|
471
519
|
deliverIntercomResults: config.intercomBridge?.resultDelivery === true,
|
|
520
|
+
resultScanLogging: config.resultScanLogging ?? "all",
|
|
472
521
|
},
|
|
473
522
|
);
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
523
|
+
const { startResultWatcher, primeExistingResults, stopResultWatcher } = resultWatcher;
|
|
524
|
+
refreshResultDelivery = resultWatcher.refreshResultDelivery;
|
|
525
|
+
const asyncRetentionAbort = new AbortController();
|
|
526
|
+
const asyncRetentionTimer = setTimeout(async () => {
|
|
527
|
+
try {
|
|
528
|
+
await cleanupAsyncRetention({
|
|
529
|
+
asyncDirRoot: DIRS.async,
|
|
530
|
+
resultsDir: DIRS.results,
|
|
531
|
+
signal: asyncRetentionAbort.signal,
|
|
532
|
+
protectedRunIds: new Set([
|
|
533
|
+
...state.asyncJobs.keys(),
|
|
534
|
+
...(state.workflowControllers?.keys() ?? []),
|
|
535
|
+
...scheduledRunManager.referencedAsyncRunIds(),
|
|
536
|
+
]),
|
|
537
|
+
});
|
|
538
|
+
} catch (error) {
|
|
539
|
+
console.error("Failed to clean retained async subagent state:", error);
|
|
540
|
+
}
|
|
541
|
+
}, ASYNC_RETENTION_DELAY_MS);
|
|
542
|
+
asyncRetentionTimer.unref?.();
|
|
488
543
|
|
|
489
544
|
const executor = createSubagentExecutor({
|
|
490
545
|
pi,
|
|
@@ -497,7 +552,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
497
552
|
tempArtifactsDir,
|
|
498
553
|
getSubagentSessionRoot,
|
|
499
554
|
expandTilde,
|
|
500
|
-
discoverAgents,
|
|
555
|
+
discoverAgents: discoverAgentsForRuntime,
|
|
556
|
+
activateSupervisorTransport: () => supervisorChannel.activateTransport(),
|
|
557
|
+
refreshResultDelivery: () => refreshResultDelivery(),
|
|
501
558
|
});
|
|
502
559
|
executorScheduled = executor.executeScheduled;
|
|
503
560
|
|
|
@@ -568,6 +625,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
568
625
|
|
|
569
626
|
const slashBridge = registerSlashSubagentBridge({
|
|
570
627
|
events: pi.events,
|
|
628
|
+
asyncByDefault,
|
|
571
629
|
getContext: () => state.lastUiContext,
|
|
572
630
|
execute: (id, params, signal, onUpdate, ctx) =>
|
|
573
631
|
executeSubagentCollapsed(id, params, signal, onUpdate, ctx),
|
|
@@ -592,11 +650,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
592
650
|
});
|
|
593
651
|
|
|
594
652
|
|
|
595
|
-
const parameters = createSubagentParamsSchema(
|
|
653
|
+
const parameters = createSubagentParamsSchema();
|
|
596
654
|
const tool: ToolDefinition<typeof parameters, Details> = {
|
|
597
655
|
name: "subagent",
|
|
598
656
|
label: "Subagent",
|
|
599
657
|
description: buildSubagentToolDescription(config),
|
|
658
|
+
...buildSubagentToolPromptMetadata(config),
|
|
600
659
|
parameters,
|
|
601
660
|
|
|
602
661
|
execute(id, params, signal, onUpdate, ctx) {
|
|
@@ -607,7 +666,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
607
666
|
const gap = " ".repeat(config.mainWindowRenderer?.horizontalSpacing ?? 1);
|
|
608
667
|
const title = theme.fg("toolTitle", theme.bold("subagent"));
|
|
609
668
|
if (args.action) {
|
|
610
|
-
const target = args.agent ||
|
|
669
|
+
const target = args.agent || "";
|
|
611
670
|
return new Text(
|
|
612
671
|
`${title}${gap}${args.action}${target ? `${gap}${theme.fg("accent", target)}` : ""}`,
|
|
613
672
|
0, 0,
|
|
@@ -667,22 +726,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
667
726
|
foregroundDetachShortcut: config.foregroundDetachShortcut,
|
|
668
727
|
});
|
|
669
728
|
|
|
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;
|
|
729
|
+
let visibleControlNotices = new Set<string>();
|
|
686
730
|
const activeHerdrRuns = () => projectActiveHerdrRuns(state);
|
|
687
731
|
const herdrStatusBridge = registerHerdrStatusBridge({
|
|
688
732
|
events: pi.events,
|
|
@@ -704,10 +748,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
704
748
|
};
|
|
705
749
|
const asyncStartedHandler = (payload: unknown) => {
|
|
706
750
|
handleStarted(payload);
|
|
751
|
+
supervisorChannel.activateTransport();
|
|
752
|
+
refreshResultDelivery();
|
|
707
753
|
fleetStatus?.refresh();
|
|
708
754
|
};
|
|
709
755
|
const asyncCompleteHandler = (payload: unknown) => {
|
|
710
756
|
handleComplete(payload);
|
|
757
|
+
refreshResultDelivery();
|
|
711
758
|
refreshActiveAsyncCapacity();
|
|
712
759
|
scheduledRunManager.handleAsyncCompletion(payload);
|
|
713
760
|
fleetStatus?.refresh();
|
|
@@ -724,7 +771,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
724
771
|
herdrStatusBridge.dispose,
|
|
725
772
|
rpcBridge.dispose,
|
|
726
773
|
];
|
|
727
|
-
globalStore[eventUnsubscribeStoreKey] = eventUnsubscribes;
|
|
728
774
|
|
|
729
775
|
pi.on("tool_result", (event, ctx) => {
|
|
730
776
|
if (event.toolName !== "subagent") return;
|
|
@@ -802,6 +848,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
802
848
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
803
849
|
if (sessionId) {
|
|
804
850
|
process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId;
|
|
851
|
+
parentSessionEnvValue = sessionId;
|
|
805
852
|
}
|
|
806
853
|
}
|
|
807
854
|
state.lastUiContext = ctx;
|
|
@@ -840,6 +887,90 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
840
887
|
fleetStatus?.setContext(ctx);
|
|
841
888
|
};
|
|
842
889
|
|
|
890
|
+
let runtimeCleaned = false;
|
|
891
|
+
const runtimeEntry: SubagentRuntimeEntry = {
|
|
892
|
+
sessionManager: null,
|
|
893
|
+
visibleControlNotices,
|
|
894
|
+
cleanup() {
|
|
895
|
+
if (runtimeCleaned) return;
|
|
896
|
+
runtimeCleaned = true;
|
|
897
|
+
const shuttingDownParentSession = parentSessionEnvValue;
|
|
898
|
+
clearRuntimeAgentsForPi(pi);
|
|
899
|
+
clearTimeout(resultIndexCleanupTimer);
|
|
900
|
+
clearTimeout(asyncRetentionTimer);
|
|
901
|
+
asyncRetentionAbort.abort();
|
|
902
|
+
stopResultWatcher();
|
|
903
|
+
completionNotifier.dispose();
|
|
904
|
+
mainWatchdog.dispose();
|
|
905
|
+
scheduledRunManager.stop();
|
|
906
|
+
supervisorChannel.dispose();
|
|
907
|
+
waitSubscriptionManager.dispose();
|
|
908
|
+
fleetStatus?.dispose();
|
|
909
|
+
disposeAsyncJobTracker();
|
|
910
|
+
for (const timer of state.cleanupTimers.values()) clearTimeout(timer);
|
|
911
|
+
state.cleanupTimers.clear();
|
|
912
|
+
state.asyncJobs.clear();
|
|
913
|
+
for (const unsubscribe of eventUnsubscribes) {
|
|
914
|
+
try {
|
|
915
|
+
unsubscribe();
|
|
916
|
+
} catch {
|
|
917
|
+
// Best effort cleanup during shutdown or reload.
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
slashBridge.cancelAll();
|
|
921
|
+
slashBridge.dispose();
|
|
922
|
+
promptTemplateBridge.cancelAll();
|
|
923
|
+
promptTemplateBridge.dispose();
|
|
924
|
+
state.widgetsSuspended = false;
|
|
925
|
+
state.currentSessionId = null;
|
|
926
|
+
state.parentSessionFile = null;
|
|
927
|
+
parentSessionEnvValue = null;
|
|
928
|
+
if (shuttingDownParentSession && process.env[SUBAGENT_PARENT_SESSION_ENV] === shuttingDownParentSession) {
|
|
929
|
+
delete process.env[SUBAGENT_PARENT_SESSION_ENV];
|
|
930
|
+
}
|
|
931
|
+
if (runtimeEntry.sessionManager && runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
|
|
932
|
+
runtimeRegistry.bySessionManager.delete(runtimeEntry.sessionManager);
|
|
933
|
+
}
|
|
934
|
+
runtimeRegistry.activeEntries.delete(runtimeEntry);
|
|
935
|
+
if (runtimeRegistry.activeEntries.size === 0) clearSlashSnapshots();
|
|
936
|
+
try {
|
|
937
|
+
if (state.lastUiContext?.hasUI) state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
|
|
938
|
+
} catch (error) {
|
|
939
|
+
if (!isStaleExtensionContextError(error)) throw error;
|
|
940
|
+
}
|
|
941
|
+
state.lastUiContext = null;
|
|
942
|
+
},
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
const installRuntime = (ctx: ExtensionContext) => {
|
|
946
|
+
if (runtimeCleaned) {
|
|
947
|
+
throw new Error("Cannot restart a cleaned pi-subagents extension runtime; register a new extension instance.");
|
|
948
|
+
}
|
|
949
|
+
const sessionManager = ctx.sessionManager as object;
|
|
950
|
+
const previousRuntime = runtimeRegistry.bySessionManager.get(sessionManager);
|
|
951
|
+
const existingVisibleControlNotices = runtimeRegistry.visibleControlNoticesBySessionManager.get(sessionManager);
|
|
952
|
+
if (existingVisibleControlNotices) {
|
|
953
|
+
visibleControlNotices = existingVisibleControlNotices;
|
|
954
|
+
} else {
|
|
955
|
+
runtimeRegistry.visibleControlNoticesBySessionManager.set(sessionManager, visibleControlNotices);
|
|
956
|
+
}
|
|
957
|
+
runtimeEntry.visibleControlNotices = visibleControlNotices;
|
|
958
|
+
if (runtimeEntry.sessionManager && runtimeEntry.sessionManager !== sessionManager
|
|
959
|
+
&& runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
|
|
960
|
+
runtimeRegistry.bySessionManager.delete(runtimeEntry.sessionManager);
|
|
961
|
+
}
|
|
962
|
+
runtimeEntry.sessionManager = sessionManager;
|
|
963
|
+
runtimeRegistry.bySessionManager.set(sessionManager, runtimeEntry);
|
|
964
|
+
runtimeRegistry.activeEntries.add(runtimeEntry);
|
|
965
|
+
if (previousRuntime && previousRuntime !== runtimeEntry) {
|
|
966
|
+
try {
|
|
967
|
+
previousRuntime.cleanup();
|
|
968
|
+
} catch {
|
|
969
|
+
// Best effort cleanup for stale resources from the replaced runtime.
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
|
|
843
974
|
pi.on("agent_start", () => {
|
|
844
975
|
resumeWidgetsAfterCompaction();
|
|
845
976
|
herdrStatusBridge.agentStarted();
|
|
@@ -867,6 +998,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
867
998
|
});
|
|
868
999
|
|
|
869
1000
|
pi.on("session_start", (event, ctx) => {
|
|
1001
|
+
installRuntime(ctx);
|
|
870
1002
|
const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
|
|
871
1003
|
resetSessionState(ctx, recovering);
|
|
872
1004
|
herdrStatusBridge.sessionStarted({
|
|
@@ -875,50 +1007,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
875
1007
|
});
|
|
876
1008
|
rpcBridge.emitReady(ctx);
|
|
877
1009
|
supervisorChannel.start();
|
|
1010
|
+
supervisorChannel.activateTransport();
|
|
878
1011
|
});
|
|
879
1012
|
|
|
880
1013
|
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
|
-
}
|
|
1014
|
+
runtimeEntry.cleanup();
|
|
922
1015
|
await herdrStatusBridge.flush();
|
|
923
1016
|
});
|
|
924
1017
|
}
|