@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,229 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
|
+
import { readMissionBinding } from "../../missions/lifecycle.ts";
|
|
6
|
+
import { listMissions, missionRecordPath, resolveMissionStoreLocation } from "../../missions/store.ts";
|
|
7
|
+
import type { MissionStoreConfig } from "../../missions/types.ts";
|
|
8
|
+
import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../../policy/authority.ts";
|
|
9
|
+
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
10
|
+
import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
|
|
11
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
12
|
+
import { resolveSubagentRunId } from "../../runs/background/run-id-resolver.ts";
|
|
13
|
+
import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode, type HerdrResult } from "./client.ts";
|
|
14
|
+
|
|
15
|
+
export const HERDR_INSPECTOR_ACTIONS = ["inspector.open", "inspector.status", "inspector.close"] as const;
|
|
16
|
+
export type HerdrInspectorAction = typeof HERDR_INSPECTOR_ACTIONS[number];
|
|
17
|
+
|
|
18
|
+
export interface HerdrInspectorBinding {
|
|
19
|
+
schemaVersion: 1;
|
|
20
|
+
kind: "herdr-inspector";
|
|
21
|
+
runId: string;
|
|
22
|
+
asyncDir: string;
|
|
23
|
+
childIndex?: number;
|
|
24
|
+
missionId?: string;
|
|
25
|
+
missionPath?: string;
|
|
26
|
+
paneId: string;
|
|
27
|
+
openedAt: string;
|
|
28
|
+
lastFocusedAt?: string;
|
|
29
|
+
herdrVersion?: string;
|
|
30
|
+
command: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface InspectorParams {
|
|
34
|
+
id?: string;
|
|
35
|
+
runId?: string;
|
|
36
|
+
dir?: string;
|
|
37
|
+
index?: number;
|
|
38
|
+
focus?: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface InspectorDeps {
|
|
42
|
+
state?: SubagentState;
|
|
43
|
+
asyncDirRoot?: string;
|
|
44
|
+
resultsDir?: string;
|
|
45
|
+
client?: HerdrClient;
|
|
46
|
+
missions?: MissionStoreConfig;
|
|
47
|
+
authorityPolicy?: AuthorityPolicyConfig;
|
|
48
|
+
cwd: string;
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
now?: () => Date;
|
|
51
|
+
runnerPath?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function result(text: string, isError = false): AgentToolResult<Details> {
|
|
55
|
+
return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}), details: { mode: "management", results: [] } };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function formatHerdrError(input: { code: HerdrErrorCode; message: string }): string {
|
|
59
|
+
return `Herdr inspector error (${input.code}): ${input.message}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function bindingPath(asyncDir: string, index?: number): string {
|
|
63
|
+
return path.join(asyncDir, "inspectors", `herdr${index === undefined ? "" : `-${index}`}.json`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseBinding(value: unknown): HerdrInspectorBinding | undefined {
|
|
67
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
68
|
+
const input = value as Partial<HerdrInspectorBinding>;
|
|
69
|
+
if (input.schemaVersion !== 1 || input.kind !== "herdr-inspector") return undefined;
|
|
70
|
+
if (typeof input.runId !== "string" || typeof input.asyncDir !== "string" || typeof input.paneId !== "string" || typeof input.openedAt !== "string" || typeof input.command !== "string") return undefined;
|
|
71
|
+
if (input.childIndex !== undefined && (!Number.isInteger(input.childIndex) || input.childIndex < 0)) return undefined;
|
|
72
|
+
return input as HerdrInspectorBinding;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function readHerdrInspectorBinding(asyncDir: string, index?: number): HerdrInspectorBinding | undefined {
|
|
76
|
+
try { return parseBinding(JSON.parse(fs.readFileSync(bindingPath(asyncDir, index), "utf-8"))); } catch { return undefined; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function extractPaneId(value: unknown): string | undefined {
|
|
80
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
81
|
+
const record = value as Record<string, unknown>;
|
|
82
|
+
const pane = record.pane && typeof record.pane === "object" && !Array.isArray(record.pane) ? record.pane as Record<string, unknown> : record;
|
|
83
|
+
for (const key of ["pane_id", "paneId", "id"]) if (typeof pane[key] === "string") return pane[key];
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function shellQuote(value: string): string {
|
|
88
|
+
if (process.platform === "win32") return `"${value.replaceAll('"', '\\"')}"`;
|
|
89
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean }): string {
|
|
93
|
+
const args = [process.execPath, input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop)];
|
|
94
|
+
if (input.index !== undefined) args.push("--index", String(input.index));
|
|
95
|
+
if (input.missionPath) args.push("--mission-path", input.missionPath);
|
|
96
|
+
return `${process.platform === "win32" ? "& " : ""}${args.map(shellQuote).join(" ")}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function missionForRun(asyncDir: string, cwd: string, config: MissionStoreConfig | undefined, runId: string): { id: string; path: string } | undefined {
|
|
100
|
+
try {
|
|
101
|
+
const binding = readMissionBinding(asyncDir);
|
|
102
|
+
if (binding) return { id: binding.missionId, path: missionRecordPath(binding.location, binding.missionId) };
|
|
103
|
+
const location = resolveMissionStoreLocation({ projectRoot: cwd, ...(config ? { config } : {}) });
|
|
104
|
+
const mission = listMissions(location).records.find((record) => record.runs.some((run) => run.runId === runId));
|
|
105
|
+
return mission ? { id: mission.id, path: missionRecordPath(location, mission.id) } : undefined;
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function pathWithin(base: string, candidate: string): boolean {
|
|
112
|
+
const resolvedBase = path.resolve(base);
|
|
113
|
+
const resolvedCandidate = path.resolve(candidate);
|
|
114
|
+
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isTrustedAsyncDir(asyncDir: string, deps: InspectorDeps): boolean {
|
|
118
|
+
try {
|
|
119
|
+
if (fs.lstatSync(asyncDir).isSymbolicLink() || !fs.statSync(asyncDir).isDirectory()) return false;
|
|
120
|
+
const realDir = fs.realpathSync(asyncDir);
|
|
121
|
+
const registered = [...(deps.state?.asyncJobs.values() ?? [])].some((job) => {
|
|
122
|
+
try { return fs.realpathSync(job.asyncDir) === realDir; } catch { return false; }
|
|
123
|
+
});
|
|
124
|
+
if (registered) return true;
|
|
125
|
+
const root = deps.asyncDirRoot ?? DIRS.async;
|
|
126
|
+
if (!fs.existsSync(root) || !pathWithin(root, asyncDir)) return false;
|
|
127
|
+
return pathWithin(fs.realpathSync(root), realDir);
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function resolveAsyncTarget(params: InspectorParams, deps: InspectorDeps): { runId: string; asyncDir: string } | { error: string } {
|
|
134
|
+
const requestedId = params.id ?? params.runId;
|
|
135
|
+
if (params.dir) {
|
|
136
|
+
const asyncDir = path.resolve(params.dir);
|
|
137
|
+
if (!isTrustedAsyncDir(asyncDir, deps)) return { error: `Async run directory '${asyncDir}' is outside trusted run roots.` };
|
|
138
|
+
const status = readStatus(asyncDir);
|
|
139
|
+
if (!status) return { error: `No async run status found in '${asyncDir}'.` };
|
|
140
|
+
if (requestedId && requestedId !== status.runId && !status.runId.startsWith(requestedId)) return { error: `Run '${requestedId}' does not match status run '${status.runId}'.` };
|
|
141
|
+
return { runId: status.runId, asyncDir };
|
|
142
|
+
}
|
|
143
|
+
if (!requestedId) return { error: "Herdr inspector actions require id or dir." };
|
|
144
|
+
try {
|
|
145
|
+
const resolved = resolveSubagentRunId(requestedId, { state: deps.state, asyncDirRoot: deps.asyncDirRoot ?? DIRS.async, resultsDir: deps.resultsDir ?? DIRS.results });
|
|
146
|
+
if (!resolved) return { error: `No subagent run found for '${requestedId}'.` };
|
|
147
|
+
if (resolved.kind !== "async" || !resolved.location.asyncDir) return { error: `Run '${resolved.id}' is not an inspectable async run with lifecycle artifacts.` };
|
|
148
|
+
return { runId: resolved.id, asyncDir: resolved.location.asyncDir };
|
|
149
|
+
} catch (cause) {
|
|
150
|
+
return { error: cause instanceof Error ? cause.message : String(cause) };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function paneExists(client: HerdrClient, paneId: string, signal?: AbortSignal): Promise<HerdrResult<unknown>> {
|
|
155
|
+
return client.run(["pane", "get", paneId], { timeoutMs: 5_000, signal });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function handleHerdrInspectorAction(action: HerdrInspectorAction, params: InspectorParams, deps: InspectorDeps): Promise<AgentToolResult<Details>> {
|
|
159
|
+
const target = resolveAsyncTarget(params, deps);
|
|
160
|
+
if ("error" in target) return result(target.error, true);
|
|
161
|
+
const status = readStatus(target.asyncDir);
|
|
162
|
+
if (!status) return result(`No lifecycle status exists for async run '${target.runId}'.`, true);
|
|
163
|
+
if (params.index !== undefined && (params.index < 0 || params.index >= (status.steps?.length ?? 0))) {
|
|
164
|
+
return result(`Async run '${target.runId}' has ${status.steps?.length ?? 0} children. Index ${params.index} is out of range.`, true);
|
|
165
|
+
}
|
|
166
|
+
const existing = readHerdrInspectorBinding(target.asyncDir, params.index);
|
|
167
|
+
const client = deps.client ?? createHerdrClient();
|
|
168
|
+
|
|
169
|
+
if (action === "inspector.status") {
|
|
170
|
+
if (!existing) return result(`No Herdr inspector binding exists for async run ${target.runId}${params.index === undefined ? "" : ` child ${params.index}`}.`);
|
|
171
|
+
const live = await paneExists(client, existing.paneId, deps.signal);
|
|
172
|
+
if (live.ok === false) return result(`${formatHerdrError(live.error)}\nBinding: ${bindingPath(target.asyncDir, params.index)}\nRun state remains authoritative: ${status.state}.`, true);
|
|
173
|
+
return result(`Herdr inspector ${existing.paneId} is open for async run ${target.runId}.\nRun state: ${status.state}\nBinding: ${bindingPath(target.asyncDir, params.index)}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
if (action === "inspector.close") {
|
|
178
|
+
if (!existing) return result(`No Herdr inspector binding exists for async run ${target.runId}.`);
|
|
179
|
+
const closed = await client.run(["pane", "close", existing.paneId], { timeoutMs: 10_000, signal: deps.signal });
|
|
180
|
+
if (closed.ok === false && closed.error.code !== "NOT_FOUND" && closed.error.code !== "PANE_GONE") return result(formatHerdrError(closed.error), true);
|
|
181
|
+
fs.rmSync(bindingPath(target.asyncDir, params.index), { force: true });
|
|
182
|
+
return result(`Closed Herdr inspector pane ${existing.paneId} for async run ${target.runId}. The subagent run was not stopped.`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const detected = await detectHerdr(client, deps.signal);
|
|
186
|
+
if (detected.ok === false) return result(formatHerdrError(detected.error), true);
|
|
187
|
+
if (existing) {
|
|
188
|
+
const live = await paneExists(client, existing.paneId, deps.signal);
|
|
189
|
+
if (live.ok) return result(`Herdr inspector pane ${existing.paneId} is already open for async run ${target.runId}.${params.focus ? " Herdr cannot refocus an arbitrary raw pane id; select it in the Herdr UI." : ""}`);
|
|
190
|
+
}
|
|
191
|
+
const splitArgs = ["pane", "split", "--current", "--direction", "right", "--cwd", status.cwd ?? deps.cwd];
|
|
192
|
+
if (params.focus !== false) splitArgs.push("--focus");
|
|
193
|
+
const split = await client.run(splitArgs, { timeoutMs: 15_000, signal: deps.signal });
|
|
194
|
+
if (split.ok === false) return result(formatHerdrError(split.error), true);
|
|
195
|
+
const paneId = extractPaneId(split.data);
|
|
196
|
+
if (!paneId) return result("Herdr inspector error (PANE_GONE): pane split returned no pane id.", true);
|
|
197
|
+
const mission = missionForRun(target.asyncDir, deps.cwd, deps.missions, target.runId);
|
|
198
|
+
const runnerPath = deps.runnerPath ?? fileURLToPath(new URL("../../../inspector-runner.mjs", import.meta.url));
|
|
199
|
+
const command = inspectorCommand({
|
|
200
|
+
runnerPath,
|
|
201
|
+
asyncDir: target.asyncDir,
|
|
202
|
+
runId: target.runId,
|
|
203
|
+
index: params.index,
|
|
204
|
+
missionPath: mission?.path,
|
|
205
|
+
allowSteer: resolveAuthorityDecision({ action: "steerRun", policy: deps.authorityPolicy }) === "auto",
|
|
206
|
+
allowStop: resolveAuthorityDecision({ action: "stopRun", policy: deps.authorityPolicy }) === "auto",
|
|
207
|
+
});
|
|
208
|
+
const started = await client.run(["pane", "run", paneId, command], { timeoutMs: 15_000, signal: deps.signal });
|
|
209
|
+
if (started.ok === false) {
|
|
210
|
+
await client.run(["pane", "close", paneId], { timeoutMs: 5_000 });
|
|
211
|
+
return result(formatHerdrError(started.error), true);
|
|
212
|
+
}
|
|
213
|
+
const now = (deps.now?.() ?? new Date()).toISOString();
|
|
214
|
+
const binding: HerdrInspectorBinding = {
|
|
215
|
+
schemaVersion: 1,
|
|
216
|
+
kind: "herdr-inspector",
|
|
217
|
+
runId: target.runId,
|
|
218
|
+
asyncDir: target.asyncDir,
|
|
219
|
+
...(params.index !== undefined ? { childIndex: params.index } : {}),
|
|
220
|
+
...(mission ? { missionId: mission.id, missionPath: mission.path } : {}),
|
|
221
|
+
paneId,
|
|
222
|
+
openedAt: now,
|
|
223
|
+
...(params.focus !== false ? { lastFocusedAt: now } : {}),
|
|
224
|
+
herdrVersion: detected.data.versionText,
|
|
225
|
+
command,
|
|
226
|
+
};
|
|
227
|
+
writeAtomicJson(bindingPath(target.asyncDir, params.index), binding);
|
|
228
|
+
return result(`Opened read-only Herdr inspector pane ${paneId} for async run ${target.runId}. Closing the pane does not stop the run.\nControls inside the pane: steer <message>, stop, status.`);
|
|
229
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export type HerdrErrorCode =
|
|
4
|
+
| "HERDR_UNAVAILABLE"
|
|
5
|
+
| "HERDR_UNSUPPORTED_VERSION"
|
|
6
|
+
| "PANE_GONE"
|
|
7
|
+
| "NOT_FOUND"
|
|
8
|
+
| "TIMEOUT"
|
|
9
|
+
| "VALIDATION_ERROR";
|
|
10
|
+
|
|
11
|
+
export type HerdrResult<T> =
|
|
12
|
+
| { ok: true; data: T }
|
|
13
|
+
| { ok: false; error: { code: HerdrErrorCode; message: string; details?: unknown } };
|
|
14
|
+
|
|
15
|
+
export interface HerdrClient {
|
|
16
|
+
run<T = unknown>(args: string[], options?: { timeoutMs?: number; signal?: AbortSignal; textOk?: boolean }): Promise<HerdrResult<T>>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type SpawnHerdr = (command: string, args: readonly string[], options: { shell: false; windowsHide: true; env: NodeJS.ProcessEnv }) => ChildProcess;
|
|
20
|
+
|
|
21
|
+
function error(code: HerdrErrorCode, message: string, details?: unknown): HerdrResult<never> {
|
|
22
|
+
return { ok: false, error: { code, message, ...(details !== undefined ? { details } : {}) } };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseLastJson(value: string): unknown | undefined {
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
if (!trimmed) return undefined;
|
|
28
|
+
try { return JSON.parse(trimmed) as unknown; } catch {}
|
|
29
|
+
for (const line of trimmed.split(/\r?\n/).reverse()) {
|
|
30
|
+
try { return JSON.parse(line) as unknown; } catch {}
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function normalizeCode(raw: unknown): HerdrErrorCode {
|
|
36
|
+
const code = String(raw ?? "").toLowerCase();
|
|
37
|
+
if (code.includes("timeout") || code.includes("timed_out")) return "TIMEOUT";
|
|
38
|
+
if (code.includes("gone")) return "PANE_GONE";
|
|
39
|
+
if (code.includes("not_found") || code.includes("not-found") || code === "no_such_pane") return "NOT_FOUND";
|
|
40
|
+
return "VALIDATION_ERROR";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createHerdrClient(options: { bin?: string; spawn?: SpawnHerdr } = {}): HerdrClient {
|
|
44
|
+
const bin = options.bin ?? process.env.HERDR_BIN ?? "herdr";
|
|
45
|
+
const spawnImpl = options.spawn ?? spawn;
|
|
46
|
+
return {
|
|
47
|
+
run<T>(args: string[], runOptions: { timeoutMs?: number; signal?: AbortSignal; textOk?: boolean } = {}): Promise<HerdrResult<T>> {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
let child: ChildProcess;
|
|
50
|
+
try {
|
|
51
|
+
child = spawnImpl(bin, args, { shell: false, windowsHide: true, env: process.env });
|
|
52
|
+
} catch (cause) {
|
|
53
|
+
const code = (cause as NodeJS.ErrnoException | undefined)?.code;
|
|
54
|
+
resolve(error("HERDR_UNAVAILABLE", code === "ENOENT"
|
|
55
|
+
? "Herdr is not installed or is not on PATH. Install Herdr 0.7.5+ or set HERDR_BIN."
|
|
56
|
+
: `Failed to start Herdr: ${cause instanceof Error ? cause.message : String(cause)}`));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
let stdout = "";
|
|
60
|
+
let stderr = "";
|
|
61
|
+
let settled = false;
|
|
62
|
+
const finish = (result: HerdrResult<T>) => {
|
|
63
|
+
if (settled) return;
|
|
64
|
+
settled = true;
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
runOptions.signal?.removeEventListener("abort", abort);
|
|
67
|
+
resolve(result);
|
|
68
|
+
};
|
|
69
|
+
const abort = () => {
|
|
70
|
+
try { child.kill(); } catch {}
|
|
71
|
+
finish(error("TIMEOUT", `Herdr command '${args.join(" ")}' was aborted.`));
|
|
72
|
+
};
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
try { child.kill(); } catch {}
|
|
75
|
+
finish(error("TIMEOUT", `Herdr command '${args.join(" ")}' timed out after ${runOptions.timeoutMs ?? 15_000}ms.`));
|
|
76
|
+
}, runOptions.timeoutMs ?? 15_000);
|
|
77
|
+
timer.unref?.();
|
|
78
|
+
if (runOptions.signal?.aborted) abort();
|
|
79
|
+
else runOptions.signal?.addEventListener("abort", abort, { once: true });
|
|
80
|
+
child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
|
|
81
|
+
child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
|
|
82
|
+
child.on("error", (cause) => {
|
|
83
|
+
const code = (cause as NodeJS.ErrnoException).code;
|
|
84
|
+
finish(error("HERDR_UNAVAILABLE", code === "ENOENT"
|
|
85
|
+
? "Herdr is not installed or is not on PATH. Install Herdr 0.7.5+ or set HERDR_BIN."
|
|
86
|
+
: `Failed to run Herdr: ${cause.message}`));
|
|
87
|
+
});
|
|
88
|
+
child.on("close", (exitCode) => {
|
|
89
|
+
const parsed = parseLastJson(stdout) ?? (exitCode === 0 ? undefined : parseLastJson(stderr));
|
|
90
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && "error" in parsed) {
|
|
91
|
+
const raw = (parsed as { error?: { code?: unknown; message?: unknown } }).error;
|
|
92
|
+
finish(error(normalizeCode(raw?.code), String(raw?.message ?? "Herdr command failed."), raw));
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (exitCode === 0) {
|
|
96
|
+
if (parsed !== undefined) {
|
|
97
|
+
const envelope = parsed as { result?: unknown };
|
|
98
|
+
finish({ ok: true, data: (envelope.result ?? parsed) as T });
|
|
99
|
+
} else if (runOptions.textOk) finish({ ok: true, data: stdout.trim() as T });
|
|
100
|
+
else finish({ ok: true, data: {} as T });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const message = stderr.split(/\r?\n/).find((line) => line.trim())?.trim() ?? `Herdr exited with code ${exitCode}.`;
|
|
104
|
+
finish(error("VALIDATION_ERROR", message, { exitCode }));
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface HerdrVersion { major: number; minor: number; patch: number }
|
|
112
|
+
|
|
113
|
+
export function parseHerdrVersion(value: string): HerdrVersion | undefined {
|
|
114
|
+
const match = /(\d+)\.(\d+)\.(\d+)/.exec(value);
|
|
115
|
+
return match ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) } : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function supportsRawPanes(version: HerdrVersion): boolean {
|
|
119
|
+
return version.major > 0 || version.minor > 7 || (version.minor === 7 && version.patch >= 5);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function detectHerdr(client: HerdrClient, signal?: AbortSignal): Promise<HerdrResult<{ version: HerdrVersion; versionText: string }>> {
|
|
123
|
+
const result = await client.run<string>(["--version"], { timeoutMs: 3_000, signal, textOk: true });
|
|
124
|
+
if (result.ok === false) return result;
|
|
125
|
+
const versionText = typeof result.data === "string" ? result.data : JSON.stringify(result.data);
|
|
126
|
+
const version = parseHerdrVersion(versionText);
|
|
127
|
+
if (!version) return error("VALIDATION_ERROR", `Could not parse the Herdr version from '${versionText}'.`);
|
|
128
|
+
if (!supportsRawPanes(version)) return error("HERDR_UNSUPPORTED_VERSION", `Herdr ${versionText} does not support raw inspector panes. Upgrade to Herdr 0.7.5 or newer.`);
|
|
129
|
+
return { ok: true, data: { version, versionText } };
|
|
130
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as readline from "node:readline";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parseMissionRecord } from "../../missions/store.ts";
|
|
6
|
+
import type { MissionRecord } from "../../missions/types.ts";
|
|
7
|
+
import { requestAsyncSteer, requestAsyncStop } from "../../runs/background/control-channel.ts";
|
|
8
|
+
import { formatAsyncRunTranscript } from "../../runs/background/fleet-view.ts";
|
|
9
|
+
import type { AsyncStatus } from "../../shared/types.ts";
|
|
10
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
11
|
+
|
|
12
|
+
export interface RunnerOptions {
|
|
13
|
+
asyncDir: string;
|
|
14
|
+
runId: string;
|
|
15
|
+
index?: number;
|
|
16
|
+
missionPath?: string;
|
|
17
|
+
refreshMs: number;
|
|
18
|
+
allowSteer?: boolean;
|
|
19
|
+
allowStop?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function readMission(filePath: string | undefined): MissionRecord | undefined {
|
|
23
|
+
if (!filePath) return undefined;
|
|
24
|
+
try { return parseMissionRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")), filePath); } catch { return undefined; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir: string; index?: number; mission?: MissionRecord; allowSteer?: boolean; allowStop?: boolean }): string {
|
|
28
|
+
const { status, asyncDir, mission } = input;
|
|
29
|
+
const lines = [
|
|
30
|
+
`pi-subagents inspector for ${status.runId}`,
|
|
31
|
+
"This pane mirrors lifecycle artifacts; closing it does not stop the run.",
|
|
32
|
+
"",
|
|
33
|
+
];
|
|
34
|
+
if (mission) {
|
|
35
|
+
lines.push(`Mission: ${mission.title} (${mission.status})`, `Mission id: ${mission.id}`);
|
|
36
|
+
const open = mission.decisions.filter((decision) => decision.status === "open");
|
|
37
|
+
if (open.length) lines.push(`Open decisions: ${open.map((decision) => `${decision.id}: ${decision.title}`).join(" | ")}`);
|
|
38
|
+
lines.push("");
|
|
39
|
+
}
|
|
40
|
+
lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60 }));
|
|
41
|
+
const controls = [input.allowSteer === false ? undefined : "steer <message>", input.allowStop === false ? undefined : "stop", "status"].filter(Boolean);
|
|
42
|
+
lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom).");
|
|
43
|
+
return lines.join("\n");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseArgs(argv: string[]): RunnerOptions {
|
|
47
|
+
const values = new Map<string, string>();
|
|
48
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
49
|
+
const key = argv[index];
|
|
50
|
+
const value = argv[index + 1];
|
|
51
|
+
if (!key?.startsWith("--") || value === undefined) throw new Error(`Invalid inspector argument '${key ?? ""}'.`);
|
|
52
|
+
values.set(key, value);
|
|
53
|
+
}
|
|
54
|
+
const asyncDir = values.get("--async-dir");
|
|
55
|
+
const runId = values.get("--run-id");
|
|
56
|
+
if (!asyncDir || !runId) throw new Error("Inspector requires --async-dir and --run-id.");
|
|
57
|
+
const indexRaw = values.get("--index");
|
|
58
|
+
const childIndex = indexRaw === undefined ? undefined : Number(indexRaw);
|
|
59
|
+
if (childIndex !== undefined && (!Number.isInteger(childIndex) || childIndex < 0)) throw new Error("--index must be a non-negative integer.");
|
|
60
|
+
const refreshRaw = values.get("--refresh-ms");
|
|
61
|
+
const refreshMs = refreshRaw === undefined ? 1_500 : Number(refreshRaw);
|
|
62
|
+
if (!Number.isInteger(refreshMs) || refreshMs < 250) throw new Error("--refresh-ms must be an integer >= 250.");
|
|
63
|
+
return {
|
|
64
|
+
asyncDir: path.resolve(asyncDir),
|
|
65
|
+
runId,
|
|
66
|
+
...(childIndex !== undefined ? { index: childIndex } : {}),
|
|
67
|
+
...(values.get("--mission-path") ? { missionPath: path.resolve(values.get("--mission-path")!) } : {}),
|
|
68
|
+
refreshMs,
|
|
69
|
+
allowSteer: values.get("--allow-steer") !== "false",
|
|
70
|
+
allowStop: values.get("--allow-stop") !== "false",
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function isTerminal(status: AsyncStatus): boolean {
|
|
75
|
+
return status.state !== "queued" && status.state !== "running";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function submitInspectorControl(options: RunnerOptions, line: string): string {
|
|
79
|
+
const command = line.trim();
|
|
80
|
+
if (!command || command === "status") return "Status refreshed.";
|
|
81
|
+
const status = readStatus(options.asyncDir);
|
|
82
|
+
if (!status || status.runId !== options.runId) throw new Error(`Lifecycle status for run '${options.runId}' is unavailable.`);
|
|
83
|
+
if (command === "stop") {
|
|
84
|
+
if (options.allowStop === false) throw new Error("Authority policy does not allow stop from this inspector.");
|
|
85
|
+
if (isTerminal(status)) throw new Error(`Run '${options.runId}' is ${status.state} and cannot be stopped.`);
|
|
86
|
+
requestAsyncStop(options.asyncDir, { source: "herdr-inspector" });
|
|
87
|
+
return `Stop requested for run ${options.runId}.`;
|
|
88
|
+
}
|
|
89
|
+
if (command.startsWith("steer ")) {
|
|
90
|
+
if (options.allowSteer === false) throw new Error("Authority policy does not allow steer from this inspector.");
|
|
91
|
+
const message = command.slice("steer ".length).trim();
|
|
92
|
+
if (!message) throw new Error("steer requires a message.");
|
|
93
|
+
if (isTerminal(status)) throw new Error(`Run '${options.runId}' is ${status.state} and cannot be steered.`);
|
|
94
|
+
const runningIndexes = (status.steps ?? []).map((step, index) => step.status === "running" ? index : undefined).filter((index): index is number => index !== undefined);
|
|
95
|
+
const targetIndex = options.index ?? (status.mode === "single" ? 0 : undefined);
|
|
96
|
+
if (targetIndex === undefined && runningIndexes.length === 0) throw new Error("No running child is available to steer. Open a child-specific inspector for a pending child.");
|
|
97
|
+
requestAsyncSteer(options.asyncDir, {
|
|
98
|
+
message,
|
|
99
|
+
...(targetIndex !== undefined ? { targetIndex } : { targetIndexes: runningIndexes }),
|
|
100
|
+
source: "herdr-inspector",
|
|
101
|
+
});
|
|
102
|
+
return `Steering queued for run ${options.runId}.`;
|
|
103
|
+
}
|
|
104
|
+
if (command.startsWith("reply ")) throw new Error("Supervisor replies are owned by the parent Pi session; use subagent_supervisor/intercom there.");
|
|
105
|
+
throw new Error("Unknown control. Use steer <message>, stop, or status.");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function runInspector(argv = process.argv.slice(2)): void {
|
|
109
|
+
const options = parseArgs(argv);
|
|
110
|
+
let notice = "";
|
|
111
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
112
|
+
const render = () => {
|
|
113
|
+
const status = readStatus(options.asyncDir);
|
|
114
|
+
if (!status || status.runId !== options.runId) {
|
|
115
|
+
process.stdout.write(`\x1b[2J\x1b[Hpi-subagents inspector\n\nLifecycle status for ${options.runId} is unavailable.\n`);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
process.stdout.write(`\x1b[2J\x1b[H${formatInspectorDashboard({ status, asyncDir: options.asyncDir, index: options.index, mission: readMission(options.missionPath), allowSteer: options.allowSteer, allowStop: options.allowStop })}${notice ? `\n\n${notice}` : ""}\n> `);
|
|
119
|
+
if (isTerminal(status) && timer) {
|
|
120
|
+
clearInterval(timer);
|
|
121
|
+
timer = undefined;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
|
|
125
|
+
rl.on("line", (line) => {
|
|
126
|
+
try { notice = submitInspectorControl(options, line); } catch (cause) { notice = `Control error: ${cause instanceof Error ? cause.message : String(cause)}`; }
|
|
127
|
+
render();
|
|
128
|
+
});
|
|
129
|
+
render();
|
|
130
|
+
if (!isTerminal(readStatus(options.asyncDir) ?? { state: "failed" } as AsyncStatus)) {
|
|
131
|
+
timer = setInterval(render, options.refreshMs);
|
|
132
|
+
timer.unref?.();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
|
|
137
|
+
try { runInspector(); } catch (cause) {
|
|
138
|
+
process.stderr.write(`Herdr inspector failed: ${cause instanceof Error ? cause.message : String(cause)}\n`);
|
|
139
|
+
process.exitCode = 1;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import { getPiSpawnCommand } from "../../runs/shared/pi-spawn.ts";
|
|
5
|
+
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
6
|
+
import type { Details } from "../../shared/types.ts";
|
|
7
|
+
import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode, type HerdrResult } from "./client.ts";
|
|
8
|
+
|
|
9
|
+
export const HERDR_PROJECT_PANE_ACTIONS = ["project.open", "project.status", "project.close"] as const;
|
|
10
|
+
export type HerdrProjectPaneAction = typeof HERDR_PROJECT_PANE_ACTIONS[number];
|
|
11
|
+
|
|
12
|
+
export interface HerdrProjectPaneBinding {
|
|
13
|
+
schemaVersion: 1;
|
|
14
|
+
kind: "herdr-project-pane";
|
|
15
|
+
projectRoot: string;
|
|
16
|
+
paneId: string;
|
|
17
|
+
openedAt: string;
|
|
18
|
+
lastFocusedAt?: string;
|
|
19
|
+
herdrVersion?: string;
|
|
20
|
+
command: string;
|
|
21
|
+
startupMessage?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface ProjectPaneParams {
|
|
25
|
+
cwd?: string;
|
|
26
|
+
message?: string;
|
|
27
|
+
focus?: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface ProjectPaneDeps {
|
|
31
|
+
cwd: string;
|
|
32
|
+
client?: HerdrClient;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
now?: () => Date;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function result(text: string, isError = false): AgentToolResult<Details> {
|
|
38
|
+
return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}), details: { mode: "management", results: [] } };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function formatHerdrError(input: { code: HerdrErrorCode; message: string }): string {
|
|
42
|
+
return `Herdr project pane error (${input.code}): ${input.message}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function projectPaneDir(projectRoot: string): string {
|
|
46
|
+
return path.join(projectRoot, ".pi-subagents", "project-panes");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function bindingPath(projectRoot: string): string {
|
|
50
|
+
return path.join(projectPaneDir(projectRoot), "herdr.json");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseBinding(value: unknown): HerdrProjectPaneBinding | undefined {
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
55
|
+
const input = value as Partial<HerdrProjectPaneBinding>;
|
|
56
|
+
if (input.schemaVersion !== 1 || input.kind !== "herdr-project-pane") return undefined;
|
|
57
|
+
if (typeof input.projectRoot !== "string" || typeof input.paneId !== "string" || typeof input.openedAt !== "string" || typeof input.command !== "string") return undefined;
|
|
58
|
+
return input as HerdrProjectPaneBinding;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function readHerdrProjectPaneBinding(projectRoot: string): HerdrProjectPaneBinding | undefined {
|
|
62
|
+
try { return parseBinding(JSON.parse(fs.readFileSync(bindingPath(projectRoot), "utf-8"))); } catch { return undefined; }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function extractPaneId(value: unknown): string | undefined {
|
|
66
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
67
|
+
const record = value as Record<string, unknown>;
|
|
68
|
+
const pane = record.pane && typeof record.pane === "object" && !Array.isArray(record.pane) ? record.pane as Record<string, unknown> : record;
|
|
69
|
+
for (const key of ["pane_id", "paneId", "id"]) if (typeof pane[key] === "string") return pane[key];
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function shellQuote(value: string): string {
|
|
74
|
+
if (process.platform === "win32") return `"${value.replaceAll('"', '\\"')}"`;
|
|
75
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function resolveProjectRoot(params: ProjectPaneParams, deps: ProjectPaneDeps): string | { error: string } {
|
|
79
|
+
const requested = params.cwd?.trim() || deps.cwd;
|
|
80
|
+
const resolved = path.resolve(requested);
|
|
81
|
+
try {
|
|
82
|
+
const stat = fs.statSync(resolved);
|
|
83
|
+
if (!stat.isDirectory()) return { error: `Project pane target '${resolved}' is not a directory.` };
|
|
84
|
+
return fs.realpathSync(resolved);
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
return { error: `Project pane target '${resolved}' is unavailable: ${cause instanceof Error ? cause.message : String(cause)}` };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function paneExists(client: HerdrClient, paneId: string, signal?: AbortSignal): Promise<HerdrResult<unknown>> {
|
|
91
|
+
return client.run(["pane", "get", paneId], { timeoutMs: 5_000, signal });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function projectPaneCommand(message: string | undefined): string {
|
|
95
|
+
const args = message?.trim() ? [message.trim()] : [];
|
|
96
|
+
const command = getPiSpawnCommand(args);
|
|
97
|
+
return `${process.platform === "win32" ? "& " : ""}${[command.command, ...command.args].map(shellQuote).join(" ")}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function handleHerdrProjectPaneAction(action: HerdrProjectPaneAction, params: ProjectPaneParams, deps: ProjectPaneDeps): Promise<AgentToolResult<Details>> {
|
|
101
|
+
const projectRoot = resolveProjectRoot(params, deps);
|
|
102
|
+
if (typeof projectRoot !== "string") return result(projectRoot.error, true);
|
|
103
|
+
const client = deps.client ?? createHerdrClient();
|
|
104
|
+
const existing = readHerdrProjectPaneBinding(projectRoot);
|
|
105
|
+
|
|
106
|
+
if (action === "project.status") {
|
|
107
|
+
if (!existing) return result(`No Herdr project pane binding exists for ${projectRoot}.`);
|
|
108
|
+
const live = await paneExists(client, existing.paneId, deps.signal);
|
|
109
|
+
if (live.ok === false) return result(`${formatHerdrError(live.error)}\nBinding: ${bindingPath(projectRoot)}`, true);
|
|
110
|
+
return result(`Herdr project pane ${existing.paneId} is open for ${projectRoot}.\nBinding: ${bindingPath(projectRoot)}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (action === "project.close") {
|
|
114
|
+
if (!existing) return result(`No Herdr project pane binding exists for ${projectRoot}.`);
|
|
115
|
+
const closed = await client.run(["pane", "close", existing.paneId], { timeoutMs: 10_000, signal: deps.signal });
|
|
116
|
+
if (closed.ok === false && closed.error.code !== "NOT_FOUND" && closed.error.code !== "PANE_GONE") return result(formatHerdrError(closed.error), true);
|
|
117
|
+
fs.rmSync(bindingPath(projectRoot), { force: true });
|
|
118
|
+
return result(`Closed Herdr project pane ${existing.paneId} for ${projectRoot}.`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const detected = await detectHerdr(client, deps.signal);
|
|
122
|
+
if (detected.ok === false) return result(formatHerdrError(detected.error), true);
|
|
123
|
+
if (existing) {
|
|
124
|
+
const live = await paneExists(client, existing.paneId, deps.signal);
|
|
125
|
+
if (live.ok) return result(`Herdr project pane ${existing.paneId} is already open for ${projectRoot}.${params.focus ? " Herdr cannot refocus an arbitrary raw pane id; select it in the Herdr UI." : ""}`);
|
|
126
|
+
}
|
|
127
|
+
const splitArgs = ["pane", "split", "--current", "--direction", "right", "--cwd", projectRoot];
|
|
128
|
+
if (params.focus !== false) splitArgs.push("--focus");
|
|
129
|
+
const split = await client.run(splitArgs, { timeoutMs: 15_000, signal: deps.signal });
|
|
130
|
+
if (split.ok === false) return result(formatHerdrError(split.error), true);
|
|
131
|
+
const paneId = extractPaneId(split.data);
|
|
132
|
+
if (!paneId) return result("Herdr project pane error (PANE_GONE): pane split returned no pane id.", true);
|
|
133
|
+
const startupMessage = params.message?.trim();
|
|
134
|
+
const command = projectPaneCommand(startupMessage);
|
|
135
|
+
const started = await client.run(["pane", "run", paneId, command], { timeoutMs: 15_000, signal: deps.signal });
|
|
136
|
+
if (started.ok === false) {
|
|
137
|
+
await client.run(["pane", "close", paneId], { timeoutMs: 5_000 });
|
|
138
|
+
return result(formatHerdrError(started.error), true);
|
|
139
|
+
}
|
|
140
|
+
const now = (deps.now?.() ?? new Date()).toISOString();
|
|
141
|
+
const binding: HerdrProjectPaneBinding = {
|
|
142
|
+
schemaVersion: 1,
|
|
143
|
+
kind: "herdr-project-pane",
|
|
144
|
+
projectRoot,
|
|
145
|
+
paneId,
|
|
146
|
+
openedAt: now,
|
|
147
|
+
...(params.focus !== false ? { lastFocusedAt: now } : {}),
|
|
148
|
+
herdrVersion: detected.data.versionText,
|
|
149
|
+
command,
|
|
150
|
+
...(startupMessage ? { startupMessage } : {}),
|
|
151
|
+
};
|
|
152
|
+
writeAtomicJson(bindingPath(projectRoot), binding);
|
|
153
|
+
return result(`Opened Herdr project pane ${paneId} for ${projectRoot}. The pane runs its own Pi session; subagents launched there belong to that project.`);
|
|
154
|
+
}
|