@howaboua/pi-shepherdr 0.1.1 → 0.1.2
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/README.md +9 -1
- package/index.ts +4 -5
- package/package.json +1 -1
- package/src/fleet.ts +556 -0
- package/src/herdr-client.ts +10 -1
- package/src/herdr.ts +6 -5
- package/src/launch.ts +13 -7
- package/src/machines-config.ts +148 -0
- package/src/master-mode.ts +214 -26
- package/src/messages.ts +41 -10
- package/src/monitor-events.ts +7 -5
- package/src/monitor.ts +61 -50
- package/src/remote/shepherdr.mjs +400 -0
- package/src/remote-client.ts +420 -0
- package/src/session-reader.ts +88 -69
- package/src/settlement.ts +20 -11
- package/src/tool.ts +62 -23
- package/src/types.ts +11 -0
- package/src/widget.ts +23 -8
package/src/launch.ts
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
parsePaneInfo,
|
|
7
7
|
resolveWorkspace,
|
|
8
8
|
} from "./herdr.js";
|
|
9
|
-
import { type
|
|
9
|
+
import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
|
|
10
10
|
import type { AgentMonitor } from "./monitor.js";
|
|
11
11
|
import type { PaneInfo } from "./types.js";
|
|
12
12
|
|
|
@@ -43,8 +43,13 @@ async function directory(
|
|
|
43
43
|
return path;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
export type DirectoryResolver = (
|
|
47
|
+
value: string | undefined,
|
|
48
|
+
fallback: string,
|
|
49
|
+
) => Promise<string>;
|
|
50
|
+
|
|
46
51
|
async function createStartPane(
|
|
47
|
-
client:
|
|
52
|
+
client: HerdrConnection,
|
|
48
53
|
params: StartAgentParams,
|
|
49
54
|
cwd: string,
|
|
50
55
|
label: string,
|
|
@@ -155,10 +160,11 @@ function nestedId(value: unknown, key: string, path: string): string {
|
|
|
155
160
|
}
|
|
156
161
|
|
|
157
162
|
export async function startAgent(
|
|
158
|
-
client:
|
|
163
|
+
client: HerdrConnection,
|
|
159
164
|
monitor: AgentMonitor,
|
|
160
165
|
params: StartAgentParams,
|
|
161
166
|
fallbackCwd: string,
|
|
167
|
+
resolveDirectory: DirectoryResolver = directory,
|
|
162
168
|
): Promise<{ id: string }> {
|
|
163
169
|
const name = required(params.name, "name");
|
|
164
170
|
if (!AGENT_NAME.test(name)) {
|
|
@@ -173,7 +179,7 @@ export async function startAgent(
|
|
|
173
179
|
const cwd =
|
|
174
180
|
params.placement === "pane"
|
|
175
181
|
? fallbackCwd
|
|
176
|
-
: await
|
|
182
|
+
: await resolveDirectory(params.cwd, fallbackCwd);
|
|
177
183
|
const created = await createStartPane(client, params, cwd, label);
|
|
178
184
|
let agent: PaneInfo;
|
|
179
185
|
try {
|
|
@@ -212,7 +218,7 @@ export async function startAgent(
|
|
|
212
218
|
}
|
|
213
219
|
|
|
214
220
|
async function rollbackCreatedLocation(
|
|
215
|
-
client:
|
|
221
|
+
client: HerdrConnection,
|
|
216
222
|
cleanup: { id: string; method: "tab.close" | "workspace.close" } | undefined,
|
|
217
223
|
cause: unknown,
|
|
218
224
|
): Promise<never> {
|
|
@@ -231,7 +237,7 @@ async function rollbackCreatedLocation(
|
|
|
231
237
|
}
|
|
232
238
|
|
|
233
239
|
async function startWhenShellReady(
|
|
234
|
-
client:
|
|
240
|
+
client: HerdrConnection,
|
|
235
241
|
params: Record<string, unknown>,
|
|
236
242
|
): Promise<PaneInfo> {
|
|
237
243
|
const shellDeadline = Date.now() + 3_000;
|
|
@@ -305,7 +311,7 @@ async function startWhenShellReady(
|
|
|
305
311
|
}
|
|
306
312
|
|
|
307
313
|
async function resolveDuringStart(
|
|
308
|
-
client:
|
|
314
|
+
client: HerdrConnection,
|
|
309
315
|
name: string,
|
|
310
316
|
paneId: string,
|
|
311
317
|
): Promise<PaneInfo> {
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
|
|
6
|
+
const MACHINE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
7
|
+
|
|
8
|
+
export const LOCAL_MACHINE = "local";
|
|
9
|
+
|
|
10
|
+
export function isMachineName(value: string): boolean {
|
|
11
|
+
return MACHINE_NAME.test(value);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface RemoteMachineConfig {
|
|
15
|
+
command: string[];
|
|
16
|
+
herdr: string;
|
|
17
|
+
node: string;
|
|
18
|
+
session?: string;
|
|
19
|
+
socket?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface MachinesConfig {
|
|
23
|
+
machines: Record<string, RemoteMachineConfig>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function agentDir(): string {
|
|
27
|
+
return (
|
|
28
|
+
process.env["PI_CODING_AGENT_DIR"]?.trim() ||
|
|
29
|
+
join(homedir(), ".pi", "agent")
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function machinesConfigPath(): string {
|
|
34
|
+
return join(agentDir(), "shepherdr.json");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function optionalString(
|
|
38
|
+
value: Record<string, unknown>,
|
|
39
|
+
key: string,
|
|
40
|
+
): string | undefined {
|
|
41
|
+
const candidate = value[key];
|
|
42
|
+
if (candidate === undefined) return undefined;
|
|
43
|
+
if (typeof candidate !== "string" || !candidate.trim()) {
|
|
44
|
+
throw new Error(`${key} must be a non-empty string`);
|
|
45
|
+
}
|
|
46
|
+
return candidate.trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseMachine(name: string, value: unknown): RemoteMachineConfig {
|
|
50
|
+
if (!isMachineName(name)) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`machine name ${JSON.stringify(name)} must match ${MACHINE_NAME.source}`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
56
|
+
throw new Error(`machine ${JSON.stringify(name)} must be an object`);
|
|
57
|
+
}
|
|
58
|
+
const record = value as Record<string, unknown>;
|
|
59
|
+
const command = record["command"];
|
|
60
|
+
if (
|
|
61
|
+
!Array.isArray(command) ||
|
|
62
|
+
command.length === 0 ||
|
|
63
|
+
command.some((part) => typeof part !== "string" || !part)
|
|
64
|
+
) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`machine ${JSON.stringify(name)} command must be a non-empty string array`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const session = optionalString(record, "session");
|
|
70
|
+
const socket = optionalString(record, "socket");
|
|
71
|
+
if (session && socket) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`machine ${JSON.stringify(name)} cannot set both session and socket`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
command: command as string[],
|
|
78
|
+
herdr: optionalString(record, "herdr") ?? "herdr",
|
|
79
|
+
node: optionalString(record, "node") ?? "node",
|
|
80
|
+
...(session ? { session } : {}),
|
|
81
|
+
...(socket ? { socket } : {}),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function readMachinesConfig(): Promise<MachinesConfig> {
|
|
86
|
+
const path = machinesConfigPath();
|
|
87
|
+
let text: string;
|
|
88
|
+
try {
|
|
89
|
+
text = await readFile(path, "utf8");
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
92
|
+
return { machines: {} };
|
|
93
|
+
}
|
|
94
|
+
throw new Error(
|
|
95
|
+
`could not read ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
let value: unknown;
|
|
99
|
+
try {
|
|
100
|
+
value = JSON.parse(text);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
107
|
+
throw new Error(`${path} must contain a JSON object`);
|
|
108
|
+
}
|
|
109
|
+
const record = value as Record<string, unknown>;
|
|
110
|
+
const machines = record["machines"] ?? {};
|
|
111
|
+
if (
|
|
112
|
+
typeof machines !== "object" ||
|
|
113
|
+
machines === null ||
|
|
114
|
+
Array.isArray(machines)
|
|
115
|
+
) {
|
|
116
|
+
throw new Error(`${path} machines must be an object`);
|
|
117
|
+
}
|
|
118
|
+
const parsed = Object.fromEntries(
|
|
119
|
+
Object.entries(machines).map(([name, machine]) => [
|
|
120
|
+
name,
|
|
121
|
+
parseMachine(name, machine),
|
|
122
|
+
]),
|
|
123
|
+
);
|
|
124
|
+
if (LOCAL_MACHINE in parsed)
|
|
125
|
+
throw new Error(
|
|
126
|
+
`remote machine ${JSON.stringify(LOCAL_MACHINE)} conflicts with local`,
|
|
127
|
+
);
|
|
128
|
+
return { machines: parsed };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function writeMachinesConfig(
|
|
132
|
+
config: MachinesConfig,
|
|
133
|
+
): Promise<string> {
|
|
134
|
+
const path = machinesConfigPath();
|
|
135
|
+
await mkdir(dirname(path), { recursive: true });
|
|
136
|
+
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
137
|
+
try {
|
|
138
|
+
await writeFile(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, {
|
|
139
|
+
encoding: "utf8",
|
|
140
|
+
mode: 0o600,
|
|
141
|
+
});
|
|
142
|
+
await rename(temporaryPath, path);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
return path;
|
|
148
|
+
}
|
package/src/master-mode.ts
CHANGED
|
@@ -2,31 +2,99 @@ import type {
|
|
|
2
2
|
ExtensionAPI,
|
|
3
3
|
ExtensionContext,
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { AgentFleet } from "./fleet.js";
|
|
6
|
+
import {
|
|
7
|
+
isMachineName,
|
|
8
|
+
LOCAL_MACHINE,
|
|
9
|
+
readMachinesConfig,
|
|
10
|
+
writeMachinesConfig,
|
|
11
|
+
} from "./machines-config.js";
|
|
5
12
|
import { enableMasterDirectory, isMasterDirectory } from "./master-config.js";
|
|
6
|
-
import type { AgentMonitor } from "./monitor.js";
|
|
7
13
|
|
|
8
14
|
const TOOL_NAME = "herdr_agents";
|
|
9
15
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
let
|
|
16
|
+
function parseSshArguments(value: string): string[] {
|
|
17
|
+
const parts: string[] = [];
|
|
18
|
+
let current = "";
|
|
19
|
+
let quote: "'" | '"' | undefined;
|
|
20
|
+
let escaped = false;
|
|
21
|
+
let started = false;
|
|
22
|
+
for (const character of value) {
|
|
23
|
+
if (escaped) {
|
|
24
|
+
current += character;
|
|
25
|
+
escaped = false;
|
|
26
|
+
started = true;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (character === "\\" && quote !== "'") {
|
|
30
|
+
escaped = true;
|
|
31
|
+
started = true;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (quote) {
|
|
35
|
+
if (character === quote) quote = undefined;
|
|
36
|
+
else current += character;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (character === "'" || character === '"') {
|
|
40
|
+
quote = character;
|
|
41
|
+
started = true;
|
|
42
|
+
} else if (/\s/.test(character)) {
|
|
43
|
+
if (started) {
|
|
44
|
+
parts.push(current);
|
|
45
|
+
current = "";
|
|
46
|
+
started = false;
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
current += character;
|
|
50
|
+
started = true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (quote) throw new Error("SSH arguments contain an unclosed quote");
|
|
54
|
+
if (escaped) throw new Error("SSH arguments end with an incomplete escape");
|
|
55
|
+
if (started) parts.push(current);
|
|
56
|
+
if (parts.length === 0) throw new Error("SSH target is required");
|
|
57
|
+
const target = parts.pop()!;
|
|
58
|
+
return [...parts, "--", target];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function registerMasterMode(pi: ExtensionAPI, fleet: AgentFleet): void {
|
|
15
62
|
pi.registerCommand("herdr", {
|
|
16
|
-
description: "
|
|
63
|
+
description: "Manage Herdr master mode and machines",
|
|
17
64
|
getArgumentCompletions: (prefix) =>
|
|
18
|
-
["master", "json"]
|
|
65
|
+
["master", "json", "connect"]
|
|
19
66
|
.filter((action) => action.startsWith(prefix.trim().toLowerCase()))
|
|
20
67
|
.map((value) => ({ label: value, value })),
|
|
21
68
|
handler: async (args, ctx) => {
|
|
22
|
-
const
|
|
69
|
+
const [rawAction = "", target] = args.trim().split(/\s+/, 2);
|
|
70
|
+
const action = rawAction.toLowerCase();
|
|
71
|
+
if (!action) {
|
|
72
|
+
await showHerdrMenu(pi, fleet, ctx);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (action === "connect") {
|
|
76
|
+
if (!fleet.isActive()) {
|
|
77
|
+
ctx.ui.notify("Enable Herdr master mode first", "warning");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
ctx.ui.notify(fleet.connect(target), "info");
|
|
82
|
+
} catch (error) {
|
|
83
|
+
ctx.ui.notify(
|
|
84
|
+
error instanceof Error ? error.message : String(error),
|
|
85
|
+
"error",
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
23
90
|
if (action !== "master" && action !== "json") {
|
|
24
|
-
ctx.ui.notify(
|
|
91
|
+
ctx.ui.notify(
|
|
92
|
+
"Usage: /herdr [master|json|connect [machine]]",
|
|
93
|
+
"warning",
|
|
94
|
+
);
|
|
25
95
|
return;
|
|
26
96
|
}
|
|
27
|
-
|
|
28
|
-
if (!activeMonitor) return;
|
|
29
|
-
monitor = activeMonitor;
|
|
97
|
+
if (!(await activateMaster(pi, fleet, ctx))) return;
|
|
30
98
|
if (action === "master") {
|
|
31
99
|
ctx.ui.notify("Herdr master enabled for this Pi session", "info");
|
|
32
100
|
return;
|
|
@@ -44,7 +112,7 @@ export function registerMasterMode(
|
|
|
44
112
|
});
|
|
45
113
|
|
|
46
114
|
pi.on("session_start", async (_event, ctx) => {
|
|
47
|
-
|
|
115
|
+
fleet.deactivate();
|
|
48
116
|
let master = false;
|
|
49
117
|
try {
|
|
50
118
|
master = await isMasterDirectory(ctx.cwd);
|
|
@@ -58,39 +126,159 @@ export function registerMasterMode(
|
|
|
58
126
|
setToolActive(pi, false);
|
|
59
127
|
return;
|
|
60
128
|
}
|
|
61
|
-
|
|
62
|
-
if (activeMonitor) monitor = activeMonitor;
|
|
129
|
+
await activateMaster(pi, fleet, ctx);
|
|
63
130
|
});
|
|
64
131
|
|
|
65
132
|
pi.on("session_shutdown", async () => {
|
|
66
|
-
|
|
133
|
+
fleet.deactivate();
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function showHerdrMenu(
|
|
138
|
+
pi: ExtensionAPI,
|
|
139
|
+
fleet: AgentFleet,
|
|
140
|
+
ctx: ExtensionContext,
|
|
141
|
+
): Promise<void> {
|
|
142
|
+
const config = await readMachinesConfig().catch((error) => {
|
|
143
|
+
ctx.ui.notify(
|
|
144
|
+
`Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
|
|
145
|
+
"error",
|
|
146
|
+
);
|
|
147
|
+
return undefined;
|
|
67
148
|
});
|
|
149
|
+
if (!config) return;
|
|
150
|
+
const statuses = fleet.isActive()
|
|
151
|
+
? fleet.statuses()
|
|
152
|
+
: Object.keys(config.machines).map((name) => ({
|
|
153
|
+
local: false,
|
|
154
|
+
name,
|
|
155
|
+
status: "unavailable" as const,
|
|
156
|
+
}));
|
|
157
|
+
const selected = await ctx.ui.select("Shepherdr", [
|
|
158
|
+
...(fleet.isActive() ? [] : ["Enable master for this session"]),
|
|
159
|
+
"Enable master in this folder",
|
|
160
|
+
"Add machine",
|
|
161
|
+
...statuses
|
|
162
|
+
.filter((machine) => !machine.local)
|
|
163
|
+
.map(
|
|
164
|
+
(machine) =>
|
|
165
|
+
`${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
|
|
166
|
+
),
|
|
167
|
+
]);
|
|
168
|
+
if (!selected) return;
|
|
169
|
+
if (selected === "Enable master for this session") {
|
|
170
|
+
if (await activateMaster(pi, fleet, ctx))
|
|
171
|
+
ctx.ui.notify("Herdr master enabled for this Pi session", "info");
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (selected === "Enable master in this folder") {
|
|
175
|
+
if (!fleet.isActive() && !(await activateMaster(pi, fleet, ctx))) return;
|
|
176
|
+
try {
|
|
177
|
+
const path = await enableMasterDirectory(ctx.cwd);
|
|
178
|
+
ctx.ui.notify(`Herdr master enabled in ${path}`, "info");
|
|
179
|
+
} catch (error) {
|
|
180
|
+
ctx.ui.notify(
|
|
181
|
+
error instanceof Error ? error.message : String(error),
|
|
182
|
+
"error",
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (selected === "Add machine") {
|
|
188
|
+
await addMachine(ctx, fleet);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const name = selected.slice(2).split(" · ", 1)[0];
|
|
192
|
+
if (!name) return;
|
|
193
|
+
const status = statuses.find((machine) => machine.name === name);
|
|
194
|
+
const action = await ctx.ui.select(name, [
|
|
195
|
+
...(status?.status !== "connected" ? ["Connect"] : []),
|
|
196
|
+
"Remove",
|
|
197
|
+
]);
|
|
198
|
+
if (action === "Connect") {
|
|
199
|
+
if (!fleet.isActive() && !(await activateMaster(pi, fleet, ctx))) return;
|
|
200
|
+
ctx.ui.notify(fleet.connect(name), "info");
|
|
201
|
+
} else if (action === "Remove") {
|
|
202
|
+
const confirmed = await ctx.ui.confirm(
|
|
203
|
+
`Remove ${name}?`,
|
|
204
|
+
"The remote Shepherdr helper will remain available for other controllers",
|
|
205
|
+
);
|
|
206
|
+
if (!confirmed) return;
|
|
207
|
+
delete config.machines[name];
|
|
208
|
+
await writeMachinesConfig(config);
|
|
209
|
+
await fleet.reload();
|
|
210
|
+
ctx.ui.notify(`Removed ${name}`, "info");
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function addMachine(
|
|
215
|
+
ctx: ExtensionContext,
|
|
216
|
+
fleet: AgentFleet,
|
|
217
|
+
): Promise<void> {
|
|
218
|
+
const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
|
|
219
|
+
if (!name) return;
|
|
220
|
+
if (!isMachineName(name)) {
|
|
221
|
+
ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const ssh = (
|
|
225
|
+
await ctx.ui.input("SSH options and target (target last)", name)
|
|
226
|
+
)?.trim();
|
|
227
|
+
if (!ssh) return;
|
|
228
|
+
let sshArguments: string[];
|
|
229
|
+
try {
|
|
230
|
+
sshArguments = parseSshArguments(ssh);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
ctx.ui.notify(
|
|
233
|
+
error instanceof Error ? error.message : String(error),
|
|
234
|
+
"error",
|
|
235
|
+
);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const session = (
|
|
239
|
+
await ctx.ui.input("Herdr session", "default (leave blank)")
|
|
240
|
+
)?.trim();
|
|
241
|
+
const config = await readMachinesConfig();
|
|
242
|
+
if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
|
|
243
|
+
ctx.ui.notify(`Machine ${name} already exists`, "error");
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
config.machines[name] = {
|
|
247
|
+
command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
|
|
248
|
+
herdr: "herdr",
|
|
249
|
+
node: "node",
|
|
250
|
+
...(session && session !== "default (leave blank)" ? { session } : {}),
|
|
251
|
+
};
|
|
252
|
+
const path = await writeMachinesConfig(config);
|
|
253
|
+
await fleet.reload();
|
|
254
|
+
ctx.ui.notify(
|
|
255
|
+
`Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
|
|
256
|
+
"info",
|
|
257
|
+
);
|
|
68
258
|
}
|
|
69
259
|
|
|
70
260
|
async function activateMaster(
|
|
71
261
|
pi: ExtensionAPI,
|
|
72
|
-
|
|
262
|
+
fleet: AgentFleet,
|
|
73
263
|
ctx: ExtensionContext,
|
|
74
|
-
): Promise<
|
|
264
|
+
): Promise<boolean> {
|
|
75
265
|
if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
|
|
76
266
|
setToolActive(pi, false);
|
|
77
267
|
ctx.ui.notify("Herdr master mode requires Pi to run inside Herdr", "error");
|
|
78
|
-
return
|
|
268
|
+
return false;
|
|
79
269
|
}
|
|
80
|
-
const monitor = getMonitor();
|
|
81
270
|
try {
|
|
82
|
-
await monitor.client.request("ping");
|
|
83
271
|
setToolActive(pi, true);
|
|
84
|
-
await
|
|
85
|
-
return
|
|
272
|
+
await fleet.activate(ctx);
|
|
273
|
+
return true;
|
|
86
274
|
} catch (error) {
|
|
87
275
|
setToolActive(pi, false);
|
|
88
|
-
|
|
276
|
+
fleet.deactivate();
|
|
89
277
|
ctx.ui.notify(
|
|
90
278
|
`Herdr master could not start: ${error instanceof Error ? error.message : String(error)}`,
|
|
91
279
|
"error",
|
|
92
280
|
);
|
|
93
|
-
return
|
|
281
|
+
return false;
|
|
94
282
|
}
|
|
95
283
|
}
|
|
96
284
|
|
package/src/messages.ts
CHANGED
|
@@ -35,6 +35,8 @@ interface AgentEventOptions {
|
|
|
35
35
|
agent: PaneInfo;
|
|
36
36
|
blockedMessage?: string;
|
|
37
37
|
labels: AgentEventLabels;
|
|
38
|
+
machine: string;
|
|
39
|
+
operatorPrefix: string;
|
|
38
40
|
record: MonitoredAgent;
|
|
39
41
|
reply?: LatestAssistant;
|
|
40
42
|
status: SettledAgentStatus;
|
|
@@ -43,6 +45,7 @@ interface AgentEventOptions {
|
|
|
43
45
|
interface AgentEventDetails {
|
|
44
46
|
blockedOn?: string;
|
|
45
47
|
cwd?: string;
|
|
48
|
+
machine: string;
|
|
46
49
|
name?: string;
|
|
47
50
|
paneId: string;
|
|
48
51
|
response?: string;
|
|
@@ -72,7 +75,7 @@ function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
|
|
|
72
75
|
|
|
73
76
|
function agentVoicePrompt(details: AgentEventDetails): string {
|
|
74
77
|
const lines = [
|
|
75
|
-
`Worker: ${details.name?.trim() || "unnamed"}`,
|
|
78
|
+
`Worker: ${details.machine} / ${details.name?.trim() || "unnamed"}`,
|
|
76
79
|
`State: ${details.state}`,
|
|
77
80
|
];
|
|
78
81
|
if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
|
|
@@ -105,7 +108,7 @@ function announceAgentEvent(
|
|
|
105
108
|
pi: ExtensionAPI,
|
|
106
109
|
details: AgentEventDetails,
|
|
107
110
|
): void {
|
|
108
|
-
const candidateId = `pi-shepherdr:${details.paneId}`;
|
|
111
|
+
const candidateId = `pi-shepherdr:${details.machine}:${details.paneId}`;
|
|
109
112
|
const id =
|
|
110
113
|
new TextEncoder().encode(candidateId).byteLength <= 160
|
|
111
114
|
? candidateId
|
|
@@ -115,12 +118,24 @@ function announceAgentEvent(
|
|
|
115
118
|
pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
|
|
116
119
|
}
|
|
117
120
|
|
|
118
|
-
function
|
|
119
|
-
return
|
|
121
|
+
function operatorCommand(operatorPrefix: string, command: string): string {
|
|
122
|
+
return `\`${operatorPrefix} ${command}\``;
|
|
120
123
|
}
|
|
121
124
|
|
|
122
|
-
function
|
|
123
|
-
|
|
125
|
+
function blockedOperatorHint(
|
|
126
|
+
machine: string,
|
|
127
|
+
operatorPrefix: string,
|
|
128
|
+
paneId: string,
|
|
129
|
+
): string {
|
|
130
|
+
return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through herdr_agents with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function failedOperatorHint(
|
|
134
|
+
machine: string,
|
|
135
|
+
operatorPrefix: string,
|
|
136
|
+
paneId: string,
|
|
137
|
+
): string {
|
|
138
|
+
return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through herdr_agents with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
|
|
124
139
|
}
|
|
125
140
|
|
|
126
141
|
function eventDetails(value: unknown): AgentEventDetails | undefined {
|
|
@@ -128,6 +143,8 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
|
|
|
128
143
|
const details = value as Record<string, unknown>;
|
|
129
144
|
if (
|
|
130
145
|
typeof details["paneId"] !== "string" ||
|
|
146
|
+
(details["machine"] !== undefined &&
|
|
147
|
+
typeof details["machine"] !== "string") ||
|
|
131
148
|
(details["state"] !== "blocked" &&
|
|
132
149
|
details["state"] !== "failed" &&
|
|
133
150
|
details["state"] !== "finished")
|
|
@@ -139,6 +156,8 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
|
|
|
139
156
|
? { [field]: details[field] as string }
|
|
140
157
|
: {};
|
|
141
158
|
return {
|
|
159
|
+
machine:
|
|
160
|
+
typeof details["machine"] === "string" ? details["machine"] : "local",
|
|
142
161
|
paneId: details["paneId"],
|
|
143
162
|
state: details["state"],
|
|
144
163
|
...optional("blockedOn"),
|
|
@@ -155,7 +174,16 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
155
174
|
content: string;
|
|
156
175
|
details: AgentEventDetails;
|
|
157
176
|
} {
|
|
158
|
-
const {
|
|
177
|
+
const {
|
|
178
|
+
agent,
|
|
179
|
+
blockedMessage,
|
|
180
|
+
labels,
|
|
181
|
+
machine,
|
|
182
|
+
operatorPrefix,
|
|
183
|
+
record,
|
|
184
|
+
reply,
|
|
185
|
+
status,
|
|
186
|
+
} = options;
|
|
159
187
|
const task = activityTask(record.activity);
|
|
160
188
|
const blocked = status === "blocked";
|
|
161
189
|
const failed = !blocked && reply?.stopReason === "error";
|
|
@@ -166,6 +194,7 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
166
194
|
? "herdr_agent_failed"
|
|
167
195
|
: "herdr_agent_result";
|
|
168
196
|
const attributes = [
|
|
197
|
+
`machine="${xml(machine)}"`,
|
|
169
198
|
`pane="${xml(agent.pane_id)}"`,
|
|
170
199
|
record.name ? `name="${xml(record.name)}"` : undefined,
|
|
171
200
|
cwd ? `directory="${xml(cwd)}"` : undefined,
|
|
@@ -179,12 +208,12 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
179
208
|
}
|
|
180
209
|
if (blocked) {
|
|
181
210
|
lines.push(
|
|
182
|
-
`<operator_hint>${xml(blockedOperatorHint(agent.pane_id))}</operator_hint>`,
|
|
211
|
+
`<operator_hint>${xml(blockedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
183
212
|
);
|
|
184
213
|
}
|
|
185
214
|
if (failed) {
|
|
186
215
|
lines.push(
|
|
187
|
-
`<operator_hint>${xml(failedOperatorHint(agent.pane_id))}</operator_hint>`,
|
|
216
|
+
`<operator_hint>${xml(failedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
|
|
188
217
|
);
|
|
189
218
|
}
|
|
190
219
|
if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
|
|
@@ -193,6 +222,7 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
193
222
|
return {
|
|
194
223
|
content: lines.join("\n"),
|
|
195
224
|
details: {
|
|
225
|
+
machine,
|
|
196
226
|
paneId: agent.pane_id,
|
|
197
227
|
state: blocked ? "blocked" : failed ? "failed" : "finished",
|
|
198
228
|
...(record.name ? { name: record.name } : {}),
|
|
@@ -249,9 +279,10 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
|
|
|
249
279
|
}
|
|
250
280
|
const blocked = details?.state === "blocked";
|
|
251
281
|
const failed = details?.state === "failed";
|
|
252
|
-
const
|
|
282
|
+
const agentIdentity = details?.name
|
|
253
283
|
? `${details.name} (${details.paneId})`
|
|
254
284
|
: (details?.paneId ?? "unknown");
|
|
285
|
+
const identity = `${details.machine} / ${agentIdentity}`;
|
|
255
286
|
const title = theme.fg(
|
|
256
287
|
blocked || failed ? "error" : "success",
|
|
257
288
|
`Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
|
package/src/monitor-events.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { HerdrConnection } from "./herdr-client.js";
|
|
2
2
|
import type { HerdrEvent } from "./types.js";
|
|
3
3
|
|
|
4
4
|
interface Subscription {
|
|
@@ -7,7 +7,8 @@ interface Subscription {
|
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
interface MonitorEventsOptions {
|
|
10
|
-
client:
|
|
10
|
+
client: HerdrConnection;
|
|
11
|
+
reconnect?: boolean;
|
|
11
12
|
onEvent: (event: HerdrEvent) => void;
|
|
12
13
|
onReconnect: () => Promise<void>;
|
|
13
14
|
onWarning: (message: string) => void;
|
|
@@ -94,9 +95,9 @@ export class MonitorEvents {
|
|
|
94
95
|
} catch (error) {
|
|
95
96
|
this.live.delete(generation);
|
|
96
97
|
if (!this.active || generation !== this.generation) return;
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
);
|
|
98
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
99
|
+
this.warn(`Herdr monitoring unavailable: ${failure.message}`);
|
|
100
|
+
if (this.options.reconnect === false) throw failure;
|
|
100
101
|
this.scheduleReconnect(generation, false);
|
|
101
102
|
}
|
|
102
103
|
}
|
|
@@ -115,6 +116,7 @@ export class MonitorEvents {
|
|
|
115
116
|
|
|
116
117
|
private scheduleReconnect(generation: number, disconnected: boolean): void {
|
|
117
118
|
if (!this.active || generation !== this.generation) return;
|
|
119
|
+
if (this.options.reconnect === false) return;
|
|
118
120
|
if (disconnected && this.subscription?.generation === generation) {
|
|
119
121
|
this.subscription = undefined;
|
|
120
122
|
}
|