@xzzpig/pi-subagents 0.13.0 → 0.15.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 +243 -0
- package/README.md +6 -5
- package/agents/evidence-auditor.md +34 -0
- package/agents/researcher.md +23 -13
- package/agents/reviewer.md +3 -2
- package/docs/agents.md +56 -15
- package/docs/configuration.md +93 -15
- package/docs/extension-api.md +132 -19
- package/docs/missions.md +10 -2
- package/docs/models.md +11 -22
- package/docs/observability.md +67 -11
- package/docs/standalone-background.md +59 -0
- package/docs/tool-reference.md +42 -23
- package/docs/watchdog.md +39 -10
- package/docs/workflows.md +58 -19
- package/index.ts +5 -2
- package/inspector-runner.mjs +2 -2
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
- package/node_modules/@xzzpig/pi-components/README.md +28 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
- package/node_modules/@xzzpig/pi-components/package.json +1 -1
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
- package/package.json +10 -5
- package/prompts/parallel-review.md +1 -1
- package/runner-peer-loader.mjs +24 -0
- package/runner-peer-preload.mjs +36 -0
- package/skills/pi-subagents/SKILL.md +34 -22
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
- package/skills/pi-subagents/references/execution-controls.md +27 -8
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
- package/skills/pi-subagents/references/review-and-validation.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +94 -0
- package/src/agents/agent-management.ts +71 -59
- package/src/agents/agent-serializer.ts +6 -3
- package/src/agents/agents.ts +198 -72
- package/src/agents/builtin-names.ts +1 -0
- package/src/agents/chain-serializer.ts +5 -0
- package/src/agents/runtime-agent-registry.ts +7 -6
- package/src/api/delegation.ts +4 -0
- package/src/api/preflight.ts +110 -71
- package/src/api/required-child-extensions.ts +6 -0
- package/src/api/shared-types.ts +3 -1
- package/src/api/workflow-resources.ts +6 -0
- package/src/extension/config.ts +14 -37
- package/src/extension/fanout-child.ts +68 -5
- package/src/extension/herdr-pi-bridge.ts +164 -0
- package/src/extension/index.ts +141 -51
- package/src/extension/public-execution.ts +7 -6
- package/src/extension/rpc.ts +8 -21
- package/src/extension/schemas.ts +86 -84
- package/src/extension/tool-description.ts +32 -79
- package/src/inspectors/actions.ts +148 -0
- package/src/inspectors/ghostty/actions.ts +74 -0
- package/src/inspectors/ghostty/plugin.ts +17 -0
- package/src/inspectors/herdr/actions.ts +99 -179
- package/src/inspectors/herdr/plugin.ts +20 -0
- package/src/inspectors/herdr/project-panes.ts +4 -1
- package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
- package/src/inspectors/plugins.ts +8 -0
- package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
- package/src/inspectors/types.ts +51 -0
- package/src/integrations/pi-web-session-liveness.ts +73 -0
- package/src/intercom/intercom-bridge.ts +50 -8
- package/src/intercom/native-supervisor-channel.ts +142 -115
- package/src/intercom/supervisor-ui.ts +3 -2
- package/src/missions/workflow-state.ts +37 -16
- package/src/policy/authority.ts +4 -0
- package/src/profiles/profiles.ts +12 -6
- package/src/runs/background/active-async-capacity.ts +22 -18
- package/src/runs/background/active-run-index.ts +17 -1
- package/src/runs/background/async-execution.ts +359 -176
- package/src/runs/background/async-job-tracker.ts +41 -7
- package/src/runs/background/async-resume.ts +19 -12
- package/src/runs/background/async-retention.ts +20 -0
- package/src/runs/background/async-status-snapshot.ts +10 -12
- package/src/runs/background/async-status.ts +32 -13
- package/src/runs/background/auto-drain.ts +59 -35
- package/src/runs/background/binary-bootstrap.ts +38 -0
- package/src/runs/background/chain-append.ts +1 -1
- package/src/runs/background/chain-root-attachment.ts +22 -33
- package/src/runs/background/control-channel.ts +78 -44
- package/src/runs/background/fleet-view.ts +30 -2
- package/src/runs/background/notify.ts +193 -19
- package/src/runs/background/owned-process-tree.ts +35 -8
- package/src/runs/background/process-terminal.ts +23 -23
- package/src/runs/background/result-files.ts +8 -4
- package/src/runs/background/result-watcher.ts +19 -2
- package/src/runs/background/retained-nested-route-tracker.ts +96 -0
- package/src/runs/background/run-child-session.ts +118 -41
- package/src/runs/background/run-status.ts +78 -5
- package/src/runs/background/runner-aliases.ts +22 -5
- package/src/runs/background/runner-child-launch.ts +93 -0
- package/src/runs/background/runner-child-sessions.ts +5 -4
- package/src/runs/background/runner-http-dispatcher.ts +119 -0
- package/src/runs/background/scheduled-runs.ts +51 -18
- package/src/runs/background/stale-run-reconciler.ts +38 -12
- package/src/runs/background/steering.ts +20 -2
- package/src/runs/background/subagent-runner.ts +766 -432
- package/src/runs/background/subagent-wait.ts +179 -28
- package/src/runs/background/wait-completions.ts +79 -27
- package/src/runs/background/wait-subscriptions.ts +9 -3
- package/src/runs/background/wait-tool.ts +5 -3
- package/src/runs/foreground/async-steering-action.ts +37 -7
- package/src/runs/foreground/async-stop-action.ts +93 -3
- package/src/runs/foreground/execution.ts +174 -194
- package/src/runs/foreground/foreground-history.ts +5 -2
- package/src/runs/foreground/prompt-audit.ts +12 -6
- package/src/runs/foreground/subagent-executor.ts +896 -397
- package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
- package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
- package/src/runs/shared/acceptance.ts +54 -14
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +172 -78
- package/src/runs/shared/capability-ceiling.ts +2 -0
- package/src/runs/shared/child-hooks.ts +167 -3
- package/src/runs/shared/child-launch-plan.ts +15 -3
- package/src/runs/shared/child-launch.ts +44 -16
- package/src/runs/shared/child-lifecycle.ts +6 -3
- package/src/runs/shared/child-runtime-config.ts +8 -1
- package/src/runs/shared/child-session.ts +130 -24
- package/src/runs/shared/child-tool-plan.ts +145 -14
- package/src/runs/shared/completion-evidence.ts +2 -2
- package/src/runs/shared/completion-guard.ts +6 -3
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/effective-system-prompt.ts +33 -0
- package/src/runs/shared/external-cli-contract.ts +11 -1
- package/src/runs/shared/external-cli-preflight.ts +6 -2
- package/src/runs/shared/external-cli-runner.ts +9 -7
- package/src/runs/shared/herdr-connection.ts +134 -0
- package/src/runs/shared/herdr-external-adapters.ts +169 -0
- package/src/runs/shared/herdr-machine.ts +279 -0
- package/src/runs/shared/herdr-pi-protocol.ts +59 -0
- package/src/runs/shared/herdr-placed-run.ts +263 -0
- package/src/runs/shared/host-step-status.ts +11 -11
- package/src/runs/shared/llm-intent-arbiter.ts +40 -21
- package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
- package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
- package/src/runs/shared/model-scope.ts +1 -1
- package/src/runs/shared/nested-events.ts +19 -10
- package/src/runs/shared/orca-progress-tabs.ts +7 -1
- package/src/runs/shared/parallel-handoff.ts +57 -12
- package/src/runs/shared/parallel-utils.ts +10 -4
- package/src/runs/shared/pi-spawn.ts +10 -0
- package/src/runs/shared/readonly-drain-observation.ts +42 -0
- package/src/runs/shared/run-fanout-budget.ts +8 -8
- package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
- package/src/runs/shared/task-intent.ts +46 -13
- package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
- package/src/runs/shared/worktree-setup-command.ts +213 -0
- package/src/runs/shared/worktree.ts +437 -214
- package/src/shared/child-cache-retention.ts +43 -0
- package/src/shared/fork-context.ts +15 -72
- package/src/shared/launch-contract.ts +70 -8
- package/src/shared/model-response-aliases.ts +13 -0
- package/src/shared/opencode-session-headers.ts +30 -0
- package/src/shared/pruned-fork.ts +1 -1
- package/src/shared/required-child-extensions.ts +81 -0
- package/src/shared/settings.ts +5 -2
- package/src/shared/shortcuts.ts +0 -4
- package/src/shared/types.ts +164 -90
- package/src/shared/utils.ts +10 -2
- package/src/shared/watch-strategy.ts +2 -0
- package/src/shared/workflow-child-permit.ts +18 -13
- package/src/slash/delegation-adapters.ts +3 -1
- package/src/slash/delegation-request.ts +14 -0
- package/src/slash/slash-commands.ts +2 -7
- package/src/slash/subagents-admin.ts +31 -14
- package/src/tui/fleet-native-transcript.ts +50 -6
- package/src/tui/fleet-status.ts +165 -20
- package/src/tui/fleet.ts +52 -21
- package/src/tui/render.ts +210 -50
- package/src/watchdog/child-status.ts +28 -28
- package/src/watchdog/lsp-diagnostics.ts +1 -1
- package/src/watchdog/model-selection.ts +21 -1
- package/src/watchdog/permission-arbiter.ts +5 -2
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/register-main.ts +39 -35
- package/src/watchdog/render.ts +1 -1
- package/src/watchdog/review.ts +122 -74
- package/src/watchdog/rules.ts +1 -1
- package/src/watchdog/runtime.ts +100 -27
- package/src/watchdog/scope.ts +1 -1
- package/src/watchdog/settings.ts +3 -0
- package/src/watchdog/tool-actions.ts +13 -12
- package/src/watchdog/turn-delta.ts +23 -0
- package/src/watchdog/types.ts +5 -3
- package/src/watchdog/warning-format.ts +1 -1
- package/src/workflows/chat-progress.ts +3 -3
- package/src/workflows/scripted-workflow.ts +349 -26
- package/src/workflows/workflow-checklist.ts +17 -20
- package/src/workflows/workflow-child-summary.ts +57 -8
- package/src/workflows/workflow-preflight.ts +19 -19
- package/src/workflows/workflow-receipt.ts +24 -6
- package/src/workflows/workflow-resources.ts +108 -22
- package/src/workflows/workflow-settlement.ts +3 -0
- package/src/runs/shared/model-exclusions.ts +0 -373
- /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
|
@@ -9,11 +9,13 @@ import { resolveWaitToolConfig } from "../runs/background/wait-config.ts";
|
|
|
9
9
|
import type { ChildRuntimeConfig } from "../runs/shared/child-runtime-config.ts";
|
|
10
10
|
import { readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
|
|
11
11
|
import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
|
|
12
|
+
import { createNativeSupervisorChannel, NATIVE_SUPERVISOR_TOOL_NAME, resolveSupervisorChannelDir } from "../intercom/native-supervisor-channel.ts";
|
|
13
|
+
import { readStatus } from "../shared/utils.ts";
|
|
12
14
|
import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
|
|
13
15
|
import { createSubagentParamsSchema } from "./schemas.ts";
|
|
14
16
|
import { finalizeToolResult } from "./tool-result.ts";
|
|
15
17
|
import { loadConfig, resolveAsyncByDefault } from "./config.ts";
|
|
16
|
-
import { type Details, type SubagentState } from "../shared/types.ts";
|
|
18
|
+
import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
|
|
17
19
|
|
|
18
20
|
function getSubagentSessionRoot(parentSessionFile: string | null): string {
|
|
19
21
|
if (parentSessionFile) {
|
|
@@ -28,7 +30,7 @@ function expandTilde(p: string): string {
|
|
|
28
30
|
return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
function createChildSafeState(): SubagentState {
|
|
33
|
+
export function createChildSafeState(): SubagentState {
|
|
32
34
|
return {
|
|
33
35
|
baseCwd: "",
|
|
34
36
|
currentSessionId: null,
|
|
@@ -127,7 +129,8 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
|
|
|
127
129
|
}
|
|
128
130
|
inboxState.pendingResults.delete(request.requestId);
|
|
129
131
|
inboxState.seen.add(request.requestId);
|
|
130
|
-
|
|
132
|
+
// Best-effort cleanup of an already-consumed request; the inbox loop tolerates a missing file.
|
|
133
|
+
try { fs.unlinkSync(request.filePath); } catch { /* tolerate a missing inbox file */ }
|
|
131
134
|
} finally {
|
|
132
135
|
inboxState.inFlight.delete(request.requestId);
|
|
133
136
|
}
|
|
@@ -141,7 +144,7 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
|
|
|
141
144
|
return () => clearInterval(timer);
|
|
142
145
|
}
|
|
143
146
|
|
|
144
|
-
/** Register
|
|
147
|
+
/** Register delegation and supervisor replies for fanout-authorized children. */
|
|
145
148
|
export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, childConfig: ChildRuntimeConfig): void {
|
|
146
149
|
if (!childConfig.fanoutChild) return;
|
|
147
150
|
|
|
@@ -156,7 +159,40 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
|
|
|
156
159
|
|
|
157
160
|
const config = loadConfig();
|
|
158
161
|
const waitToolConfig = resolveWaitToolConfig(config.waitTool);
|
|
159
|
-
const state = createChildSafeState();
|
|
162
|
+
const state = childConfig.runtimeState ?? createChildSafeState();
|
|
163
|
+
const asyncChildren = new Map<string, { dir: string; agents: string[] }>();
|
|
164
|
+
const foregroundChannels = new Set<string>();
|
|
165
|
+
const supervisorChannel = createNativeSupervisorChannel(pi, state, {
|
|
166
|
+
getChannelDirs: () => {
|
|
167
|
+
const dirs = new Set<string>();
|
|
168
|
+
for (const run of state.foregroundControls.values()) {
|
|
169
|
+
for (const child of run.activeChildren?.values() ?? []) dirs.add(resolveSupervisorChannelDir(run.runId, child.agent, child.index));
|
|
170
|
+
}
|
|
171
|
+
for (const run of state.foregroundRuns?.values() ?? []) {
|
|
172
|
+
for (const child of run.children) {
|
|
173
|
+
if (child.status === "detached") dirs.add(resolveSupervisorChannelDir(run.runId, child.agent, child.index));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const retiringForeground = [...foregroundChannels].filter(dir => !dirs.has(dir));
|
|
177
|
+
for (const dir of dirs) foregroundChannels.add(dir);
|
|
178
|
+
for (const dir of retiringForeground) dirs.add(dir);
|
|
179
|
+
const retiringAsync: string[] = [];
|
|
180
|
+
for (const [id, child] of asyncChildren) {
|
|
181
|
+
const status = readStatus(child.dir);
|
|
182
|
+
if (status && status.state !== "queued" && status.state !== "running") retiringAsync.push(id);
|
|
183
|
+
for (const [index, agent] of child.agents.entries()) dirs.add(resolveSupervisorChannelDir(id, agent, index));
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
dirs: [...dirs],
|
|
187
|
+
retire: () => {
|
|
188
|
+
for (const dir of retiringForeground) foregroundChannels.delete(dir);
|
|
189
|
+
for (const id of retiringAsync) asyncChildren.delete(id);
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
const hasPendingSupervisorRequest = supervisorChannel.hasPendingRequests;
|
|
195
|
+
childConfig.hasPendingSupervisorRequest = hasPendingSupervisorRequest;
|
|
160
196
|
const executor = createSubagentExecutor({
|
|
161
197
|
pi,
|
|
162
198
|
state,
|
|
@@ -170,6 +206,8 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
|
|
|
170
206
|
discoverAgents,
|
|
171
207
|
allowMutatingManagementActions: false,
|
|
172
208
|
childRuntime: childConfig,
|
|
209
|
+
activateSupervisorTransport: supervisorChannel.activateTransport,
|
|
210
|
+
findPendingAsks: supervisorChannel.findPendingAsks,
|
|
173
211
|
});
|
|
174
212
|
|
|
175
213
|
const params = createSubagentParamsSchema();
|
|
@@ -188,6 +226,31 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
|
|
|
188
226
|
};
|
|
189
227
|
|
|
190
228
|
pi.registerTool(tool);
|
|
229
|
+
let unsubscribeAsyncStarted: (() => void) | undefined;
|
|
230
|
+
pi.on("session_start", (_event, ctx) => {
|
|
231
|
+
supervisorChannel.registerTools();
|
|
232
|
+
// The host applies the explicit allowlist to dynamic registration too.
|
|
233
|
+
if (!pi.getAllTools().some(tool => tool.name === NATIVE_SUPERVISOR_TOOL_NAME)) return;
|
|
234
|
+
// Downward asks belong to this coordinator, not its parent or persisted session file.
|
|
235
|
+
state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
|
|
236
|
+
unsubscribeAsyncStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
|
|
237
|
+
const info = payload as AsyncStartedEvent;
|
|
238
|
+
if (!info.id || !info.asyncDir || info.sessionId !== state.currentSessionId) return;
|
|
239
|
+
const agents = info.agents ?? (info.agent ? [info.agent] : []);
|
|
240
|
+
asyncChildren.set(info.id, { dir: info.asyncDir, agents });
|
|
241
|
+
supervisorChannel.activateTransport();
|
|
242
|
+
});
|
|
243
|
+
supervisorChannel.start();
|
|
244
|
+
supervisorChannel.activateTransport();
|
|
245
|
+
});
|
|
246
|
+
pi.on("session_shutdown", () => {
|
|
247
|
+
unsubscribeAsyncStarted?.();
|
|
248
|
+
asyncChildren.clear();
|
|
249
|
+
foregroundChannels.clear();
|
|
250
|
+
supervisorChannel.dispose();
|
|
251
|
+
if (childConfig.hasPendingSupervisorRequest === hasPendingSupervisorRequest) childConfig.hasPendingSupervisorRequest = undefined;
|
|
252
|
+
state.supervisorOwnerSessionId = null;
|
|
253
|
+
});
|
|
191
254
|
const route = resolveNestedControlRoute(childConfig);
|
|
192
255
|
if (!route) return;
|
|
193
256
|
const listenerCleanupKey = "__piSubagentFanoutChildNestedControlInboxCleanups";
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as net from "node:net";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
7
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import packageJson from "../../package.json" with { type: "json" };
|
|
9
|
+
import { encodeHerdrPiFrame, HERDR_PI_MAX_FRAME_BYTES, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId, type HerdrPiFrame } from "../runs/shared/herdr-pi-protocol.ts";
|
|
10
|
+
import { discoverAgents } from "../agents/agents.ts";
|
|
11
|
+
import { buildSkillInjection, resolveSkills } from "../agents/skills.ts";
|
|
12
|
+
import { buildAgentMemoryInjection } from "../agents/agent-memory.ts";
|
|
13
|
+
import { appendAgentRefinementOverlay } from "../agents/agent-refinements.ts";
|
|
14
|
+
import { rewriteSubagentPrompt } from "../runs/shared/subagent-prompt-runtime.ts";
|
|
15
|
+
import { resolveExistingReadPaths } from "../shared/settings.ts";
|
|
16
|
+
|
|
17
|
+
interface PendingRequest { operation: "prompt" | "steer" | "follow-up" | "abort" | "supervisor-reply"; text?: string; supervisorId?: string }
|
|
18
|
+
interface BridgeContext {
|
|
19
|
+
isIdle(): boolean;
|
|
20
|
+
hasPendingMessages(): boolean;
|
|
21
|
+
getActiveTools?(): string[];
|
|
22
|
+
sessionManager?: { getSessionId?(): string; getSessionFile?(): string | undefined };
|
|
23
|
+
model?: { provider?: string; id?: string };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function gitEvidence(cwd: string): Record<string, unknown> | undefined {
|
|
27
|
+
const run = (args: string[]) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 5_000, maxBuffer: 128 * 1024 });
|
|
28
|
+
const inside = run(["rev-parse", "--is-inside-work-tree"]);
|
|
29
|
+
if (inside.status !== 0) return undefined;
|
|
30
|
+
const head = run(["rev-parse", "HEAD"]); const branch = run(["symbolic-ref", "--quiet", "--short", "HEAD"]); const dirty = run(["status", "--porcelain"]);
|
|
31
|
+
return { ...(head.status === 0 ? { head: head.stdout.trim() } : {}), ...(branch.status === 0 ? { branch: branch.stdout.trim() } : {}), dirty: Boolean(dirty.stdout.trim()) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function resolveRemoteHerdrResources(cwd: string, resources: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false }, remoteDefaultTools: string[] = []): { agent: string; skills: string[]; tools: string[]; systemPrompt: string; inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean } {
|
|
35
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || resources.skills?.some((name) => !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)) || resources.toolCeiling?.some((name) => !/^[A-Za-z0-9_-]{1,64}$/u.test(name)) || (resources.reads !== undefined && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string")))) throw new Error("Remote logical resource names are invalid.");
|
|
36
|
+
const discovered = discoverAgents(cwd, "both").agents.filter((agent) => agent.name === resources.agent || agent.aliases?.includes(resources.agent));
|
|
37
|
+
if (discovered.length !== 1) throw new Error(`Remote agent '${resources.agent}' was not found unambiguously in ${cwd}.`);
|
|
38
|
+
const agent = discovered[0]!; const names = resources.skills ?? agent.skills ?? [];
|
|
39
|
+
const skills = resolveSkills(names, cwd); if (skills.missing.length) throw new Error(`Remote Pi skills not found: ${skills.missing.join(", ")}. Configure them on the saved machine.`);
|
|
40
|
+
const skillPrompt = buildSkillInjection(skills.resolved);
|
|
41
|
+
const reads = resources.reads === undefined ? agent.defaultReads ?? false : resources.reads; const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, cwd) : [];
|
|
42
|
+
const systemPrompt = appendAgentRefinementOverlay(`${agent.systemPrompt}${buildAgentMemoryInjection(agent, cwd)}${skillPrompt ? `\n\n${skillPrompt}` : ""}${readPaths.length ? `\n\n[Read from: ${readPaths.join(", ")}]` : ""}`, { cwd, agentName: agent.name });
|
|
43
|
+
const denied = new Set(agent.excludeTools ?? []); const tools = (agent.tools === undefined ? remoteDefaultTools : agent.tools).filter((tool) => !denied.has(tool) && (!resources.toolCeiling || resources.toolCeiling.includes(tool))); if (agent.tools === undefined && !tools.length) throw new Error(`Remote agent '${agent.name}' resolved no default active tools within the inherited ceiling.`);
|
|
44
|
+
return { agent: agent.name, skills: names, tools, systemPrompt, inheritProjectContext: agent.inheritProjectContext, inheritGlobalContext: agent.inheritGlobalContext, inheritSkills: agent.inheritSkills };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export default function registerHerdrPiBridge(pi: ExtensionAPI): void {
|
|
48
|
+
const runId = validateHerdrPiRunId(process.env[HERDR_PI_RUN_ENV]);
|
|
49
|
+
const runDir = process.env[HERDR_PI_RUNTIME_DIR_ENV];
|
|
50
|
+
if (!runDir || !path.isAbsolute(runDir) || fs.lstatSync(runDir).isSymbolicLink()) throw new Error("Herdr bridge runtime directory was not authoritatively provisioned.");
|
|
51
|
+
fs.chmodSync(runDir, 0o700);
|
|
52
|
+
const socketPath = path.join(runDir, "bridge.sock");
|
|
53
|
+
const manifestPath = path.join(runDir, "manifest.json");
|
|
54
|
+
for (const candidate of [socketPath, manifestPath]) {
|
|
55
|
+
try { const stat = fs.lstatSync(candidate); if (stat.isSymbolicLink()) throw new Error(`Refusing symlink at '${candidate}'.`); fs.rmSync(candidate, { force: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
56
|
+
}
|
|
57
|
+
let client: net.Socket | undefined;
|
|
58
|
+
let context: BridgeContext | undefined;
|
|
59
|
+
let nativeSessionId: string | undefined;
|
|
60
|
+
let finalAssistant: AgentMessage | undefined;
|
|
61
|
+
let activeRequestId: string | undefined;
|
|
62
|
+
let resolvedSystemPrompt: string | undefined;
|
|
63
|
+
let resolvedContextPolicy: { agent: string; inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean } | undefined;
|
|
64
|
+
let configured = false;
|
|
65
|
+
const pending = new Map<string, PendingRequest>();
|
|
66
|
+
const supervisor = new Map<string, { reason: "need_decision" | "interview_request" | "progress_update"; resolve(answer: string): void }>();
|
|
67
|
+
let evidenceCursor = 0; let journalBytes = 0; const journal: HerdrPiFrame[] = [];
|
|
68
|
+
const send = (frame: { type: string; [key: string]: unknown }) => {
|
|
69
|
+
const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: ++evidenceCursor } as HerdrPiFrame; const size = Buffer.byteLength(JSON.stringify(record)); journal.push(record); journalBytes += size; while (journal.length > 512 || journalBytes > 8 * 1024 * 1024) { const removed = journal.shift(); if (removed) journalBytes -= Buffer.byteLength(JSON.stringify(removed)); }
|
|
70
|
+
if (!client || client.destroyed) return;
|
|
71
|
+
client.write(encodeHerdrPiFrame(record));
|
|
72
|
+
};
|
|
73
|
+
const sessionId = (ctx: BridgeContext) => ctx.sessionManager?.getSessionId?.();
|
|
74
|
+
const activeTools = (ctx: BridgeContext) => ctx.getActiveTools?.() ?? [];
|
|
75
|
+
|
|
76
|
+
pi.registerTool({
|
|
77
|
+
name: "contact_supervisor",
|
|
78
|
+
label: "Contact supervisor",
|
|
79
|
+
description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
|
|
80
|
+
parameters: Type.Object({ reason: Type.Union([Type.Literal("need_decision"), Type.Literal("interview_request"), Type.Literal("progress_update")]), message: Type.Optional(Type.String({ maxLength: 65_536 })), interview: Type.Optional(Type.Unknown()) }, { additionalProperties: false }),
|
|
81
|
+
execute: async (_toolCallId, input: { reason: "need_decision" | "interview_request" | "progress_update"; message?: string; interview?: unknown }) => {
|
|
82
|
+
if (input.reason !== "interview_request" && !input.message?.trim()) throw new Error("message is required for supervisor decisions and progress updates.");
|
|
83
|
+
const id = `sup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
84
|
+
send({ type: "supervisor-request", requestId: id, reason: input.reason, message: input.message?.slice(0, 65_536) ?? "", ...(input.interview !== undefined ? { interview: input.interview } : {}), expectsReply: input.reason !== "progress_update", nativeSessionId });
|
|
85
|
+
if (input.reason === "progress_update") { await new Promise<string>((resolve) => supervisor.set(id, { reason: input.reason, resolve })); return { content: [{ type: "text", text: "Supervisor progress update queued." }], details: { delivered: true, requestId: id, reason: input.reason } }; }
|
|
86
|
+
const reason = input.reason as "need_decision" | "interview_request"; const answer = await new Promise<string>((resolve) => supervisor.set(id, { reason, resolve })); const details: Record<string, unknown> = { requestId: id, reason }; if (reason === "interview_request") try { details.structuredReply = JSON.parse(answer.replace(/^```(?:json)?\s*|\s*```$/giu, "")); } catch { details.structuredReplyParseError = "Supervisor interview reply was not valid JSON."; }
|
|
87
|
+
return { content: [{ type: "text", text: `**Reply from supervisor:**\n${answer}` }], details };
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const execute = async (requestId: string, ctx: BridgeContext) => {
|
|
92
|
+
const request = pending.get(requestId);
|
|
93
|
+
if (!request) throw new Error(`Unknown or already consumed bridge request '${requestId}'.`);
|
|
94
|
+
pending.delete(requestId);
|
|
95
|
+
if (sessionId(ctx) !== nativeSessionId) throw new Error("Native Pi session identity changed.");
|
|
96
|
+
send({ type: "accepted", requestId, operation: request.operation, nativeSessionId });
|
|
97
|
+
// SAFETY: pi exposes sendUserMessage/abort on the live host API; narrowed to the two methods this bridge drives.
|
|
98
|
+
const api = pi as unknown as { sendUserMessage(text: string, options?: { deliverAs?: "steer" | "followUp" }): void; abort(): void };
|
|
99
|
+
if (request.operation === "prompt") { activeRequestId = requestId; finalAssistant = undefined; api.sendUserMessage(request.text ?? ""); }
|
|
100
|
+
else if (request.operation === "steer") api.sendUserMessage(request.text ?? "", { deliverAs: "steer" });
|
|
101
|
+
else if (request.operation === "follow-up") api.sendUserMessage(request.text ?? "", { deliverAs: "followUp" });
|
|
102
|
+
else if (request.operation === "abort") api.abort();
|
|
103
|
+
else {
|
|
104
|
+
const entry = request.supervisorId ? supervisor.get(request.supervisorId) : undefined;
|
|
105
|
+
if (!entry) throw new Error("Unknown supervisor request.");
|
|
106
|
+
supervisor.delete(request.supervisorId!); entry.resolve(request.text ?? "");
|
|
107
|
+
}
|
|
108
|
+
send({ type: "control-ack", requestId, operation: request.operation, nativeSessionId });
|
|
109
|
+
};
|
|
110
|
+
// SAFETY: BridgeContext is the same ctx object pi passes to command handlers; the cast only drops the generic wrapper.
|
|
111
|
+
pi.registerCommand("pi-subagents-bridge", { description: "Internal pane-native request dispatch", handler: (args, ctx) => execute(args.trim(), ctx as unknown as BridgeContext) });
|
|
112
|
+
|
|
113
|
+
// SAFETY: pi.on is a typed event emitter; the cast widens it to the dynamic handler signature this bridge registers.
|
|
114
|
+
const on = pi.on as unknown as (name: string, handler: (event: Record<string, unknown>, ctx: BridgeContext) => unknown) => void;
|
|
115
|
+
on("before_agent_start", (event) => resolvedSystemPrompt && resolvedContextPolicy ? { systemPrompt: `${rewriteSubagentPrompt(typeof event.systemPrompt === "string" ? event.systemPrompt : "", { inheritProjectContext: resolvedContextPolicy.inheritProjectContext, inheritGlobalContext: resolvedContextPolicy.inheritGlobalContext, inheritSkills: resolvedContextPolicy.inheritSkills })}\n\n<active_agent name=${JSON.stringify(resolvedContextPolicy.agent)}/>\n\n${resolvedSystemPrompt}` } : undefined);
|
|
116
|
+
on("session_start", (_event, ctx) => {
|
|
117
|
+
context = ctx; nativeSessionId = sessionId(ctx);
|
|
118
|
+
if (!nativeSessionId) throw new Error("Pane-native Pi bridge requires a persisted native session identity.");
|
|
119
|
+
fs.writeFileSync(manifestPath, JSON.stringify({ protocol: HERDR_PI_PROTOCOL, packageVersion: packageJson.version, runId, socketPath, nativeSessionId, pid: process.pid }), { mode: 0o600, flag: "wx" });
|
|
120
|
+
send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: activeTools(ctx), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
|
|
121
|
+
});
|
|
122
|
+
on("message_end", (event) => {
|
|
123
|
+
const message = event.message as AgentMessage | undefined;
|
|
124
|
+
if (message?.role === "assistant") finalAssistant = message;
|
|
125
|
+
send({ type: "event", requestId: activeRequestId, event: { ...event, message }, nativeSessionId });
|
|
126
|
+
});
|
|
127
|
+
on("agent_settled", (_event, ctx) => { const requestId = activeRequestId; send({ type: "settled", requestId, nativeSessionId, idle: ctx.isIdle(), pending: ctx.hasPendingMessages(), finalAssistant, finalGit: gitEvidence(process.cwd()) }); if (ctx.isIdle() && !ctx.hasPendingMessages()) activeRequestId = undefined; });
|
|
128
|
+
on("session_shutdown", () => { server.close(); client?.destroy(); try { fs.rmSync(runDir, { recursive: true, force: true }); } catch { /* Best-effort; the run dir may already be gone. */ } });
|
|
129
|
+
|
|
130
|
+
const server = net.createServer((socket) => {
|
|
131
|
+
if (client && !client.destroyed) { socket.destroy(); return; }
|
|
132
|
+
client = socket; const decoder = new HerdrPiFrameDecoder(); let total = 0;
|
|
133
|
+
for (const record of journal) socket.write(encodeHerdrPiFrame(record));
|
|
134
|
+
socket.on("data", (chunk: Buffer) => {
|
|
135
|
+
total += chunk.byteLength; if (total > HERDR_PI_MAX_FRAME_BYTES * 32) { socket.destroy(new Error("Bridge byte budget exceeded.")); return; }
|
|
136
|
+
try {
|
|
137
|
+
for (const frame of decoder.push(chunk)) {
|
|
138
|
+
if (frame.runId !== runId) throw new Error("Bridge run identity mismatch.");
|
|
139
|
+
if (frame.type === "supervisor-delivered" && typeof frame.requestId === "string") { const entry = supervisor.get(frame.requestId); if (!entry || entry.reason !== "progress_update") throw new Error("Unknown supervisor delivery acknowledgement."); supervisor.delete(frame.requestId); entry.resolve("delivered"); continue; }
|
|
140
|
+
if (frame.type === "configure") {
|
|
141
|
+
if (configured || typeof frame.requestId !== "string" || !frame.resources || typeof frame.resources !== "object") throw new Error("Invalid or duplicate bridge configuration.");
|
|
142
|
+
const resources = frame.resources as { agent?: unknown; skills?: unknown; toolCeiling?: unknown; reads?: unknown };
|
|
143
|
+
const invalidSkills = resources.skills !== undefined && (!Array.isArray(resources.skills) || resources.skills.some((name) => typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)));
|
|
144
|
+
const invalidReads = resources.reads !== undefined && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"));
|
|
145
|
+
if (typeof resources.agent !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || invalidSkills || invalidReads) throw new Error("Remote logical resource names are invalid.");
|
|
146
|
+
const resolved = resolveRemoteHerdrResources(process.cwd(), { agent: resources.agent, ...(resources.skills ? { skills: resources.skills as string[] } : {}), ...(resources.toolCeiling ? { toolCeiling: resources.toolCeiling as string[] } : {}), ...(resources.reads !== undefined ? { reads: resources.reads as string[] | false } : {}) }, context ? activeTools(context) : []); resolvedSystemPrompt = resolved.systemPrompt; resolvedContextPolicy = resolved;
|
|
147
|
+
// SAFETY: setActiveTools is optional on the host API; presence-checked with ?. before use.
|
|
148
|
+
(pi as unknown as { setActiveTools?(tools: string[]): void }).setActiveTools?.(resolved.tools); const acknowledged = context ? activeTools(context) : []; if (acknowledged.some((tool) => !resolved.tools.includes(tool)) || resolved.tools.some((tool) => !acknowledged.includes(tool))) throw new Error("Remote Pi did not apply the resolved active-tool set exactly.");
|
|
149
|
+
configured = true; send({ type: "configured", requestId: frame.requestId, nativeSessionId, agent: resolved.agent, skills: resolved.skills, model: context?.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, tools: acknowledged }); continue;
|
|
150
|
+
}
|
|
151
|
+
if (frame.type !== "prepare" || typeof frame.requestId !== "string" || pending.has(frame.requestId) || !configured) throw new Error("Invalid, duplicate, or unconfigured bridge request.");
|
|
152
|
+
const operation = frame.operation;
|
|
153
|
+
if (!(["prompt", "steer", "follow-up", "abort", "supervisor-reply"] as unknown[]).includes(operation)) throw new Error("Unsupported bridge operation.");
|
|
154
|
+
const text = frame.text; if (text !== undefined && (typeof text !== "string" || Buffer.byteLength(text) > 256 * 1024)) throw new Error("Bridge request text is invalid or too large.");
|
|
155
|
+
pending.set(frame.requestId, { operation: operation as PendingRequest["operation"], ...(text !== undefined ? { text } : {}), ...(typeof frame.supervisorId === "string" ? { supervisorId: frame.supervisorId } : {}) });
|
|
156
|
+
send({ type: "prepared", requestId: frame.requestId, nativeSessionId });
|
|
157
|
+
}
|
|
158
|
+
} catch (error) { socket.destroy(error as Error); }
|
|
159
|
+
});
|
|
160
|
+
socket.on("close", () => { if (client === socket) client = undefined; });
|
|
161
|
+
if (context && nativeSessionId) send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: context.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: activeTools(context), model: context.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
|
|
162
|
+
});
|
|
163
|
+
server.listen(socketPath, () => { fs.chmodSync(socketPath, 0o600); });
|
|
164
|
+
}
|