@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
|
|
4
|
+
import { isAsyncAvailable } from "../runs/background/async-execution.ts";
|
|
5
|
+
import { formatSpawnBudgetSummary, getSpawnBudgetSnapshot } from "../runs/shared/spawn-budget.ts";
|
|
6
|
+
import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "../intercom/intercom-bridge.ts";
|
|
7
|
+
import { discoverAvailableSkills, type SkillSource } from "../agents/skills.ts";
|
|
8
|
+
import {
|
|
9
|
+
DIRS,
|
|
10
|
+
CHAIN_RUNS_DIR,
|
|
11
|
+
TEMP_ROOT_DIR,
|
|
12
|
+
type ExtensionConfig,
|
|
13
|
+
type SubagentState,
|
|
14
|
+
} from "../shared/types.ts";
|
|
15
|
+
|
|
16
|
+
interface DoctorPaths {
|
|
17
|
+
tempRootDir: string;
|
|
18
|
+
asyncDir: string;
|
|
19
|
+
resultsDir: string;
|
|
20
|
+
chainRunsDir: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface DoctorDeps {
|
|
24
|
+
isAsyncAvailable: () => boolean;
|
|
25
|
+
discoverAgentsAll: typeof discoverAgentsAll;
|
|
26
|
+
discoverAvailableSkills: typeof discoverAvailableSkills;
|
|
27
|
+
diagnoseIntercomBridge: typeof diagnoseIntercomBridge;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface DoctorReportInput {
|
|
31
|
+
cwd: string;
|
|
32
|
+
config: ExtensionConfig;
|
|
33
|
+
state: SubagentState;
|
|
34
|
+
context?: "fresh" | "fork";
|
|
35
|
+
requestedSessionDir?: string;
|
|
36
|
+
currentSessionFile?: string | null;
|
|
37
|
+
currentSessionId?: string | null;
|
|
38
|
+
orchestratorTarget?: string;
|
|
39
|
+
sessionError?: string;
|
|
40
|
+
expandTilde?: (value: string) => string;
|
|
41
|
+
paths?: DoctorPaths;
|
|
42
|
+
deps?: Partial<DoctorDeps>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function defaultPaths(): DoctorPaths {
|
|
46
|
+
return {
|
|
47
|
+
tempRootDir: TEMP_ROOT_DIR,
|
|
48
|
+
asyncDir: DIRS.async,
|
|
49
|
+
resultsDir: DIRS.results,
|
|
50
|
+
chainRunsDir: CHAIN_RUNS_DIR,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const DEFAULT_DEPS: DoctorDeps = {
|
|
55
|
+
isAsyncAvailable,
|
|
56
|
+
discoverAgentsAll,
|
|
57
|
+
discoverAvailableSkills,
|
|
58
|
+
diagnoseIntercomBridge,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
function errorText(error: unknown): string {
|
|
62
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function lineFromCheck(label: string, check: () => string): string {
|
|
66
|
+
try {
|
|
67
|
+
return check();
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return `- ${label}: failed — ${errorText(error)}`;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function formatExistingDirectory(label: string, dirPath: string): string {
|
|
74
|
+
try {
|
|
75
|
+
if (!fs.existsSync(dirPath)) return `- ${label}: missing (${dirPath})`;
|
|
76
|
+
const stats = fs.statSync(dirPath);
|
|
77
|
+
if (!stats.isDirectory()) throw new Error(`not a directory: ${dirPath}`);
|
|
78
|
+
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
|
|
79
|
+
return `- ${label}: ok (${dirPath})`;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return `- ${label}: failed (${dirPath}) — ${errorText(error)}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function formatSourceCounts(counts: Record<AgentSource, number>): string {
|
|
86
|
+
return `builtin ${counts.builtin}, package ${counts.package}, user ${counts.user}, project ${counts.project}`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function formatSkillSourceCounts(skills: Array<{ source: SkillSource }>): string {
|
|
90
|
+
const counts = new Map<SkillSource, number>();
|
|
91
|
+
for (const skill of skills) counts.set(skill.source, (counts.get(skill.source) ?? 0) + 1);
|
|
92
|
+
const ordered: SkillSource[] = [
|
|
93
|
+
"project",
|
|
94
|
+
"project-settings",
|
|
95
|
+
"project-package",
|
|
96
|
+
"user",
|
|
97
|
+
"user-settings",
|
|
98
|
+
"user-package",
|
|
99
|
+
"extension",
|
|
100
|
+
"builtin",
|
|
101
|
+
"unknown",
|
|
102
|
+
];
|
|
103
|
+
const parts = ordered
|
|
104
|
+
.map((source) => `${source} ${counts.get(source) ?? 0}`)
|
|
105
|
+
.filter((part) => !part.endsWith(" 0"));
|
|
106
|
+
return parts.length > 0 ? parts.join(", ") : "none";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function formatConfiguredSessionDir(input: DoctorReportInput): string {
|
|
110
|
+
if (input.requestedSessionDir) {
|
|
111
|
+
return path.resolve(input.expandTilde?.(input.requestedSessionDir) ?? input.requestedSessionDir);
|
|
112
|
+
}
|
|
113
|
+
if (input.config.defaultSessionDir) {
|
|
114
|
+
return path.resolve(input.expandTilde?.(input.config.defaultSessionDir) ?? input.config.defaultSessionDir);
|
|
115
|
+
}
|
|
116
|
+
return "not configured";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function formatSessionLines(input: DoctorReportInput): string[] {
|
|
120
|
+
const sessionFile = input.currentSessionFile ?? null;
|
|
121
|
+
const lines = [
|
|
122
|
+
lineFromCheck("configured session dir", () => `- configured session dir: ${formatConfiguredSessionDir(input)}`),
|
|
123
|
+
`- current session file: ${sessionFile ?? "not available"}`,
|
|
124
|
+
`- current session dir: ${sessionFile ? path.dirname(sessionFile) : "not available"}`,
|
|
125
|
+
`- current session id: ${input.currentSessionId ?? input.state.currentSessionId ?? "not available"}`,
|
|
126
|
+
];
|
|
127
|
+
if (input.sessionError) lines.push(`- session manager: failed — ${input.sessionError}`);
|
|
128
|
+
return lines;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
|
|
132
|
+
return [
|
|
133
|
+
lineFromCheck("agents/chains", () => {
|
|
134
|
+
const discovered = deps.discoverAgentsAll(input.cwd);
|
|
135
|
+
const agentCounts = {
|
|
136
|
+
builtin: discovered.builtin.length,
|
|
137
|
+
package: discovered.package?.length ?? 0,
|
|
138
|
+
user: discovered.user.length,
|
|
139
|
+
project: discovered.project.length,
|
|
140
|
+
};
|
|
141
|
+
const chainCounts = discovered.chains.reduce<Record<AgentSource, number>>((counts, chain) => {
|
|
142
|
+
counts[chain.source] += 1;
|
|
143
|
+
return counts;
|
|
144
|
+
}, { builtin: 0, package: 0, user: 0, project: 0 });
|
|
145
|
+
return [
|
|
146
|
+
`- agents: total ${agentCounts.builtin + agentCounts.package + agentCounts.user + agentCounts.project} (${formatSourceCounts(agentCounts)})`,
|
|
147
|
+
`- chains: total ${discovered.chains.length} (${formatSourceCounts(chainCounts)})`,
|
|
148
|
+
].join("\n");
|
|
149
|
+
}),
|
|
150
|
+
lineFromCheck("skills", () => {
|
|
151
|
+
const skills = deps.discoverAvailableSkills(input.cwd);
|
|
152
|
+
return `- skills: total ${skills.length} (${formatSkillSourceCounts(skills)})`;
|
|
153
|
+
}),
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function formatIntercomDiagnostic(diagnostic: IntercomBridgeDiagnostic, context: "fresh" | "fork" | undefined): string[] {
|
|
158
|
+
const lines = [
|
|
159
|
+
`- bridge: ${diagnostic.active ? "active" : "inactive"}${diagnostic.reason ? ` (${diagnostic.reason})` : ""}`,
|
|
160
|
+
`- mode: ${diagnostic.mode}; context: ${context ?? "unspecified"}`,
|
|
161
|
+
`- orchestrator target: ${diagnostic.orchestratorTarget ?? "not available"}`,
|
|
162
|
+
`- supervisor channel: ${diagnostic.supervisorChannelAvailable ? "available" : "unavailable"} (${diagnostic.extensionDir})`,
|
|
163
|
+
];
|
|
164
|
+
return lines;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function formatSpawnBudgetSection(input: DoctorReportInput): string[] {
|
|
168
|
+
const snapshot = getSpawnBudgetSnapshot(input.state, input.config, input.currentSessionId ?? input.state.currentSessionId);
|
|
169
|
+
return [
|
|
170
|
+
`- usage: ${formatSpawnBudgetSummary(snapshot)}`,
|
|
171
|
+
`- recent grants: ${snapshot.grantHistory.length === 0
|
|
172
|
+
? "none"
|
|
173
|
+
: snapshot.grantHistory.map((grant) => `+${grant.amount} at ${new Date(grant.grantedAt).toISOString()} (${grant.previousLimit} → ${grant.limit})`).join("; ")}`,
|
|
174
|
+
"- reset boundary: a new parent session resets usage and grants; compaction does not",
|
|
175
|
+
];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function formatPermissionSystemSection(): string[] {
|
|
179
|
+
const lines: string[] = [];
|
|
180
|
+
const parentSession = process.env["PI_SUBAGENT_PARENT_SESSION"] ?? "";
|
|
181
|
+
const trimmed = parentSession.trim();
|
|
182
|
+
if (trimmed) {
|
|
183
|
+
lines.push(`- parent session: set (${trimmed})`);
|
|
184
|
+
} else {
|
|
185
|
+
lines.push("- parent session: not set — ask forwarding from subprocess children will not reach a parent UI");
|
|
186
|
+
}
|
|
187
|
+
const isChild = process.env["PI_SUBAGENT_CHILD"] === "1";
|
|
188
|
+
lines.push(`- subagent process: ${isChild ? "yes (PI_SUBAGENT_CHILD=1)" : "no"}`);
|
|
189
|
+
// Whether pi-permission-system is installed and where it stores config is
|
|
190
|
+
// outside pi-subagents' control, so we only report the forwarding signal we
|
|
191
|
+
// own. Run `pi list` to confirm the permission extension is installed.
|
|
192
|
+
return lines;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function buildDoctorReport(input: DoctorReportInput): string {
|
|
196
|
+
const paths = input.paths ?? defaultPaths();
|
|
197
|
+
const deps = { ...DEFAULT_DEPS, ...input.deps };
|
|
198
|
+
const lines = [
|
|
199
|
+
"Subagents doctor report",
|
|
200
|
+
"",
|
|
201
|
+
"Runtime",
|
|
202
|
+
`- cwd: ${input.cwd}`,
|
|
203
|
+
lineFromCheck("async support", () => `- async support: ${deps.isAsyncAvailable() ? "available" : "unavailable"}`),
|
|
204
|
+
...formatSessionLines(input),
|
|
205
|
+
"",
|
|
206
|
+
"Filesystem",
|
|
207
|
+
formatExistingDirectory("temp root", paths.tempRootDir),
|
|
208
|
+
formatExistingDirectory("async runs", paths.asyncDir),
|
|
209
|
+
formatExistingDirectory("results", paths.resultsDir),
|
|
210
|
+
formatExistingDirectory("chain runs", paths.chainRunsDir),
|
|
211
|
+
"",
|
|
212
|
+
"Discovery",
|
|
213
|
+
...formatDiscovery(input, deps),
|
|
214
|
+
"",
|
|
215
|
+
"Spawn budget",
|
|
216
|
+
...formatSpawnBudgetSection(input),
|
|
217
|
+
"",
|
|
218
|
+
"Permission system",
|
|
219
|
+
...formatPermissionSystemSection(),
|
|
220
|
+
"",
|
|
221
|
+
"Intercom bridge",
|
|
222
|
+
...lineFromCheck("intercom bridge", () => formatIntercomDiagnostic(deps.diagnoseIntercomBridge({
|
|
223
|
+
config: input.config.intercomBridge,
|
|
224
|
+
context: input.context,
|
|
225
|
+
orchestratorTarget: input.orchestratorTarget,
|
|
226
|
+
cwd: input.cwd,
|
|
227
|
+
}), input.context).join("\n")).split("\n"),
|
|
228
|
+
];
|
|
229
|
+
return lines.join("\n");
|
|
230
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { discoverAgents } from "../agents/agents.ts";
|
|
6
|
+
import { getArtifactsDir } from "../shared/artifacts.ts";
|
|
7
|
+
import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
8
|
+
import { resolveWaitToolConfig } from "../runs/background/wait-config.ts";
|
|
9
|
+
import { SUBAGENT_CHILD_ENV, SUBAGENT_FANOUT_CHILD_ENV } from "../runs/shared/pi-args.ts";
|
|
10
|
+
import { readNestedControlRequests, resolveNestedRouteFromEnv, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
|
|
11
|
+
import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
|
|
12
|
+
import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
|
|
13
|
+
import { SubagentParams } from "./schemas.ts";
|
|
14
|
+
import { loadConfig, resolveAsyncByDefault } from "./config.ts";
|
|
15
|
+
import { type Details, type SubagentState } from "../shared/types.ts";
|
|
16
|
+
|
|
17
|
+
function getSubagentSessionRoot(parentSessionFile: string | null): string {
|
|
18
|
+
if (parentSessionFile) {
|
|
19
|
+
const baseName = path.basename(parentSessionFile, ".jsonl");
|
|
20
|
+
const sessionsDir = path.dirname(parentSessionFile);
|
|
21
|
+
return path.join(sessionsDir, baseName);
|
|
22
|
+
}
|
|
23
|
+
return fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-session-"));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function expandTilde(p: string): string {
|
|
27
|
+
return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function createChildSafeState(): SubagentState {
|
|
31
|
+
return {
|
|
32
|
+
baseCwd: "",
|
|
33
|
+
currentSessionId: null,
|
|
34
|
+
subagentInProgress: false,
|
|
35
|
+
subagentSpawns: { sessionId: null, count: 0 },
|
|
36
|
+
asyncJobs: new Map(),
|
|
37
|
+
foregroundRuns: new Map(),
|
|
38
|
+
foregroundControls: new Map(),
|
|
39
|
+
lastForegroundControlId: null,
|
|
40
|
+
cleanupTimers: new Map(),
|
|
41
|
+
lastUiContext: null,
|
|
42
|
+
poller: null,
|
|
43
|
+
completionSeen: new Map(),
|
|
44
|
+
watcher: null,
|
|
45
|
+
watcherRestartTimer: null,
|
|
46
|
+
resultFileCoalescer: {
|
|
47
|
+
schedule: () => false,
|
|
48
|
+
clear: () => {},
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function resolveNestedControlRoute(): NestedRoute | undefined {
|
|
54
|
+
try {
|
|
55
|
+
return resolveNestedRouteFromEnv();
|
|
56
|
+
} catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function nestedControlRouteKey(route: NestedRoute): string {
|
|
62
|
+
return route.controlInbox;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface NestedControlInboxState {
|
|
66
|
+
seen: Set<string>;
|
|
67
|
+
inFlight: Set<string>;
|
|
68
|
+
pendingResults: Map<string, Parameters<typeof writeNestedControlResult>[1]>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface NestedControlListenerEntry {
|
|
72
|
+
cleanup: () => void;
|
|
73
|
+
state: NestedControlInboxState;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function createNestedControlInboxState(): NestedControlInboxState {
|
|
77
|
+
return { seen: new Set(), inFlight: new Set(), pendingResults: new Map() };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState, route: NestedRoute, inboxState: NestedControlInboxState): () => void {
|
|
81
|
+
const timer = setInterval(() => {
|
|
82
|
+
try {
|
|
83
|
+
for (const request of readNestedControlRequests(route)) {
|
|
84
|
+
if (inboxState.seen.has(request.requestId) || inboxState.inFlight.has(request.requestId)) continue;
|
|
85
|
+
inboxState.inFlight.add(request.requestId);
|
|
86
|
+
void (async () => {
|
|
87
|
+
try {
|
|
88
|
+
let result = inboxState.pendingResults.get(request.requestId);
|
|
89
|
+
if (!result) {
|
|
90
|
+
let ok = false;
|
|
91
|
+
let message = "Control request failed.";
|
|
92
|
+
try {
|
|
93
|
+
const control = state.foregroundControls.get(request.targetRunId);
|
|
94
|
+
if (!control) {
|
|
95
|
+
message = `Nested run ${request.targetRunId} is not active in this fanout child.`;
|
|
96
|
+
} else if (request.action === "interrupt") {
|
|
97
|
+
ok = control.interrupt?.() === true;
|
|
98
|
+
message = ok
|
|
99
|
+
? `Interrupt requested for nested run ${request.targetRunId}.`
|
|
100
|
+
: `Nested run ${request.targetRunId} has no active child step to interrupt.`;
|
|
101
|
+
} else if (!request.message?.trim()) {
|
|
102
|
+
message = "Nested resume requires message.";
|
|
103
|
+
} else if (!control.currentAgent) {
|
|
104
|
+
message = `Nested run ${request.targetRunId} has no active child message route.`;
|
|
105
|
+
} else {
|
|
106
|
+
const index = control.currentIndex ?? 0;
|
|
107
|
+
const target = resolveSubagentIntercomTarget(request.targetRunId, control.currentAgent, index);
|
|
108
|
+
ok = await deliverSubagentIntercomMessageEvent(
|
|
109
|
+
pi.events,
|
|
110
|
+
target,
|
|
111
|
+
`Follow-up for nested run ${request.targetRunId} (${control.currentAgent}):\n\n${request.message.trim()}`,
|
|
112
|
+
500,
|
|
113
|
+
{ source: "nested-resume", runId: request.targetRunId, agent: control.currentAgent, index },
|
|
114
|
+
);
|
|
115
|
+
message = ok
|
|
116
|
+
? `Delivered follow-up to live nested run ${request.targetRunId}.`
|
|
117
|
+
: `Nested child intercom target is not registered: ${target}`;
|
|
118
|
+
}
|
|
119
|
+
} catch (error) {
|
|
120
|
+
message = error instanceof Error ? error.message : String(error);
|
|
121
|
+
}
|
|
122
|
+
result = { ts: Date.now(), requestId: request.requestId, targetRunId: request.targetRunId, ok, message };
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
writeNestedControlResult(route, result);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
inboxState.pendingResults.set(request.requestId, result);
|
|
128
|
+
console.error(`Failed to write nested control result for request '${request.requestId}' targeting '${request.targetRunId}' via inbox '${route.controlInbox}'; keeping request for retry:`, error);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
inboxState.pendingResults.delete(request.requestId);
|
|
132
|
+
inboxState.seen.add(request.requestId);
|
|
133
|
+
try { fs.unlinkSync(request.filePath); } catch {}
|
|
134
|
+
} finally {
|
|
135
|
+
inboxState.inFlight.delete(request.requestId);
|
|
136
|
+
}
|
|
137
|
+
})();
|
|
138
|
+
}
|
|
139
|
+
} catch (error) {
|
|
140
|
+
console.error(`Failed to poll nested control inbox '${route.controlInbox}' for root '${route.rootRunId}':`, error);
|
|
141
|
+
}
|
|
142
|
+
}, 200);
|
|
143
|
+
timer.unref?.();
|
|
144
|
+
return () => clearInterval(timer);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI): void {
|
|
148
|
+
if (process.env[SUBAGENT_CHILD_ENV] !== "1" || process.env[SUBAGENT_FANOUT_CHILD_ENV] !== "1") return;
|
|
149
|
+
|
|
150
|
+
const globalStore = globalThis as Record<string, unknown>;
|
|
151
|
+
const registeredKey = "__piSubagentFanoutChildRegisteredApis";
|
|
152
|
+
const registeredApis = globalStore[registeredKey] instanceof WeakSet
|
|
153
|
+
? globalStore[registeredKey] as WeakSet<ExtensionAPI>
|
|
154
|
+
: new WeakSet<ExtensionAPI>();
|
|
155
|
+
globalStore[registeredKey] = registeredApis;
|
|
156
|
+
if (registeredApis.has(pi)) return;
|
|
157
|
+
registeredApis.add(pi);
|
|
158
|
+
|
|
159
|
+
const config = loadConfig();
|
|
160
|
+
const state = createChildSafeState();
|
|
161
|
+
const executor = createSubagentExecutor({
|
|
162
|
+
pi,
|
|
163
|
+
state,
|
|
164
|
+
config,
|
|
165
|
+
asyncByDefault: resolveAsyncByDefault(config),
|
|
166
|
+
waitToolEnabled: resolveWaitToolConfig(config.waitTool).enabled,
|
|
167
|
+
tempArtifactsDir: getArtifactsDir(null),
|
|
168
|
+
getSubagentSessionRoot,
|
|
169
|
+
expandTilde,
|
|
170
|
+
discoverAgents,
|
|
171
|
+
allowMutatingManagementActions: false,
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const tool: ToolDefinition<typeof SubagentParams, Details> = {
|
|
175
|
+
name: "subagent",
|
|
176
|
+
label: "Subagent",
|
|
177
|
+
description: [
|
|
178
|
+
"Delegate to subagents from child-safe fanout mode.",
|
|
179
|
+
"Allowed management/control actions: list, get, status, interrupt, resume, steer, append-step, doctor.",
|
|
180
|
+
"Mutating management actions (create, update, delete, eject, disable, enable, reset, grant-spawn-budget) are blocked in this mode.",
|
|
181
|
+
].join("\n"),
|
|
182
|
+
parameters: SubagentParams,
|
|
183
|
+
execute(id, params, signal, onUpdate, ctx) {
|
|
184
|
+
return executor.executePublic(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx);
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
pi.registerTool(tool);
|
|
189
|
+
const route = resolveNestedControlRoute();
|
|
190
|
+
if (!route) return;
|
|
191
|
+
const listenerCleanupKey = "__piSubagentFanoutChildNestedControlInboxCleanups";
|
|
192
|
+
const listenerCleanups = globalStore[listenerCleanupKey] instanceof Map
|
|
193
|
+
? globalStore[listenerCleanupKey] as Map<string, NestedControlListenerEntry>
|
|
194
|
+
: new Map<string, NestedControlListenerEntry>();
|
|
195
|
+
globalStore[listenerCleanupKey] = listenerCleanups;
|
|
196
|
+
const routeKey = nestedControlRouteKey(route);
|
|
197
|
+
const previous = listenerCleanups.get(routeKey);
|
|
198
|
+
previous?.cleanup();
|
|
199
|
+
const inboxState = previous?.state ?? createNestedControlInboxState();
|
|
200
|
+
listenerCleanups.set(routeKey, { state: inboxState, cleanup: startNestedControlInboxListener(pi, state, route, inboxState) });
|
|
201
|
+
}
|