@howaboua/pi-shepherdr 0.1.0 → 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 +112 -5
- 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
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
// @howaboua/pi-shepherdr managed bridge
|
|
2
|
+
import { open, stat } from "node:fs/promises";
|
|
3
|
+
import { createConnection } from "node:net";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
const BRIDGE_VERSION = 1;
|
|
8
|
+
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
const READ_CHUNK_BYTES = 64 * 1024;
|
|
10
|
+
const subscriptions = new Map();
|
|
11
|
+
const assistantCache = new Map();
|
|
12
|
+
|
|
13
|
+
function argument(name) {
|
|
14
|
+
const index = process.argv.indexOf(`--${name}`);
|
|
15
|
+
return index >= 0 ? process.argv[index + 1] : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function expandHome(path) {
|
|
19
|
+
return path === "~"
|
|
20
|
+
? homedir()
|
|
21
|
+
: path.startsWith("~/")
|
|
22
|
+
? join(homedir(), path.slice(2))
|
|
23
|
+
: path;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function socketPath() {
|
|
27
|
+
const explicit = argument("socket");
|
|
28
|
+
if (explicit) return expandHome(explicit);
|
|
29
|
+
const root = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
30
|
+
const session = argument("session");
|
|
31
|
+
return session
|
|
32
|
+
? join(root, "herdr", "sessions", session, "herdr.sock")
|
|
33
|
+
: join(root, "herdr", "herdr.sock");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function send(value) {
|
|
37
|
+
const frame = `${JSON.stringify(value)}\n`;
|
|
38
|
+
if (Buffer.byteLength(frame) > MAX_FRAME_BYTES) {
|
|
39
|
+
throw new Error("Shepherdr bridge response is too large");
|
|
40
|
+
}
|
|
41
|
+
process.stdout.write(frame);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function responseError(value) {
|
|
45
|
+
if (value && typeof value === "object" && typeof value.message === "string") {
|
|
46
|
+
return {
|
|
47
|
+
message: value.message,
|
|
48
|
+
...(typeof value.code === "string" ? { code: value.code } : {}),
|
|
49
|
+
herdrResponse: true,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
message: `Herdr request failed: ${JSON.stringify(value)}`,
|
|
54
|
+
herdrResponse: true,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function errorFromResponse(value) {
|
|
59
|
+
const detail = responseError(value);
|
|
60
|
+
return Object.assign(new Error(detail.message), detail);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function openHerdr(label, message, onValue, onDisconnect) {
|
|
64
|
+
let buffer = "";
|
|
65
|
+
let disconnected = false;
|
|
66
|
+
const socket = createConnection(socketPath());
|
|
67
|
+
const disconnect = (error) => {
|
|
68
|
+
if (disconnected) return;
|
|
69
|
+
disconnected = true;
|
|
70
|
+
onDisconnect(error ?? new Error(`${label} disconnected`));
|
|
71
|
+
};
|
|
72
|
+
socket.setEncoding("utf8");
|
|
73
|
+
socket.on("connect", () => socket.write(`${JSON.stringify(message)}\n`));
|
|
74
|
+
socket.on("error", disconnect);
|
|
75
|
+
socket.on("end", () => disconnect());
|
|
76
|
+
socket.on("close", () => disconnect());
|
|
77
|
+
socket.on("data", (chunk) => {
|
|
78
|
+
buffer += chunk;
|
|
79
|
+
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
|
|
80
|
+
disconnect(new Error(`${label} frame is too large`));
|
|
81
|
+
socket.destroy();
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
for (;;) {
|
|
85
|
+
const newline = buffer.indexOf("\n");
|
|
86
|
+
if (newline < 0) break;
|
|
87
|
+
const line = buffer.slice(0, newline);
|
|
88
|
+
buffer = buffer.slice(newline + 1);
|
|
89
|
+
if (!line) continue;
|
|
90
|
+
let value;
|
|
91
|
+
try {
|
|
92
|
+
value = JSON.parse(line);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
disconnect(
|
|
95
|
+
new Error(`${label} returned invalid JSON: ${error.message}`),
|
|
96
|
+
);
|
|
97
|
+
socket.destroy();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
onValue(value);
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
return socket;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function request(method, params = {}, timeoutMs = 10_000) {
|
|
107
|
+
return new Promise((resolveRequest, reject) => {
|
|
108
|
+
const id = `pi-shepherdr-bridge:${crypto.randomUUID()}`;
|
|
109
|
+
let settled = false;
|
|
110
|
+
let socket;
|
|
111
|
+
const timer = setTimeout(
|
|
112
|
+
() => finish(new Error(`Herdr ${method} timed out`)),
|
|
113
|
+
timeoutMs,
|
|
114
|
+
);
|
|
115
|
+
timer.unref();
|
|
116
|
+
const finish = (error, result) => {
|
|
117
|
+
if (settled) return;
|
|
118
|
+
settled = true;
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
socket.destroy();
|
|
121
|
+
if (error) reject(error);
|
|
122
|
+
else resolveRequest(result);
|
|
123
|
+
};
|
|
124
|
+
socket = openHerdr(
|
|
125
|
+
`Herdr ${method}`,
|
|
126
|
+
{ id, method, params },
|
|
127
|
+
(response) => {
|
|
128
|
+
if (response.id !== id)
|
|
129
|
+
finish(
|
|
130
|
+
new Error(`Herdr ${method} returned a mismatched response ID`),
|
|
131
|
+
);
|
|
132
|
+
else if (response.error !== undefined)
|
|
133
|
+
finish(errorFromResponse(response.error));
|
|
134
|
+
else if (response.result !== undefined)
|
|
135
|
+
finish(undefined, response.result);
|
|
136
|
+
else finish(new Error(`Herdr ${method} returned no result`));
|
|
137
|
+
},
|
|
138
|
+
(error) => finish(error),
|
|
139
|
+
);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function subscribe(id, requested) {
|
|
144
|
+
return new Promise((resolveSubscription, reject) => {
|
|
145
|
+
const requestId = `pi-shepherdr-bridge:subscribe:${crypto.randomUUID()}`;
|
|
146
|
+
let acknowledged = false;
|
|
147
|
+
let closed = false;
|
|
148
|
+
let socket;
|
|
149
|
+
const timer = setTimeout(() => {
|
|
150
|
+
socket.destroy();
|
|
151
|
+
reject(new Error("Herdr events.subscribe timed out"));
|
|
152
|
+
}, 10_000);
|
|
153
|
+
timer.unref();
|
|
154
|
+
const disconnected = (error) => {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
if (!acknowledged)
|
|
157
|
+
reject(error ?? new Error("Herdr subscription disconnected"));
|
|
158
|
+
else if (!closed) {
|
|
159
|
+
process.stderr.write(
|
|
160
|
+
`Herdr monitoring disconnected${error ? `: ${error.message}` : ""}\n`,
|
|
161
|
+
);
|
|
162
|
+
process.exitCode = 1;
|
|
163
|
+
setTimeout(() => process.exit(), 0);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
socket = openHerdr(
|
|
167
|
+
"Herdr events.subscribe",
|
|
168
|
+
{
|
|
169
|
+
id: requestId,
|
|
170
|
+
method: "events.subscribe",
|
|
171
|
+
params: { subscriptions: requested },
|
|
172
|
+
},
|
|
173
|
+
(value) => {
|
|
174
|
+
if (!acknowledged && value.id === requestId) {
|
|
175
|
+
if (value.error !== undefined) {
|
|
176
|
+
disconnected(errorFromResponse(value.error));
|
|
177
|
+
socket.destroy();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (value.result?.type !== "subscription_started") {
|
|
181
|
+
disconnected(
|
|
182
|
+
new Error(
|
|
183
|
+
"Herdr events.subscribe returned an invalid acknowledgement",
|
|
184
|
+
),
|
|
185
|
+
);
|
|
186
|
+
socket.destroy();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
acknowledged = true;
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
subscriptions.set(id, () => {
|
|
192
|
+
closed = true;
|
|
193
|
+
socket.destroy();
|
|
194
|
+
});
|
|
195
|
+
resolveSubscription();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (
|
|
199
|
+
acknowledged &&
|
|
200
|
+
typeof value.event === "string" &&
|
|
201
|
+
value.data &&
|
|
202
|
+
typeof value.data === "object"
|
|
203
|
+
) {
|
|
204
|
+
send({
|
|
205
|
+
subscription: id,
|
|
206
|
+
event: { event: value.event, data: value.data },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
disconnected,
|
|
211
|
+
);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function assistantFromEntry(entry) {
|
|
216
|
+
const message = entry.message;
|
|
217
|
+
if (!message || typeof message !== "object" || message.role !== "assistant")
|
|
218
|
+
return undefined;
|
|
219
|
+
const text = [];
|
|
220
|
+
if (typeof message.content === "string") text.push(message.content);
|
|
221
|
+
else if (Array.isArray(message.content)) {
|
|
222
|
+
for (const part of message.content) {
|
|
223
|
+
if (
|
|
224
|
+
part &&
|
|
225
|
+
typeof part === "object" &&
|
|
226
|
+
part.type === "text" &&
|
|
227
|
+
typeof part.text === "string"
|
|
228
|
+
)
|
|
229
|
+
text.push(part.text);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const joined = text.join("");
|
|
233
|
+
const stopReason =
|
|
234
|
+
typeof message.stopReason === "string" ? message.stopReason : undefined;
|
|
235
|
+
if (!joined && stopReason !== "error") return undefined;
|
|
236
|
+
return {
|
|
237
|
+
id: entry.id,
|
|
238
|
+
text: joined,
|
|
239
|
+
...(stopReason ? { stopReason } : {}),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function latestAssistant(path, size) {
|
|
244
|
+
const file = await open(path, "r");
|
|
245
|
+
let targetId;
|
|
246
|
+
const inspect = (line) => {
|
|
247
|
+
if (line.length === 0) return undefined;
|
|
248
|
+
let entry;
|
|
249
|
+
try {
|
|
250
|
+
entry = JSON.parse(line.toString("utf8"));
|
|
251
|
+
} catch {
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
if (typeof entry.id !== "string") return undefined;
|
|
255
|
+
targetId ??= entry.id;
|
|
256
|
+
if (entry.id !== targetId) return undefined;
|
|
257
|
+
const assistant = assistantFromEntry(entry);
|
|
258
|
+
if (assistant) return assistant;
|
|
259
|
+
if (typeof entry.parentId !== "string") return null;
|
|
260
|
+
targetId = entry.parentId;
|
|
261
|
+
return undefined;
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
try {
|
|
265
|
+
let position = size;
|
|
266
|
+
let partial = Buffer.alloc(0);
|
|
267
|
+
while (position > 0) {
|
|
268
|
+
const length = Math.min(READ_CHUNK_BYTES, position);
|
|
269
|
+
position -= length;
|
|
270
|
+
const chunk = Buffer.allocUnsafe(length);
|
|
271
|
+
const { bytesRead } = await file.read(chunk, 0, length, position);
|
|
272
|
+
const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
|
|
273
|
+
let lineEnd = data.length;
|
|
274
|
+
for (let index = data.length - 1; index >= 0; index -= 1) {
|
|
275
|
+
if (data[index] !== 0x0a) continue;
|
|
276
|
+
const result = inspect(data.subarray(index + 1, lineEnd));
|
|
277
|
+
if (result !== undefined) return result ?? undefined;
|
|
278
|
+
lineEnd = index;
|
|
279
|
+
}
|
|
280
|
+
partial = data.subarray(0, lineEnd);
|
|
281
|
+
}
|
|
282
|
+
const result = inspect(partial);
|
|
283
|
+
return result ?? undefined;
|
|
284
|
+
} finally {
|
|
285
|
+
await file.close();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function latest(path) {
|
|
290
|
+
if (!path) return undefined;
|
|
291
|
+
const expanded = expandHome(path);
|
|
292
|
+
let metadata;
|
|
293
|
+
try {
|
|
294
|
+
metadata = await stat(expanded);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (error.code === "ENOENT") return undefined;
|
|
297
|
+
throw error;
|
|
298
|
+
}
|
|
299
|
+
const cached = assistantCache.get(expanded);
|
|
300
|
+
if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs)
|
|
301
|
+
return cached.result;
|
|
302
|
+
const result = await latestAssistant(expanded, metadata.size);
|
|
303
|
+
assistantCache.set(expanded, {
|
|
304
|
+
size: metadata.size,
|
|
305
|
+
mtimeMs: metadata.mtimeMs,
|
|
306
|
+
result,
|
|
307
|
+
});
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function directory(value, fallback) {
|
|
312
|
+
const base = expandHome(fallback?.trim() || homedir());
|
|
313
|
+
const path = resolve(base, expandHome(value?.trim() || "."));
|
|
314
|
+
const metadata = await stat(path).catch((error) => {
|
|
315
|
+
throw new Error(
|
|
316
|
+
`cannot use working directory ${JSON.stringify(path)}: ${error.message}`,
|
|
317
|
+
);
|
|
318
|
+
});
|
|
319
|
+
if (!metadata.isDirectory())
|
|
320
|
+
throw new Error(`${JSON.stringify(path)} is not a directory`);
|
|
321
|
+
return path;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function serializableError(error) {
|
|
325
|
+
return {
|
|
326
|
+
message: error instanceof Error ? error.message : String(error),
|
|
327
|
+
...(typeof error?.code === "string" ? { code: error.code } : {}),
|
|
328
|
+
...(error?.herdrResponse === true ? { herdrResponse: true } : {}),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function handle(message) {
|
|
333
|
+
if (
|
|
334
|
+
!message ||
|
|
335
|
+
typeof message !== "object" ||
|
|
336
|
+
typeof message.id !== "string" ||
|
|
337
|
+
typeof message.op !== "string"
|
|
338
|
+
) {
|
|
339
|
+
throw new Error("invalid Shepherdr bridge request");
|
|
340
|
+
}
|
|
341
|
+
if (message.op === "request") {
|
|
342
|
+
return request(message.method, message.params ?? {}, message.timeoutMs);
|
|
343
|
+
}
|
|
344
|
+
if (message.op === "subscribe") {
|
|
345
|
+
await subscribe(message.id, message.subscriptions ?? []);
|
|
346
|
+
return { subscribed: true };
|
|
347
|
+
}
|
|
348
|
+
if (message.op === "unsubscribe") {
|
|
349
|
+
subscriptions.get(message.subscription)?.();
|
|
350
|
+
subscriptions.delete(message.subscription);
|
|
351
|
+
return { unsubscribed: true };
|
|
352
|
+
}
|
|
353
|
+
if (message.op === "latest") return latest(message.path);
|
|
354
|
+
if (message.op === "directory")
|
|
355
|
+
return directory(message.value, message.fallback);
|
|
356
|
+
throw new Error(`unsupported Shepherdr bridge operation ${message.op}`);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
let input = "";
|
|
360
|
+
process.stdin.setEncoding("utf8");
|
|
361
|
+
process.stdin.on("data", (chunk) => {
|
|
362
|
+
input += chunk;
|
|
363
|
+
if (Buffer.byteLength(input) > MAX_FRAME_BYTES) {
|
|
364
|
+
process.stderr.write("Shepherdr bridge request is too large\n");
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
|
367
|
+
for (;;) {
|
|
368
|
+
const newline = input.indexOf("\n");
|
|
369
|
+
if (newline < 0) break;
|
|
370
|
+
const line = input.slice(0, newline);
|
|
371
|
+
input = input.slice(newline + 1);
|
|
372
|
+
if (!line) continue;
|
|
373
|
+
let message;
|
|
374
|
+
try {
|
|
375
|
+
message = JSON.parse(line);
|
|
376
|
+
} catch (error) {
|
|
377
|
+
send({ id: "invalid", ok: false, error: serializableError(error) });
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
void handle(message).then(
|
|
381
|
+
(result) => send({ id: message.id, ok: true, result }),
|
|
382
|
+
(error) =>
|
|
383
|
+
send({ id: message.id, ok: false, error: serializableError(error) }),
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
process.stdin.on("end", () => process.exit());
|
|
389
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
390
|
+
process.on(signal, () => {
|
|
391
|
+
for (const close of subscriptions.values()) close();
|
|
392
|
+
process.exit();
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
send({
|
|
397
|
+
type: "ready",
|
|
398
|
+
version: BRIDGE_VERSION,
|
|
399
|
+
socket: socketPath(),
|
|
400
|
+
});
|