@howaboua/pi-shepherdr 0.1.6 → 0.2.1
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 +25 -0
- package/README.md +25 -6
- package/index.ts +2 -0
- package/package.json +4 -4
- package/src/agents-contract.ts +11 -6
- package/src/agents-operations.ts +99 -23
- package/src/agents-tool.ts +77 -45
- package/src/controller.ts +4 -8
- package/src/delivery.ts +100 -1
- package/src/fleet.ts +59 -63
- package/src/herdr-client.ts +26 -2
- package/src/herdr.ts +17 -1
- package/src/launch.ts +0 -25
- package/src/machine-catalog.ts +77 -0
- package/src/messages.ts +75 -14
- package/src/monitor-record.ts +6 -19
- package/src/monitor-state.ts +36 -6
- package/src/monitor.ts +14 -9
- package/src/peer-inbox.ts +237 -0
- package/src/remote/shepherdr-peer.mjs +225 -0
- package/src/remote/shepherdr.mjs +33 -13
- package/src/remote-client.ts +55 -21
- package/src/session-reader.ts +21 -11
- package/src/settlement.ts +15 -13
- package/src/types.ts +19 -4
- package/src/widget.ts +4 -4
- package/tsconfig.json +7 -1
- package/src/machine-menu.ts +0 -163
- package/src/machines-config.ts +0 -148
package/src/controller.ts
CHANGED
|
@@ -4,7 +4,6 @@ import type {
|
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { sendPolicyMessage } from "./delivery.js";
|
|
6
6
|
import type { AgentFleet } from "./fleet.js";
|
|
7
|
-
import { showMachineMenu } from "./machine-menu.js";
|
|
8
7
|
import { loadAgentProfiles } from "./profiles.js";
|
|
9
8
|
|
|
10
9
|
const ORCHESTRATION_STATE_TYPE = "pi-shepherdr-orchestration-state";
|
|
@@ -20,9 +19,9 @@ export function registerAgentController(
|
|
|
20
19
|
): void {
|
|
21
20
|
let orchestrationEnabled = false;
|
|
22
21
|
pi.registerCommand("herdr", {
|
|
23
|
-
description: "Toggle agent orchestration or
|
|
22
|
+
description: "Toggle agent orchestration or reconnect machines",
|
|
24
23
|
getArgumentCompletions: (prefix) =>
|
|
25
|
-
["
|
|
24
|
+
["connect"]
|
|
26
25
|
.filter((action) => action.startsWith(prefix.trim().toLowerCase()))
|
|
27
26
|
.map((value) => ({ label: value, value })),
|
|
28
27
|
handler: async (args, ctx) => {
|
|
@@ -51,16 +50,13 @@ export function registerAgentController(
|
|
|
51
50
|
);
|
|
52
51
|
return;
|
|
53
52
|
}
|
|
54
|
-
if (action === "machines") {
|
|
55
|
-
await showMachineMenu(fleet, ctx);
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
53
|
if (action === "connect") {
|
|
59
54
|
if (!fleet.isActive()) {
|
|
60
55
|
await activateController(fleet, ctx);
|
|
61
56
|
if (!fleet.isActive()) return;
|
|
62
57
|
}
|
|
63
58
|
try {
|
|
59
|
+
await fleet.reload();
|
|
64
60
|
ctx.ui.notify(fleet.connect(rest[0]), "info");
|
|
65
61
|
} catch (error) {
|
|
66
62
|
ctx.ui.notify(
|
|
@@ -70,7 +66,7 @@ export function registerAgentController(
|
|
|
70
66
|
}
|
|
71
67
|
return;
|
|
72
68
|
}
|
|
73
|
-
ctx.ui.notify("Usage: /herdr [
|
|
69
|
+
ctx.ui.notify("Usage: /herdr [connect [machine]]", "warning");
|
|
74
70
|
},
|
|
75
71
|
});
|
|
76
72
|
|
package/src/delivery.ts
CHANGED
|
@@ -1,14 +1,31 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
2
5
|
import type {
|
|
3
6
|
CodexDeveloperCustomMessage,
|
|
4
7
|
CodexDeveloperMessageOptions,
|
|
5
8
|
trySendCodexDeveloperCustomMessage,
|
|
9
|
+
tryStartCodexPreparedIdleKickoff,
|
|
10
|
+
tryStartCodexPreparedIdlePrompt,
|
|
6
11
|
} from "@howaboua/pi-codex-conversion/developer-messages";
|
|
7
12
|
|
|
8
13
|
const senders = new WeakMap<
|
|
9
14
|
ExtensionAPI,
|
|
10
15
|
typeof trySendCodexDeveloperCustomMessage
|
|
11
16
|
>();
|
|
17
|
+
const preparedKickoffs = new WeakMap<
|
|
18
|
+
ExtensionAPI,
|
|
19
|
+
typeof tryStartCodexPreparedIdleKickoff
|
|
20
|
+
>();
|
|
21
|
+
const fallbackKickoffs = new WeakMap<
|
|
22
|
+
ExtensionAPI,
|
|
23
|
+
"preparing" | "running" | "queued"
|
|
24
|
+
>();
|
|
25
|
+
const preparedPrompts = new WeakMap<
|
|
26
|
+
ExtensionAPI,
|
|
27
|
+
typeof tryStartCodexPreparedIdlePrompt
|
|
28
|
+
>();
|
|
12
29
|
const PACKAGE = "@howaboua/pi-codex-conversion";
|
|
13
30
|
const MODULE = `${PACKAGE}/developer-messages`;
|
|
14
31
|
|
|
@@ -21,9 +38,91 @@ export async function registerDeveloperDelivery(
|
|
|
21
38
|
);
|
|
22
39
|
if (typeof api.trySendCodexDeveloperCustomMessage === "function")
|
|
23
40
|
senders.set(pi, api.trySendCodexDeveloperCustomMessage);
|
|
41
|
+
if (typeof api.tryStartCodexPreparedIdleKickoff === "function")
|
|
42
|
+
preparedKickoffs.set(pi, api.tryStartCodexPreparedIdleKickoff);
|
|
43
|
+
if (typeof api.tryStartCodexPreparedIdlePrompt === "function")
|
|
44
|
+
preparedPrompts.set(pi, api.tryStartCodexPreparedIdlePrompt);
|
|
24
45
|
} catch (error) {
|
|
25
46
|
if (!isUnavailable(error)) throw error;
|
|
26
47
|
}
|
|
48
|
+
pi.on("session_start", () => {
|
|
49
|
+
fallbackKickoffs.delete(pi);
|
|
50
|
+
});
|
|
51
|
+
pi.on("session_tree", () => {
|
|
52
|
+
fallbackKickoffs.delete(pi);
|
|
53
|
+
});
|
|
54
|
+
pi.on("agent_start", () => {
|
|
55
|
+
if (fallbackKickoffs.get(pi) === "preparing")
|
|
56
|
+
fallbackKickoffs.set(pi, "running");
|
|
57
|
+
});
|
|
58
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
59
|
+
const state = fallbackKickoffs.get(pi);
|
|
60
|
+
if (state === "running" || state === "queued") fallbackKickoffs.delete(pi);
|
|
61
|
+
if (state === "queued") startPreparedIdleTurn(pi, ctx);
|
|
62
|
+
});
|
|
63
|
+
pi.on("session_shutdown", () => {
|
|
64
|
+
fallbackKickoffs.delete(pi);
|
|
65
|
+
});
|
|
66
|
+
pi.on("input", (event, ctx) => {
|
|
67
|
+
// Idle prompts must run Pi's complete before_agent_start preparation chain.
|
|
68
|
+
if (
|
|
69
|
+
ctx.isIdle() ||
|
|
70
|
+
event.streamingBehavior === undefined ||
|
|
71
|
+
event.images?.length ||
|
|
72
|
+
!/^<herdr_sender [^\n]+ \/>\n/.test(event.text)
|
|
73
|
+
)
|
|
74
|
+
return;
|
|
75
|
+
if (
|
|
76
|
+
senders.get(pi)?.(
|
|
77
|
+
pi,
|
|
78
|
+
{
|
|
79
|
+
customType: "herdr-agent-message",
|
|
80
|
+
content: event.text,
|
|
81
|
+
display: true,
|
|
82
|
+
},
|
|
83
|
+
{ deliverAs: event.streamingBehavior },
|
|
84
|
+
)
|
|
85
|
+
) {
|
|
86
|
+
return { action: "handled" };
|
|
87
|
+
}
|
|
88
|
+
return;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function startPreparedIdleTurn(
|
|
93
|
+
pi: ExtensionAPI,
|
|
94
|
+
ctx: Pick<ExtensionContext, "ui">,
|
|
95
|
+
start?: () => void,
|
|
96
|
+
): void {
|
|
97
|
+
if (start) {
|
|
98
|
+
if (preparedPrompts.get(pi)?.(pi, start)) return;
|
|
99
|
+
if (preparedKickoffs.has(pi) && !preparedPrompts.has(pi))
|
|
100
|
+
throw new Error(
|
|
101
|
+
"Update Pi Codex Conversion and reload before sending slash commands",
|
|
102
|
+
);
|
|
103
|
+
} else if (preparedKickoffs.get(pi)?.(pi, ctx)) return;
|
|
104
|
+
if (fallbackKickoffs.has(pi)) {
|
|
105
|
+
if (start)
|
|
106
|
+
throw new Error(
|
|
107
|
+
"Target has a pending turn; retry after it starts or settles",
|
|
108
|
+
);
|
|
109
|
+
// Pi is already idle while earlier settlement handlers are awaiting.
|
|
110
|
+
if (fallbackKickoffs.get(pi) === "running")
|
|
111
|
+
fallbackKickoffs.set(pi, "queued");
|
|
112
|
+
ctx.ui.notify(
|
|
113
|
+
"An automatic turn is pending. If no turn starts, send a user message or reload the session.",
|
|
114
|
+
"warning",
|
|
115
|
+
);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
fallbackKickoffs.set(pi, "preparing");
|
|
119
|
+
try {
|
|
120
|
+
if (start) start();
|
|
121
|
+
else pi.sendUserMessage("Continue.", { deliverAs: "steer" });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
fallbackKickoffs.delete(pi);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
27
126
|
}
|
|
28
127
|
|
|
29
128
|
export function sendPolicyMessage(
|
package/src/fleet.ts
CHANGED
|
@@ -6,10 +6,9 @@ import { getSnapshot } from "./herdr.js";
|
|
|
6
6
|
import { HerdrClient, type HerdrConnection } from "./herdr-client.js";
|
|
7
7
|
import {
|
|
8
8
|
LOCAL_MACHINE,
|
|
9
|
-
|
|
10
|
-
type
|
|
11
|
-
|
|
12
|
-
} from "./machines-config.js";
|
|
9
|
+
readMachineCatalog,
|
|
10
|
+
type SshMachine,
|
|
11
|
+
} from "./machine-catalog.js";
|
|
13
12
|
import { AgentMonitor } from "./monitor.js";
|
|
14
13
|
import { parseMonitoredAgent } from "./monitor-record.js";
|
|
15
14
|
import { RemoteHerdrClient } from "./remote-client.js";
|
|
@@ -27,7 +26,7 @@ const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
|
|
|
27
26
|
interface Runtime {
|
|
28
27
|
attempting?: boolean;
|
|
29
28
|
client?: HerdrConnection;
|
|
30
|
-
config?:
|
|
29
|
+
config?: SshMachine;
|
|
31
30
|
local: boolean;
|
|
32
31
|
monitor?: AgentMonitor;
|
|
33
32
|
monitoringIssue?: MonitoringIssue;
|
|
@@ -63,41 +62,28 @@ function shellQuote(value: string): string {
|
|
|
63
62
|
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
64
63
|
}
|
|
65
64
|
|
|
66
|
-
function operatorPrefix(config:
|
|
67
|
-
|
|
68
|
-
? `HERDR_SOCKET_PATH="$HOME"/${shellQuote(config.socket.slice(2))}`
|
|
69
|
-
: config.socket === "~"
|
|
70
|
-
? 'HERDR_SOCKET_PATH="$HOME"'
|
|
71
|
-
: config.socket
|
|
72
|
-
? `HERDR_SOCKET_PATH=${shellQuote(config.socket)}`
|
|
73
|
-
: undefined;
|
|
74
|
-
const remote = socket
|
|
75
|
-
? ["env", socket, config.herdr]
|
|
76
|
-
: [config.herdr, ...(config.session ? ["--session", config.session] : [])];
|
|
77
|
-
return [...config.command, ...remote].map(shellQuote).join(" ");
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function sameMachineConfig(
|
|
81
|
-
left: RemoteMachineConfig,
|
|
82
|
-
right: RemoteMachineConfig,
|
|
83
|
-
): boolean {
|
|
84
|
-
return (
|
|
85
|
-
left.herdr === right.herdr &&
|
|
86
|
-
left.node === right.node &&
|
|
87
|
-
left.session === right.session &&
|
|
88
|
-
left.socket === right.socket &&
|
|
89
|
-
left.command.length === right.command.length &&
|
|
90
|
-
left.command.every((part, index) => part === right.command[index])
|
|
91
|
-
);
|
|
65
|
+
function operatorPrefix(config: SshMachine): string {
|
|
66
|
+
return `ssh -T -o BatchMode=yes -- ${shellQuote(config.target)} herdr --session ${shellQuote(config.session)}`;
|
|
92
67
|
}
|
|
93
68
|
|
|
94
69
|
function savedAgents(ctx: ExtensionContext): unknown[] {
|
|
95
70
|
let latest: unknown[] = [];
|
|
71
|
+
let version: unknown;
|
|
96
72
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
97
73
|
if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
|
|
98
74
|
continue;
|
|
99
|
-
const data = entry.data as { agents?: unknown };
|
|
100
|
-
if (Array.isArray(data?.agents))
|
|
75
|
+
const data = entry.data as { version?: unknown; agents?: unknown };
|
|
76
|
+
if (Array.isArray(data?.agents)) {
|
|
77
|
+
latest = data.agents;
|
|
78
|
+
version = data.version;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (latest.length > 0 && version !== 2) {
|
|
82
|
+
ctx.ui.notify(
|
|
83
|
+
"Cleared legacy Shepherdr watches; use watch to subscribe explicitly. Remote agents are unchanged.",
|
|
84
|
+
"warning",
|
|
85
|
+
);
|
|
86
|
+
return [];
|
|
101
87
|
}
|
|
102
88
|
return latest;
|
|
103
89
|
}
|
|
@@ -120,7 +106,6 @@ function groupSaved(values: unknown[]): Map<string, unknown[]> {
|
|
|
120
106
|
}
|
|
121
107
|
|
|
122
108
|
export class AgentFleet {
|
|
123
|
-
private config: MachinesConfig = { machines: {} };
|
|
124
109
|
private context: ExtensionContext | undefined;
|
|
125
110
|
private generation = 0;
|
|
126
111
|
private readonly pi: ExtensionAPI;
|
|
@@ -134,14 +119,13 @@ export class AgentFleet {
|
|
|
134
119
|
this.deactivate();
|
|
135
120
|
const generation = this.generation;
|
|
136
121
|
this.context = ctx;
|
|
137
|
-
const
|
|
122
|
+
const catalog = await readMachineCatalog();
|
|
138
123
|
if (!this.isCurrent(generation, ctx)) return;
|
|
139
|
-
|
|
124
|
+
const machines = Object.entries(catalog).filter(
|
|
125
|
+
([, machine]) => machine.enabled,
|
|
126
|
+
);
|
|
140
127
|
const grouped = groupSaved(savedAgents(ctx));
|
|
141
|
-
const known = new Set([
|
|
142
|
-
LOCAL_MACHINE,
|
|
143
|
-
...Object.keys(this.config.machines),
|
|
144
|
-
]);
|
|
128
|
+
const known = new Set([LOCAL_MACHINE, ...machines.map(([id]) => id)]);
|
|
145
129
|
const orphaned = [...grouped.entries()]
|
|
146
130
|
.filter(([machine]) => !known.has(machine))
|
|
147
131
|
.reduce((count, [, records]) => count + records.length, 0);
|
|
@@ -158,7 +142,7 @@ export class AgentFleet {
|
|
|
158
142
|
status: "connecting",
|
|
159
143
|
};
|
|
160
144
|
this.runtimes.set(LOCAL_MACHINE, localRuntime);
|
|
161
|
-
for (const [name, config] of
|
|
145
|
+
for (const [name, config] of machines) {
|
|
162
146
|
this.runtimes.set(name, {
|
|
163
147
|
config,
|
|
164
148
|
local: false,
|
|
@@ -189,9 +173,9 @@ export class AgentFleet {
|
|
|
189
173
|
}
|
|
190
174
|
localRuntime.pending = [];
|
|
191
175
|
localRuntime.status = "connected";
|
|
192
|
-
this.
|
|
176
|
+
this.changed();
|
|
193
177
|
|
|
194
|
-
for (const name of
|
|
178
|
+
for (const [name] of machines) {
|
|
195
179
|
void this.connectMachine(name, generation, true);
|
|
196
180
|
}
|
|
197
181
|
}
|
|
@@ -215,19 +199,25 @@ export class AgentFleet {
|
|
|
215
199
|
const ctx = this.context;
|
|
216
200
|
if (!ctx) return;
|
|
217
201
|
const generation = this.generation;
|
|
218
|
-
const
|
|
202
|
+
const catalog = await readMachineCatalog();
|
|
219
203
|
if (!this.isCurrent(generation, ctx)) return;
|
|
220
204
|
const reconnect: string[] = [];
|
|
221
205
|
|
|
222
206
|
for (const [name, runtime] of this.runtimes) {
|
|
223
|
-
if (runtime.local ||
|
|
207
|
+
if (runtime.local || catalog[name]?.enabled) continue;
|
|
224
208
|
runtime.monitor?.deactivate();
|
|
225
209
|
if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
|
|
226
210
|
this.runtimes.delete(name);
|
|
227
211
|
}
|
|
228
|
-
for (const [name, machineConfig] of Object.entries(
|
|
212
|
+
for (const [name, machineConfig] of Object.entries(catalog)) {
|
|
213
|
+
if (!machineConfig.enabled) continue;
|
|
229
214
|
const runtime = this.runtimes.get(name);
|
|
230
|
-
if (
|
|
215
|
+
if (
|
|
216
|
+
runtime?.config &&
|
|
217
|
+
runtime.config.target === machineConfig.target &&
|
|
218
|
+
runtime.config.session === machineConfig.session
|
|
219
|
+
) {
|
|
220
|
+
runtime.config = machineConfig;
|
|
231
221
|
continue;
|
|
232
222
|
}
|
|
233
223
|
const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
|
|
@@ -241,7 +231,6 @@ export class AgentFleet {
|
|
|
241
231
|
});
|
|
242
232
|
reconnect.push(name);
|
|
243
233
|
}
|
|
244
|
-
this.config = config;
|
|
245
234
|
this.changed();
|
|
246
235
|
for (const name of reconnect) {
|
|
247
236
|
void this.connectMachine(name, generation, true);
|
|
@@ -302,7 +291,7 @@ export class AgentFleet {
|
|
|
302
291
|
: this.statuses();
|
|
303
292
|
return Promise.all(
|
|
304
293
|
selected.map(async (status) => {
|
|
305
|
-
const runtime = this.runtimes.get(status.
|
|
294
|
+
const runtime = this.runtimes.get(status.id);
|
|
306
295
|
if (
|
|
307
296
|
status.status !== "connected" ||
|
|
308
297
|
!runtime?.client ||
|
|
@@ -317,10 +306,10 @@ export class AgentFleet {
|
|
|
317
306
|
runtime.status !== "connected" ||
|
|
318
307
|
runtime.client !== client ||
|
|
319
308
|
runtime.monitor !== monitor ||
|
|
320
|
-
this.runtimes.get(status.
|
|
309
|
+
this.runtimes.get(status.id) !== runtime
|
|
321
310
|
) {
|
|
322
|
-
return this.runtimes.has(status.
|
|
323
|
-
? this.statusFor(status.
|
|
311
|
+
return this.runtimes.has(status.id)
|
|
312
|
+
? this.statusFor(status.id)
|
|
324
313
|
: status;
|
|
325
314
|
}
|
|
326
315
|
return {
|
|
@@ -335,10 +324,10 @@ export class AgentFleet {
|
|
|
335
324
|
runtime.status !== "connected" ||
|
|
336
325
|
runtime.client !== client ||
|
|
337
326
|
runtime.monitor !== monitor ||
|
|
338
|
-
this.runtimes.get(status.
|
|
327
|
+
this.runtimes.get(status.id) !== runtime
|
|
339
328
|
) {
|
|
340
|
-
return this.runtimes.has(status.
|
|
341
|
-
? this.statusFor(status.
|
|
329
|
+
return this.runtimes.has(status.id)
|
|
330
|
+
? this.statusFor(status.id)
|
|
342
331
|
: status;
|
|
343
332
|
}
|
|
344
333
|
return { ...status, snapshotError: errorMessage(error) };
|
|
@@ -420,8 +409,15 @@ export class AgentFleet {
|
|
|
420
409
|
if (!runtime)
|
|
421
410
|
throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
|
|
422
411
|
return {
|
|
423
|
-
name,
|
|
412
|
+
id: name,
|
|
424
413
|
local: runtime.local,
|
|
414
|
+
...(runtime.config
|
|
415
|
+
? {
|
|
416
|
+
label: runtime.config.label,
|
|
417
|
+
target: runtime.config.target,
|
|
418
|
+
session: runtime.config.session,
|
|
419
|
+
}
|
|
420
|
+
: {}),
|
|
425
421
|
status: runtime.status,
|
|
426
422
|
...(runtime.monitoringIssue
|
|
427
423
|
? { monitoringIssue: runtime.monitoringIssue }
|
|
@@ -438,6 +434,7 @@ export class AgentFleet {
|
|
|
438
434
|
return new AgentMonitor(this.pi, {
|
|
439
435
|
client,
|
|
440
436
|
machine,
|
|
437
|
+
machineLabel: () => runtime.config?.label ?? LOCAL_MACHINE,
|
|
441
438
|
onChange: () => this.changed(),
|
|
442
439
|
onRefresh: () => this.refresh(),
|
|
443
440
|
operatorPrefix: runtime.local ? "herdr" : operatorPrefix(runtime.config!),
|
|
@@ -544,11 +541,12 @@ export class AgentFleet {
|
|
|
544
541
|
client.close();
|
|
545
542
|
return;
|
|
546
543
|
}
|
|
544
|
+
const pending = runtime.monitor?.list() ?? runtime.pending;
|
|
547
545
|
const monitor = this.createMonitor(name, runtime, client);
|
|
548
546
|
runtime.client = client;
|
|
549
547
|
runtime.monitor = monitor;
|
|
550
548
|
attached = true;
|
|
551
|
-
await monitor.activate(ctx,
|
|
549
|
+
await monitor.activate(ctx, pending);
|
|
552
550
|
if (
|
|
553
551
|
!this.isCurrent(generation, ctx) ||
|
|
554
552
|
this.runtimes.get(name) !== runtime ||
|
|
@@ -593,12 +591,10 @@ export class AgentFleet {
|
|
|
593
591
|
private disconnected(name: string, runtime: Runtime, reason: string): void {
|
|
594
592
|
reason = errorMessage(reason);
|
|
595
593
|
if (runtime.status === "unavailable" && runtime.reason === reason) return;
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
}
|
|
594
|
+
// Keep the stopped owner until reconnect so in-flight dispatch cleanup
|
|
595
|
+
// updates the state we persist, rather than a detached snapshot.
|
|
596
|
+
runtime.monitor?.deactivate();
|
|
600
597
|
if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
|
|
601
|
-
delete runtime.monitor;
|
|
602
598
|
delete runtime.client;
|
|
603
599
|
delete runtime.monitoringIssue;
|
|
604
600
|
runtime.status = "unavailable";
|
|
@@ -614,7 +610,7 @@ export class AgentFleet {
|
|
|
614
610
|
private changed(): void {
|
|
615
611
|
if (!this.context) return;
|
|
616
612
|
const agents = this.persistedAgents();
|
|
617
|
-
this.pi.appendEntry(MONITOR_STATE_TYPE, { agents });
|
|
613
|
+
this.pi.appendEntry(MONITOR_STATE_TYPE, { version: 2, agents });
|
|
618
614
|
this.refresh();
|
|
619
615
|
}
|
|
620
616
|
|
package/src/herdr-client.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { createConnection } from "node:net";
|
|
2
|
-
import
|
|
2
|
+
import { sendPeerMessage } from "./remote/shepherdr-peer.mjs";
|
|
3
|
+
import type {
|
|
4
|
+
HerdrEvent,
|
|
5
|
+
PaneInfo,
|
|
6
|
+
PeerDelivery,
|
|
7
|
+
PeerMessage,
|
|
8
|
+
} from "./types.js";
|
|
3
9
|
|
|
4
10
|
const MAX_FRAME_BUFFER = 8 * 1024 * 1024;
|
|
5
11
|
|
|
@@ -28,10 +34,19 @@ function errorFromResponse(value: unknown): Error {
|
|
|
28
34
|
return error;
|
|
29
35
|
}
|
|
30
36
|
|
|
31
|
-
|
|
37
|
+
function isHerdrResponseError(error: unknown): boolean {
|
|
32
38
|
return (error as Error & { herdrResponse?: unknown }).herdrResponse === true;
|
|
33
39
|
}
|
|
34
40
|
|
|
41
|
+
export function isDispatchRejected(error: unknown): boolean {
|
|
42
|
+
return (
|
|
43
|
+
isHerdrResponseError(error) ||
|
|
44
|
+
(error instanceof Error &&
|
|
45
|
+
"code" in error &&
|
|
46
|
+
error.code === "SHEPHERDR_DELIVERY_REJECTED")
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
35
50
|
export function isHerdrErrorCode(error: unknown, code: string): boolean {
|
|
36
51
|
return (
|
|
37
52
|
isHerdrResponseError(error) &&
|
|
@@ -41,6 +56,7 @@ export function isHerdrErrorCode(error: unknown, code: string): boolean {
|
|
|
41
56
|
|
|
42
57
|
export interface HerdrConnection {
|
|
43
58
|
request<T>(method: string, params?: object, timeoutMs?: number): Promise<T>;
|
|
59
|
+
sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery>;
|
|
44
60
|
subscribe(
|
|
45
61
|
subscriptions: object[],
|
|
46
62
|
onEvent: (event: HerdrEvent) => void,
|
|
@@ -61,6 +77,14 @@ export class HerdrClient implements HerdrConnection {
|
|
|
61
77
|
this.socketPath = socketPath;
|
|
62
78
|
}
|
|
63
79
|
|
|
80
|
+
sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery> {
|
|
81
|
+
return sendPeerMessage(
|
|
82
|
+
(method, params) => this.request(method, params),
|
|
83
|
+
agent,
|
|
84
|
+
message,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
64
88
|
request<T>(
|
|
65
89
|
method: string,
|
|
66
90
|
params: object = {},
|
package/src/herdr.ts
CHANGED
|
@@ -46,6 +46,21 @@ export async function getPane(
|
|
|
46
46
|
return parsePaneInfo(result["pane"], "pane.get result.pane");
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
export async function getCurrentPane(
|
|
50
|
+
client: HerdrConnection,
|
|
51
|
+
): Promise<PaneInfo> {
|
|
52
|
+
const callerPaneId = process.env["HERDR_PANE_ID"];
|
|
53
|
+
if (!callerPaneId)
|
|
54
|
+
throw new Error("HERDR_PANE_ID is required to identify the sender");
|
|
55
|
+
const result = record(
|
|
56
|
+
await client.request<unknown>("pane.current", {
|
|
57
|
+
caller_pane_id: callerPaneId,
|
|
58
|
+
}),
|
|
59
|
+
"pane.current result",
|
|
60
|
+
);
|
|
61
|
+
return parsePaneInfo(result["pane"], "pane.current result.pane");
|
|
62
|
+
}
|
|
63
|
+
|
|
49
64
|
export async function resolvePiAgent(
|
|
50
65
|
client: HerdrConnection,
|
|
51
66
|
target: string,
|
|
@@ -101,6 +116,7 @@ export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
|
|
|
101
116
|
...optionalNullableString(pane, "foreground_cwd", path),
|
|
102
117
|
...optionalNullableString(pane, "label", path),
|
|
103
118
|
...optionalNullableString(pane, "name", path),
|
|
119
|
+
...optionalNullableString(pane, "title", path),
|
|
104
120
|
...optionalBoolean(pane, "interactive_ready", path),
|
|
105
121
|
...optionalBoolean(pane, "launch_pending", path),
|
|
106
122
|
...parseAgentSession(pane["agent_session"], path),
|
|
@@ -182,7 +198,7 @@ function parseAgentSession(
|
|
|
182
198
|
}
|
|
183
199
|
|
|
184
200
|
function optionalNullableString<
|
|
185
|
-
K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name",
|
|
201
|
+
K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name" | "title",
|
|
186
202
|
>(
|
|
187
203
|
value: Record<string, unknown>,
|
|
188
204
|
key: K,
|
package/src/launch.ts
CHANGED
|
@@ -8,7 +8,6 @@ import {
|
|
|
8
8
|
resolveWorkspace,
|
|
9
9
|
} from "./herdr.js";
|
|
10
10
|
import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
|
|
11
|
-
import type { AgentMonitor } from "./monitor.js";
|
|
12
11
|
import type { PaneInfo } from "./types.js";
|
|
13
12
|
|
|
14
13
|
export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
|
|
@@ -20,7 +19,6 @@ export interface StartAgentParams {
|
|
|
20
19
|
name?: string;
|
|
21
20
|
pane?: string;
|
|
22
21
|
placement?: (typeof START_PLACEMENTS)[number];
|
|
23
|
-
prompt?: string;
|
|
24
22
|
workspace?: string;
|
|
25
23
|
}
|
|
26
24
|
|
|
@@ -200,7 +198,6 @@ function nestedId(value: unknown, key: string, path: string): string {
|
|
|
200
198
|
|
|
201
199
|
export async function startAgent(
|
|
202
200
|
client: HerdrConnection,
|
|
203
|
-
monitor: AgentMonitor,
|
|
204
201
|
params: StartAgentParams,
|
|
205
202
|
fallbackCwd: string,
|
|
206
203
|
resolveDirectory: DirectoryResolver = directory,
|
|
@@ -234,25 +231,6 @@ export async function startAgent(
|
|
|
234
231
|
} catch (error) {
|
|
235
232
|
return rollbackCreatedLocation(client, created.cleanup, error);
|
|
236
233
|
}
|
|
237
|
-
try {
|
|
238
|
-
await monitor.watch(agent);
|
|
239
|
-
} catch (error) {
|
|
240
|
-
return rollbackCreatedLocation(client, created.cleanup, error);
|
|
241
|
-
}
|
|
242
|
-
if (params.prompt?.trim()) {
|
|
243
|
-
const prompt = params.prompt.trim();
|
|
244
|
-
const attempt = monitor.beginWork(agent.pane_id, prompt);
|
|
245
|
-
try {
|
|
246
|
-
await client.request("agent.prompt", {
|
|
247
|
-
target: agent.pane_id,
|
|
248
|
-
text: prompt,
|
|
249
|
-
});
|
|
250
|
-
monitor.acceptWork(attempt);
|
|
251
|
-
} catch (error) {
|
|
252
|
-
await monitor.handleWorkFailure(attempt, error);
|
|
253
|
-
throw error;
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
234
|
return {
|
|
257
235
|
agent,
|
|
258
236
|
...(created.cleanup ? { cleanup: created.cleanup } : {}),
|
|
@@ -262,12 +240,9 @@ export async function startAgent(
|
|
|
262
240
|
|
|
263
241
|
export async function rollbackStartedAgent(
|
|
264
242
|
client: HerdrConnection,
|
|
265
|
-
monitor: AgentMonitor,
|
|
266
243
|
started: StartedAgent,
|
|
267
244
|
cause: unknown,
|
|
268
245
|
): Promise<never> {
|
|
269
|
-
if (!started.cleanup) throw cause;
|
|
270
|
-
await monitor.unwatch(started.id).catch(() => undefined);
|
|
271
246
|
return rollbackCreatedLocation(client, started.cleanup, cause);
|
|
272
247
|
}
|
|
273
248
|
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { type Static, Type } from "typebox";
|
|
5
|
+
import { Check } from "typebox/value";
|
|
6
|
+
|
|
7
|
+
export const LOCAL_MACHINE = "local";
|
|
8
|
+
|
|
9
|
+
const Machine = Type.Object({
|
|
10
|
+
id: Type.String({ pattern: "^[a-f0-9]{32}$" }),
|
|
11
|
+
label: Type.String({ minLength: 1, pattern: "^[^\\x00-\\x1f\\x7f]+$" }),
|
|
12
|
+
target: Type.String({
|
|
13
|
+
minLength: 1,
|
|
14
|
+
pattern: "^[^-\\x00-\\x1f\\x7f][^\\x00-\\x1f\\x7f]*$",
|
|
15
|
+
}),
|
|
16
|
+
session: Type.String({
|
|
17
|
+
minLength: 1,
|
|
18
|
+
maxLength: 64,
|
|
19
|
+
pattern: "^[a-zA-Z0-9_.-]+$",
|
|
20
|
+
}),
|
|
21
|
+
enabled: Type.Boolean(),
|
|
22
|
+
});
|
|
23
|
+
const Catalog = Type.Array(Machine);
|
|
24
|
+
export type SshMachine = Static<typeof Machine>;
|
|
25
|
+
|
|
26
|
+
export async function readMachineCatalog(): Promise<
|
|
27
|
+
Record<string, SshMachine>
|
|
28
|
+
> {
|
|
29
|
+
const inheritedBinary = process.env["HERDR_BIN_PATH"]?.trim() || "herdr";
|
|
30
|
+
let binary = inheritedBinary;
|
|
31
|
+
const read = (path: string) =>
|
|
32
|
+
promisify(execFile)(path, ["machine", "list", "--json"], {
|
|
33
|
+
timeout: 10_000,
|
|
34
|
+
maxBuffer: 1024 * 1024,
|
|
35
|
+
encoding: "utf8",
|
|
36
|
+
});
|
|
37
|
+
let stdout: string;
|
|
38
|
+
try {
|
|
39
|
+
try {
|
|
40
|
+
({ stdout } = await read(binary));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (
|
|
43
|
+
!(error instanceof Error) ||
|
|
44
|
+
!("code" in error) ||
|
|
45
|
+
error.code !== "ENOENT" ||
|
|
46
|
+
!isAbsolute(binary) ||
|
|
47
|
+
!binary.endsWith(" (deleted)")
|
|
48
|
+
) {
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
// Linux /proc executable paths can retain this suffix after replacement.
|
|
52
|
+
binary = binary.slice(0, -" (deleted)".length);
|
|
53
|
+
({ stdout } = await read(binary));
|
|
54
|
+
}
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Could not read Herdr machines${binary !== inheritedBinary ? " after retrying stale HERDR_BIN_PATH" : ""}: ${error instanceof Error ? error.message : String(error)}`,
|
|
58
|
+
{ cause: error },
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
let value: unknown;
|
|
62
|
+
try {
|
|
63
|
+
value = JSON.parse(stdout);
|
|
64
|
+
} catch {
|
|
65
|
+
throw new Error("Herdr machine list returned invalid JSON");
|
|
66
|
+
}
|
|
67
|
+
if (
|
|
68
|
+
!Check(Catalog, value) ||
|
|
69
|
+
value.some((machine) => machine.session === "." || machine.session === "..")
|
|
70
|
+
) {
|
|
71
|
+
throw new Error("Herdr machine list returned an invalid catalog");
|
|
72
|
+
}
|
|
73
|
+
if (new Set(value.map((machine) => machine.id)).size !== value.length) {
|
|
74
|
+
throw new Error("Herdr machine list returned duplicate profile IDs");
|
|
75
|
+
}
|
|
76
|
+
return Object.fromEntries(value.map((machine) => [machine.id, machine]));
|
|
77
|
+
}
|