@howaboua/pi-shepherdr 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/LICENSE +21 -0
- package/README.md +89 -0
- package/biome.json +31 -0
- package/index.ts +14 -0
- package/package.json +68 -0
- package/src/activity.ts +64 -0
- package/src/herdr-client.ts +236 -0
- package/src/herdr.ts +214 -0
- package/src/launch.ts +318 -0
- package/src/master-config.ts +61 -0
- package/src/master-mode.ts +107 -0
- package/src/messages.ts +218 -0
- package/src/monitor-event.ts +84 -0
- package/src/monitor-events.ts +135 -0
- package/src/monitor-record.ts +145 -0
- package/src/monitor-state.ts +295 -0
- package/src/monitor.ts +228 -0
- package/src/session-reader.ts +109 -0
- package/src/settlement.ts +204 -0
- package/src/tool.ts +195 -0
- package/src/types.ts +78 -0
- package/src/widget.ts +75 -0
- package/tsconfig.json +4 -0
package/src/herdr.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import type { HerdrClient } from "./herdr-client.js";
|
|
2
|
+
import type {
|
|
3
|
+
AgentStatus,
|
|
4
|
+
PaneInfo,
|
|
5
|
+
SessionSnapshot,
|
|
6
|
+
WorkspaceInfo,
|
|
7
|
+
} from "./types.js";
|
|
8
|
+
|
|
9
|
+
const AGENT_STATUSES: ReadonlySet<string> = new Set([
|
|
10
|
+
"idle",
|
|
11
|
+
"working",
|
|
12
|
+
"blocked",
|
|
13
|
+
"done",
|
|
14
|
+
"unknown",
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
export async function getSnapshot(
|
|
18
|
+
client: HerdrClient,
|
|
19
|
+
): Promise<SessionSnapshot> {
|
|
20
|
+
const result = record(
|
|
21
|
+
await client.request<unknown>("session.snapshot", {}),
|
|
22
|
+
"session.snapshot result",
|
|
23
|
+
);
|
|
24
|
+
return parseSessionSnapshot(result["snapshot"]);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function getAgent(
|
|
28
|
+
client: HerdrClient,
|
|
29
|
+
target: string,
|
|
30
|
+
): Promise<PaneInfo> {
|
|
31
|
+
const result = record(
|
|
32
|
+
await client.request<unknown>("agent.get", { target }),
|
|
33
|
+
"agent.get result",
|
|
34
|
+
);
|
|
35
|
+
return parsePaneInfo(result["agent"], "agent.get result.agent");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function resolvePiAgent(
|
|
39
|
+
client: HerdrClient,
|
|
40
|
+
target: string,
|
|
41
|
+
): Promise<PaneInfo> {
|
|
42
|
+
const agent = await getAgent(client, target);
|
|
43
|
+
if (agent.agent !== "pi") throw new Error(`${target} is not a Pi agent`);
|
|
44
|
+
if (agent.pane_id === process.env["HERDR_PANE_ID"]) {
|
|
45
|
+
throw new Error("refusing to target the controlling Pi session");
|
|
46
|
+
}
|
|
47
|
+
return agent;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function resolveWorkspace(
|
|
51
|
+
snapshot: SessionSnapshot,
|
|
52
|
+
target: string,
|
|
53
|
+
): WorkspaceInfo {
|
|
54
|
+
const direct = snapshot.workspaces.find(
|
|
55
|
+
(workspace) => workspace.workspace_id === target,
|
|
56
|
+
);
|
|
57
|
+
if (direct) return direct;
|
|
58
|
+
const matches = snapshot.workspaces.filter(
|
|
59
|
+
(workspace) => workspace.label === target,
|
|
60
|
+
);
|
|
61
|
+
if (matches.length === 1) return matches[0]!;
|
|
62
|
+
if (matches.length > 1) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`workspace label ${JSON.stringify(target)} is ambiguous; use its Herdr ID`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
throw new Error(`no Herdr workspace matches ${JSON.stringify(target)}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function sessionPath(agent: PaneInfo): string | undefined {
|
|
71
|
+
return agent.agent_session?.kind === "path"
|
|
72
|
+
? agent.agent_session.value
|
|
73
|
+
: undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
|
|
77
|
+
const pane = record(value, path);
|
|
78
|
+
return {
|
|
79
|
+
pane_id: requiredString(pane, "pane_id", path),
|
|
80
|
+
terminal_id: requiredString(pane, "terminal_id", path),
|
|
81
|
+
workspace_id: requiredString(pane, "workspace_id", path),
|
|
82
|
+
tab_id: requiredString(pane, "tab_id", path),
|
|
83
|
+
agent_status: parseAgentStatus(
|
|
84
|
+
pane["agent_status"],
|
|
85
|
+
`${path}.agent_status`,
|
|
86
|
+
),
|
|
87
|
+
...optionalNullableString(pane, "agent", path),
|
|
88
|
+
...optionalNullableString(pane, "cwd", path),
|
|
89
|
+
...optionalNullableString(pane, "foreground_cwd", path),
|
|
90
|
+
...optionalNullableString(pane, "name", path),
|
|
91
|
+
...optionalBoolean(pane, "interactive_ready", path),
|
|
92
|
+
...optionalBoolean(pane, "launch_pending", path),
|
|
93
|
+
...parseAgentSession(pane["agent_session"], path),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function parseSessionSnapshot(value: unknown): SessionSnapshot {
|
|
98
|
+
const snapshot = record(value, "session.snapshot result.snapshot");
|
|
99
|
+
return {
|
|
100
|
+
agents: parseArray(snapshot, "agents", parsePaneInfo),
|
|
101
|
+
panes: parseArray(snapshot, "panes", parsePaneInfo),
|
|
102
|
+
tabs: parseArray(snapshot, "tabs", parseTabInfo),
|
|
103
|
+
workspaces: parseArray(snapshot, "workspaces", parseWorkspaceInfo),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function parseTabInfo(
|
|
108
|
+
value: unknown,
|
|
109
|
+
path: string,
|
|
110
|
+
): SessionSnapshot["tabs"][number] {
|
|
111
|
+
const tab = record(value, path);
|
|
112
|
+
return {
|
|
113
|
+
tab_id: requiredString(tab, "tab_id", path),
|
|
114
|
+
workspace_id: requiredString(tab, "workspace_id", path),
|
|
115
|
+
label: requiredString(tab, "label", path),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function parseWorkspaceInfo(value: unknown, path: string): WorkspaceInfo {
|
|
120
|
+
const workspace = record(value, path);
|
|
121
|
+
return {
|
|
122
|
+
workspace_id: requiredString(workspace, "workspace_id", path),
|
|
123
|
+
label: requiredString(workspace, "label", path),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function parseArray<T>(
|
|
128
|
+
parent: Record<string, unknown>,
|
|
129
|
+
key: string,
|
|
130
|
+
parse: (value: unknown, path: string) => T,
|
|
131
|
+
): T[] {
|
|
132
|
+
const value = parent[key];
|
|
133
|
+
if (!Array.isArray(value)) {
|
|
134
|
+
throw new Error(
|
|
135
|
+
`Herdr session.snapshot result.snapshot.${key} must be an array`,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return value.map((item, index) =>
|
|
139
|
+
parse(item, `session.snapshot result.snapshot.${key}[${index}]`),
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function parseAgentStatus(value: unknown, path: string): AgentStatus {
|
|
144
|
+
if (typeof value === "string" && AGENT_STATUSES.has(value)) {
|
|
145
|
+
return value as AgentStatus;
|
|
146
|
+
}
|
|
147
|
+
throw new Error(`Herdr ${path} has invalid status ${JSON.stringify(value)}`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function parseAgentSession(
|
|
151
|
+
value: unknown,
|
|
152
|
+
path: string,
|
|
153
|
+
): Pick<PaneInfo, "agent_session"> | Record<never, never> {
|
|
154
|
+
if (value === undefined) return {};
|
|
155
|
+
if (value === null) return { agent_session: null };
|
|
156
|
+
const session = record(value, `${path}.agent_session`);
|
|
157
|
+
const kind = session["kind"];
|
|
158
|
+
if (kind !== "id" && kind !== "path") {
|
|
159
|
+
throw new Error(`Herdr ${path}.agent_session.kind must be id or path`);
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
agent_session: {
|
|
163
|
+
agent: requiredString(session, "agent", `${path}.agent_session`),
|
|
164
|
+
kind,
|
|
165
|
+
source: requiredString(session, "source", `${path}.agent_session`),
|
|
166
|
+
value: requiredString(session, "value", `${path}.agent_session`),
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function optionalNullableString<
|
|
172
|
+
K extends "agent" | "cwd" | "foreground_cwd" | "name",
|
|
173
|
+
>(
|
|
174
|
+
value: Record<string, unknown>,
|
|
175
|
+
key: K,
|
|
176
|
+
path: string,
|
|
177
|
+
): Pick<PaneInfo, K> | Record<never, never> {
|
|
178
|
+
const field = value[key];
|
|
179
|
+
if (field === undefined) return {};
|
|
180
|
+
if (field === null || typeof field === "string") {
|
|
181
|
+
return { [key]: field } as Pick<PaneInfo, K>;
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`Herdr ${path}.${key} must be string or null`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function optionalBoolean<K extends "interactive_ready" | "launch_pending">(
|
|
187
|
+
value: Record<string, unknown>,
|
|
188
|
+
key: K,
|
|
189
|
+
path: string,
|
|
190
|
+
): Pick<PaneInfo, K> | Record<never, never> {
|
|
191
|
+
const field = value[key];
|
|
192
|
+
if (field === undefined) return {};
|
|
193
|
+
if (typeof field === "boolean") {
|
|
194
|
+
return { [key]: field } as Pick<PaneInfo, K>;
|
|
195
|
+
}
|
|
196
|
+
throw new Error(`Herdr ${path}.${key} must be boolean`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function requiredString(
|
|
200
|
+
value: Record<string, unknown>,
|
|
201
|
+
key: string,
|
|
202
|
+
path: string,
|
|
203
|
+
): string {
|
|
204
|
+
const field = value[key];
|
|
205
|
+
if (typeof field === "string") return field;
|
|
206
|
+
throw new Error(`Herdr ${path}.${key} must be string`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function record(value: unknown, path: string): Record<string, unknown> {
|
|
210
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
211
|
+
return value as Record<string, unknown>;
|
|
212
|
+
}
|
|
213
|
+
throw new Error(`Herdr ${path} must be an object`);
|
|
214
|
+
}
|
package/src/launch.ts
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
getAgent,
|
|
5
|
+
getSnapshot,
|
|
6
|
+
parsePaneInfo,
|
|
7
|
+
resolveWorkspace,
|
|
8
|
+
} from "./herdr.js";
|
|
9
|
+
import { type HerdrClient, isHerdrErrorCode } from "./herdr-client.js";
|
|
10
|
+
import type { AgentMonitor } from "./monitor.js";
|
|
11
|
+
import type { PaneInfo } from "./types.js";
|
|
12
|
+
|
|
13
|
+
export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
|
|
14
|
+
const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
15
|
+
|
|
16
|
+
export interface StartAgentParams {
|
|
17
|
+
cwd?: string;
|
|
18
|
+
label?: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
pane?: string;
|
|
21
|
+
placement?: (typeof START_PLACEMENTS)[number];
|
|
22
|
+
prompt?: string;
|
|
23
|
+
workspace?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function required(value: string | undefined, field: string): string {
|
|
27
|
+
if (!value?.trim()) throw new Error(`${field} is required for start`);
|
|
28
|
+
return value.trim();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function directory(
|
|
32
|
+
value: string | undefined,
|
|
33
|
+
fallback: string,
|
|
34
|
+
): Promise<string> {
|
|
35
|
+
const path = resolve(fallback, value?.trim() || ".");
|
|
36
|
+
const metadata = await stat(path).catch((error) => {
|
|
37
|
+
throw new Error(
|
|
38
|
+
`cannot use working directory ${JSON.stringify(path)}: ${error instanceof Error ? error.message : String(error)}`,
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
if (!metadata.isDirectory())
|
|
42
|
+
throw new Error(`${JSON.stringify(path)} is not a directory`);
|
|
43
|
+
return path;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function createStartPane(
|
|
47
|
+
client: HerdrClient,
|
|
48
|
+
params: StartAgentParams,
|
|
49
|
+
cwd: string,
|
|
50
|
+
label: string,
|
|
51
|
+
): Promise<{
|
|
52
|
+
cleanup?: { id: string; method: "tab.close" | "workspace.close" };
|
|
53
|
+
paneId: string;
|
|
54
|
+
}> {
|
|
55
|
+
const placement = params.placement;
|
|
56
|
+
if (!placement) throw new Error("placement is required for start");
|
|
57
|
+
if (placement === "pane") {
|
|
58
|
+
return { paneId: required(params.pane, "pane") };
|
|
59
|
+
}
|
|
60
|
+
if (placement === "new_tab") {
|
|
61
|
+
const workspaceTarget = required(params.workspace, "workspace");
|
|
62
|
+
const workspace = resolveWorkspace(
|
|
63
|
+
await getSnapshot(client),
|
|
64
|
+
workspaceTarget,
|
|
65
|
+
);
|
|
66
|
+
const created = createdLocation(
|
|
67
|
+
await client.request<unknown>("tab.create", {
|
|
68
|
+
workspace_id: workspace.workspace_id,
|
|
69
|
+
cwd,
|
|
70
|
+
label,
|
|
71
|
+
focus: false,
|
|
72
|
+
}),
|
|
73
|
+
"tab.create result",
|
|
74
|
+
);
|
|
75
|
+
return {
|
|
76
|
+
paneId: created.root_pane.pane_id,
|
|
77
|
+
cleanup: { method: "tab.close", id: created.tab.tab_id },
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const created = createdLocation(
|
|
81
|
+
await client.request<unknown>("workspace.create", {
|
|
82
|
+
cwd,
|
|
83
|
+
focus: false,
|
|
84
|
+
}),
|
|
85
|
+
"workspace.create result",
|
|
86
|
+
true,
|
|
87
|
+
);
|
|
88
|
+
try {
|
|
89
|
+
await client.request("tab.rename", { tab_id: created.tab.tab_id, label });
|
|
90
|
+
} catch (error) {
|
|
91
|
+
return rollbackCreatedLocation(
|
|
92
|
+
client,
|
|
93
|
+
{ method: "workspace.close", id: created.workspace.workspace_id },
|
|
94
|
+
error,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
paneId: created.root_pane.pane_id,
|
|
99
|
+
cleanup: { method: "workspace.close", id: created.workspace.workspace_id },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function createdLocation(
|
|
104
|
+
value: unknown,
|
|
105
|
+
path: string,
|
|
106
|
+
): { root_pane: PaneInfo; tab: { tab_id: string } };
|
|
107
|
+
function createdLocation(
|
|
108
|
+
value: unknown,
|
|
109
|
+
path: string,
|
|
110
|
+
withWorkspace: true,
|
|
111
|
+
): {
|
|
112
|
+
root_pane: PaneInfo;
|
|
113
|
+
tab: { tab_id: string };
|
|
114
|
+
workspace: { workspace_id: string };
|
|
115
|
+
};
|
|
116
|
+
function createdLocation(
|
|
117
|
+
value: unknown,
|
|
118
|
+
path: string,
|
|
119
|
+
withWorkspace = false,
|
|
120
|
+
): {
|
|
121
|
+
root_pane: PaneInfo;
|
|
122
|
+
tab: { tab_id: string };
|
|
123
|
+
workspace?: { workspace_id: string };
|
|
124
|
+
} {
|
|
125
|
+
if (typeof value !== "object" || value === null) {
|
|
126
|
+
throw new Error(`Herdr ${path} must be an object`);
|
|
127
|
+
}
|
|
128
|
+
const result = value as Record<string, unknown>;
|
|
129
|
+
const tabId = nestedId(result["tab"], "tab_id", `${path}.tab`);
|
|
130
|
+
return {
|
|
131
|
+
root_pane: parsePaneInfo(result["root_pane"], `${path}.root_pane`),
|
|
132
|
+
tab: { tab_id: tabId },
|
|
133
|
+
...(withWorkspace
|
|
134
|
+
? {
|
|
135
|
+
workspace: {
|
|
136
|
+
workspace_id: nestedId(
|
|
137
|
+
result["workspace"],
|
|
138
|
+
"workspace_id",
|
|
139
|
+
`${path}.workspace`,
|
|
140
|
+
),
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
: {}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function nestedId(value: unknown, key: string, path: string): string {
|
|
148
|
+
if (typeof value !== "object" || value === null) {
|
|
149
|
+
throw new Error(`Herdr ${path} must be an object`);
|
|
150
|
+
}
|
|
151
|
+
const id = (value as Record<string, unknown>)[key];
|
|
152
|
+
if (typeof id !== "string")
|
|
153
|
+
throw new Error(`Herdr ${path}.${key} must be string`);
|
|
154
|
+
return id;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function startAgent(
|
|
158
|
+
client: HerdrClient,
|
|
159
|
+
monitor: AgentMonitor,
|
|
160
|
+
params: StartAgentParams,
|
|
161
|
+
fallbackCwd: string,
|
|
162
|
+
): Promise<{ id: string }> {
|
|
163
|
+
const name = required(params.name, "name");
|
|
164
|
+
if (!AGENT_NAME.test(name)) {
|
|
165
|
+
throw new Error("name must match [a-z][a-z0-9_-]{0,31}");
|
|
166
|
+
}
|
|
167
|
+
const label = params.label?.trim() || name;
|
|
168
|
+
if (params.placement === "pane" && params.cwd) {
|
|
169
|
+
throw new Error(
|
|
170
|
+
"cwd cannot change an existing pane; prepare the pane through Herdr",
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const cwd =
|
|
174
|
+
params.placement === "pane"
|
|
175
|
+
? fallbackCwd
|
|
176
|
+
: await directory(params.cwd, fallbackCwd);
|
|
177
|
+
const created = await createStartPane(client, params, cwd, label);
|
|
178
|
+
let agent: PaneInfo;
|
|
179
|
+
try {
|
|
180
|
+
agent = await startWhenShellReady(client, {
|
|
181
|
+
name,
|
|
182
|
+
kind: "pi",
|
|
183
|
+
pane_id: created.paneId,
|
|
184
|
+
args: ["--name", label],
|
|
185
|
+
timeout_ms: 30_000,
|
|
186
|
+
});
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return rollbackCreatedLocation(client, created.cleanup, error);
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
await monitor.watch(agent);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
return rollbackCreatedLocation(client, created.cleanup, error);
|
|
194
|
+
}
|
|
195
|
+
if (params.prompt?.trim()) {
|
|
196
|
+
const prompt = params.prompt.trim();
|
|
197
|
+
const attempt = monitor.beginWork(agent.pane_id, prompt);
|
|
198
|
+
try {
|
|
199
|
+
await client.request("agent.prompt", {
|
|
200
|
+
target: agent.pane_id,
|
|
201
|
+
text: prompt,
|
|
202
|
+
});
|
|
203
|
+
monitor.acceptWork(attempt);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
await monitor.handleWorkFailure(attempt, error);
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
id: agent.pane_id,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function rollbackCreatedLocation(
|
|
215
|
+
client: HerdrClient,
|
|
216
|
+
cleanup: { id: string; method: "tab.close" | "workspace.close" } | undefined,
|
|
217
|
+
cause: unknown,
|
|
218
|
+
): Promise<never> {
|
|
219
|
+
if (!cleanup) throw cause;
|
|
220
|
+
try {
|
|
221
|
+
await client.request(cleanup.method, {
|
|
222
|
+
[cleanup.method === "tab.close" ? "tab_id" : "workspace_id"]: cleanup.id,
|
|
223
|
+
});
|
|
224
|
+
} catch (cleanupError) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`${cause instanceof Error ? cause.message : String(cause)}; rollback also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
|
|
227
|
+
{ cause },
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
throw cause;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function startWhenShellReady(
|
|
234
|
+
client: HerdrClient,
|
|
235
|
+
params: Record<string, unknown>,
|
|
236
|
+
): Promise<PaneInfo> {
|
|
237
|
+
const shellDeadline = Date.now() + 3_000;
|
|
238
|
+
let started: { agent: PaneInfo };
|
|
239
|
+
for (;;) {
|
|
240
|
+
try {
|
|
241
|
+
const result = await client.request<{ agent?: unknown }>(
|
|
242
|
+
"agent.start",
|
|
243
|
+
params,
|
|
244
|
+
35_000,
|
|
245
|
+
);
|
|
246
|
+
started = {
|
|
247
|
+
agent: parsePaneInfo(result.agent, "agent.start result.agent"),
|
|
248
|
+
};
|
|
249
|
+
break;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (
|
|
252
|
+
!isHerdrErrorCode(error, "agent_pane_busy") ||
|
|
253
|
+
Date.now() >= shellDeadline
|
|
254
|
+
) {
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const name = required(
|
|
262
|
+
typeof params["name"] === "string" ? params["name"] : undefined,
|
|
263
|
+
"name",
|
|
264
|
+
);
|
|
265
|
+
const paneId = required(
|
|
266
|
+
typeof params["pane_id"] === "string" ? params["pane_id"] : undefined,
|
|
267
|
+
"pane_id",
|
|
268
|
+
);
|
|
269
|
+
const terminalId = started.agent.terminal_id;
|
|
270
|
+
const readyDeadline = Date.now() + 30_000;
|
|
271
|
+
while (Date.now() < readyDeadline) {
|
|
272
|
+
let current: PaneInfo;
|
|
273
|
+
try {
|
|
274
|
+
current = await resolveDuringStart(client, name, paneId);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (!isHerdrErrorCode(error, "agent_not_found")) throw error;
|
|
277
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (current.terminal_id !== terminalId || current.name !== name) {
|
|
281
|
+
throw new Error(`named agent ${name} no longer owns ${paneId}`);
|
|
282
|
+
}
|
|
283
|
+
if (current.agent && current.agent !== "pi") {
|
|
284
|
+
throw new Error(`expected pi, detected ${current.agent}`);
|
|
285
|
+
}
|
|
286
|
+
if (current.agent_status === "blocked") {
|
|
287
|
+
throw new Error(`agent ${name} is blocked during startup`);
|
|
288
|
+
}
|
|
289
|
+
if (
|
|
290
|
+
(current.agent_status === "idle" || current.agent_status === "done") &&
|
|
291
|
+
current.interactive_ready === true &&
|
|
292
|
+
current.agent === "pi"
|
|
293
|
+
) {
|
|
294
|
+
return current;
|
|
295
|
+
}
|
|
296
|
+
if (
|
|
297
|
+
(current.agent_status === "idle" || current.agent_status === "done") &&
|
|
298
|
+
current.launch_pending === false
|
|
299
|
+
) {
|
|
300
|
+
throw new Error("agent process exited before becoming interactive");
|
|
301
|
+
}
|
|
302
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
303
|
+
}
|
|
304
|
+
throw new Error(`timed out waiting for agent ${name} to become interactive`);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function resolveDuringStart(
|
|
308
|
+
client: HerdrClient,
|
|
309
|
+
name: string,
|
|
310
|
+
paneId: string,
|
|
311
|
+
): Promise<PaneInfo> {
|
|
312
|
+
try {
|
|
313
|
+
return await getAgent(client, name);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (!isHerdrErrorCode(error, "agent_not_found")) throw error;
|
|
316
|
+
return getAgent(client, paneId);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
function configPath(cwd: string): string {
|
|
6
|
+
return join(cwd, ".pi", "shepherdr.json");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export async function isMasterDirectory(cwd: string): Promise<boolean> {
|
|
10
|
+
const path = configPath(cwd);
|
|
11
|
+
const value = await readConfig(path);
|
|
12
|
+
if (!value || !("master" in value)) return false;
|
|
13
|
+
if (typeof value["master"] === "boolean") return value["master"];
|
|
14
|
+
throw new Error(`${path} master must be boolean`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function enableMasterDirectory(cwd: string): Promise<string> {
|
|
18
|
+
const directory = join(cwd, ".pi");
|
|
19
|
+
const path = configPath(cwd);
|
|
20
|
+
const value = (await readConfig(path)) ?? {};
|
|
21
|
+
value["master"] = true;
|
|
22
|
+
await mkdir(directory, { recursive: true });
|
|
23
|
+
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
24
|
+
try {
|
|
25
|
+
await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
|
|
26
|
+
encoding: "utf8",
|
|
27
|
+
mode: 0o600,
|
|
28
|
+
});
|
|
29
|
+
await rename(temporaryPath, path);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
return path;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function readConfig(
|
|
38
|
+
path: string,
|
|
39
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
40
|
+
let text: string;
|
|
41
|
+
try {
|
|
42
|
+
text = await readFile(path, "utf8");
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
45
|
+
throw new Error(
|
|
46
|
+
`could not read ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
let value: unknown;
|
|
50
|
+
try {
|
|
51
|
+
value = JSON.parse(text);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
`could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
58
|
+
throw new Error(`${path} must contain a JSON object`);
|
|
59
|
+
}
|
|
60
|
+
return value as Record<string, unknown>;
|
|
61
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { enableMasterDirectory, isMasterDirectory } from "./master-config.js";
|
|
6
|
+
import type { AgentMonitor } from "./monitor.js";
|
|
7
|
+
|
|
8
|
+
const TOOL_NAME = "herdr_agents";
|
|
9
|
+
|
|
10
|
+
export function registerMasterMode(
|
|
11
|
+
pi: ExtensionAPI,
|
|
12
|
+
getMonitor: () => AgentMonitor,
|
|
13
|
+
): void {
|
|
14
|
+
let monitor: AgentMonitor | undefined;
|
|
15
|
+
pi.registerCommand("herdr", {
|
|
16
|
+
description: "Enable Herdr master mode for this session or directory",
|
|
17
|
+
getArgumentCompletions: (prefix) =>
|
|
18
|
+
["master", "json"]
|
|
19
|
+
.filter((action) => action.startsWith(prefix.trim().toLowerCase()))
|
|
20
|
+
.map((value) => ({ label: value, value })),
|
|
21
|
+
handler: async (args, ctx) => {
|
|
22
|
+
const action = args.trim().toLowerCase();
|
|
23
|
+
if (action !== "master" && action !== "json") {
|
|
24
|
+
ctx.ui.notify("Usage: /herdr [master|json]", "warning");
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const activeMonitor = await activateMaster(pi, getMonitor, ctx);
|
|
28
|
+
if (!activeMonitor) return;
|
|
29
|
+
monitor = activeMonitor;
|
|
30
|
+
if (action === "master") {
|
|
31
|
+
ctx.ui.notify("Herdr master enabled for this Pi session", "info");
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const path = await enableMasterDirectory(ctx.cwd);
|
|
36
|
+
ctx.ui.notify(`Herdr master enabled in ${path}`, "info");
|
|
37
|
+
} catch (error) {
|
|
38
|
+
ctx.ui.notify(
|
|
39
|
+
`Herdr master is active for this session but could not save ${ctx.cwd}/.pi/shepherdr.json: ${error instanceof Error ? error.message : String(error)}`,
|
|
40
|
+
"error",
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
47
|
+
monitor?.deactivate();
|
|
48
|
+
let master = false;
|
|
49
|
+
try {
|
|
50
|
+
master = await isMasterDirectory(ctx.cwd);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
ctx.ui.notify(
|
|
53
|
+
`Herdr master config is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
54
|
+
"error",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (!master) {
|
|
58
|
+
setToolActive(pi, false);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const activeMonitor = await activateMaster(pi, getMonitor, ctx);
|
|
62
|
+
if (activeMonitor) monitor = activeMonitor;
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
pi.on("session_shutdown", async () => {
|
|
66
|
+
monitor?.deactivate();
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function activateMaster(
|
|
71
|
+
pi: ExtensionAPI,
|
|
72
|
+
getMonitor: () => AgentMonitor,
|
|
73
|
+
ctx: ExtensionContext,
|
|
74
|
+
): Promise<AgentMonitor | undefined> {
|
|
75
|
+
if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
|
|
76
|
+
setToolActive(pi, false);
|
|
77
|
+
ctx.ui.notify("Herdr master mode requires Pi to run inside Herdr", "error");
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
const monitor = getMonitor();
|
|
81
|
+
try {
|
|
82
|
+
await monitor.client.request("ping");
|
|
83
|
+
setToolActive(pi, true);
|
|
84
|
+
await monitor.activate(ctx);
|
|
85
|
+
return monitor;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
setToolActive(pi, false);
|
|
88
|
+
monitor.deactivate();
|
|
89
|
+
ctx.ui.notify(
|
|
90
|
+
`Herdr master could not start: ${error instanceof Error ? error.message : String(error)}`,
|
|
91
|
+
"error",
|
|
92
|
+
);
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function setToolActive(pi: ExtensionAPI, active: boolean): void {
|
|
98
|
+
const current = pi.getActiveTools();
|
|
99
|
+
const withoutTool = current.filter((name) => name !== TOOL_NAME);
|
|
100
|
+
const next = active ? [...withoutTool, TOOL_NAME] : withoutTool;
|
|
101
|
+
if (
|
|
102
|
+
next.length !== current.length ||
|
|
103
|
+
next.some((name, index) => name !== current[index])
|
|
104
|
+
) {
|
|
105
|
+
pi.setActiveTools(next);
|
|
106
|
+
}
|
|
107
|
+
}
|