@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,420 @@
|
|
|
1
|
+
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import type { HerdrConnection } from "./herdr-client.js";
|
|
6
|
+
import type { RemoteMachineConfig } from "./machines-config.js";
|
|
7
|
+
import type { AssistantReader } from "./session-reader.js";
|
|
8
|
+
import type { HerdrEvent, LatestAssistant } from "./types.js";
|
|
9
|
+
|
|
10
|
+
const BRIDGE_VERSION = 1;
|
|
11
|
+
const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
|
|
12
|
+
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
13
|
+
const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
|
|
14
|
+
const DEPLOY_TIMEOUT_MS = 20_000;
|
|
15
|
+
const READY_TIMEOUT_MS = 15_000;
|
|
16
|
+
|
|
17
|
+
const DEPLOY_SOURCE = String.raw`
|
|
18
|
+
const { randomUUID } = require("node:crypto");
|
|
19
|
+
const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
|
|
20
|
+
const { homedir } = require("node:os");
|
|
21
|
+
const { dirname, join } = require("node:path");
|
|
22
|
+
const targetValue = process.argv[1];
|
|
23
|
+
const marker = "// @howaboua/pi-shepherdr managed bridge";
|
|
24
|
+
const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
|
|
25
|
+
const chunks = [];
|
|
26
|
+
let size = 0;
|
|
27
|
+
process.stdin.on("data", chunk => { size += chunk.length; if (size > 1024 * 1024) { process.stderr.write("bridge source is too large\n"); process.exit(1); } chunks.push(chunk); });
|
|
28
|
+
process.stdin.on("end", () => { void (async () => {
|
|
29
|
+
const source = Buffer.concat(chunks);
|
|
30
|
+
let existing;
|
|
31
|
+
try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
32
|
+
if (existing) {
|
|
33
|
+
if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
|
|
34
|
+
if (!existing.toString("utf8", 0, marker.length + 32).startsWith(marker)) throw new Error(target + " is not owned by Shepherdr");
|
|
35
|
+
}
|
|
36
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
37
|
+
const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
|
|
38
|
+
try {
|
|
39
|
+
await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
|
|
40
|
+
await rename(temporary, target);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
await unlink(temporary).catch(() => undefined);
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
|
|
46
|
+
})().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
interface PendingCall {
|
|
50
|
+
reject: (error: Error) => void;
|
|
51
|
+
resolve: (value: unknown) => void;
|
|
52
|
+
timer: NodeJS.Timeout;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface SubscriptionCallbacks {
|
|
56
|
+
onDisconnect: (error?: Error) => void;
|
|
57
|
+
onEvent: (event: HerdrEvent) => void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface BridgeError {
|
|
61
|
+
code?: string;
|
|
62
|
+
herdrResponse?: boolean;
|
|
63
|
+
message: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function shellQuote(value: string): string {
|
|
67
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function executablePath(path: string): string {
|
|
71
|
+
return path.startsWith("~/")
|
|
72
|
+
? `"$HOME"/${shellQuote(path.slice(2))}`
|
|
73
|
+
: shellQuote(path);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function remoteCommand(config: RemoteMachineConfig): string {
|
|
77
|
+
const args = [
|
|
78
|
+
"exec",
|
|
79
|
+
shellQuote(config.node),
|
|
80
|
+
executablePath(REMOTE_HELPER),
|
|
81
|
+
...(config.socket ? ["--socket", shellQuote(config.socket)] : []),
|
|
82
|
+
...(config.session ? ["--session", shellQuote(config.session)] : []),
|
|
83
|
+
];
|
|
84
|
+
return args.join(" ");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function spawnConnector(
|
|
88
|
+
config: RemoteMachineConfig,
|
|
89
|
+
command: string,
|
|
90
|
+
): ChildProcessWithoutNullStreams {
|
|
91
|
+
const [program, ...args] = config.command;
|
|
92
|
+
if (!program) throw new Error("remote machine command is empty");
|
|
93
|
+
return spawn(program, [...args, command], {
|
|
94
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function appendBounded(current: string, chunk: Buffer): string {
|
|
99
|
+
const next = current + chunk.toString("utf8");
|
|
100
|
+
return next.length <= MAX_DIAGNOSTIC_BYTES
|
|
101
|
+
? next
|
|
102
|
+
: next.slice(next.length - MAX_DIAGNOSTIC_BYTES);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function deploy(
|
|
106
|
+
config: RemoteMachineConfig,
|
|
107
|
+
source: Buffer,
|
|
108
|
+
): Promise<void> {
|
|
109
|
+
const command = [
|
|
110
|
+
shellQuote(config.node),
|
|
111
|
+
"-e",
|
|
112
|
+
shellQuote(DEPLOY_SOURCE),
|
|
113
|
+
shellQuote(REMOTE_HELPER),
|
|
114
|
+
].join(" ");
|
|
115
|
+
const child = spawnConnector(config, command);
|
|
116
|
+
let stdout = "";
|
|
117
|
+
let stderr = "";
|
|
118
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
119
|
+
stdout = appendBounded(stdout, chunk);
|
|
120
|
+
});
|
|
121
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
122
|
+
stderr = appendBounded(stderr, chunk);
|
|
123
|
+
});
|
|
124
|
+
child.stdin.end(source);
|
|
125
|
+
await new Promise<void>((resolve, reject) => {
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
child.kill();
|
|
128
|
+
reject(new Error("remote bridge deployment timed out"));
|
|
129
|
+
}, DEPLOY_TIMEOUT_MS);
|
|
130
|
+
timer.unref();
|
|
131
|
+
child.on("error", (error) => {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
reject(error);
|
|
134
|
+
});
|
|
135
|
+
child.on("exit", (code) => {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
if (code === 0) resolve();
|
|
138
|
+
else
|
|
139
|
+
reject(
|
|
140
|
+
new Error(
|
|
141
|
+
stderr.trim() ||
|
|
142
|
+
stdout.trim() ||
|
|
143
|
+
`remote bridge deployment exited ${code ?? "without status"}`,
|
|
144
|
+
),
|
|
145
|
+
);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
151
|
+
private readonly child: ChildProcessWithoutNullStreams;
|
|
152
|
+
private closed = false;
|
|
153
|
+
private diagnostics = "";
|
|
154
|
+
private input = "";
|
|
155
|
+
private readonly onClose: (error: Error) => void;
|
|
156
|
+
private readonly pending = new Map<string, PendingCall>();
|
|
157
|
+
private readonly subscriptions = new Map<string, SubscriptionCallbacks>();
|
|
158
|
+
|
|
159
|
+
private constructor(
|
|
160
|
+
child: ChildProcessWithoutNullStreams,
|
|
161
|
+
onClose: (error: Error) => void,
|
|
162
|
+
) {
|
|
163
|
+
this.child = child;
|
|
164
|
+
this.onClose = onClose;
|
|
165
|
+
child.stdout.setEncoding("utf8");
|
|
166
|
+
child.stdout.on("data", (chunk: string) => this.consume(chunk));
|
|
167
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
168
|
+
this.diagnostics = appendBounded(this.diagnostics, chunk);
|
|
169
|
+
});
|
|
170
|
+
child.on("error", (error) => this.disconnected(error));
|
|
171
|
+
child.on("exit", (code) => {
|
|
172
|
+
this.disconnected(
|
|
173
|
+
new Error(
|
|
174
|
+
this.diagnostics.trim() ||
|
|
175
|
+
`remote Shepherdr bridge exited ${code ?? "without status"}`,
|
|
176
|
+
),
|
|
177
|
+
);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
static async connect(
|
|
182
|
+
config: RemoteMachineConfig,
|
|
183
|
+
onClose: (error: Error) => void,
|
|
184
|
+
): Promise<RemoteHerdrClient> {
|
|
185
|
+
const source = await readFile(
|
|
186
|
+
fileURLToPath(new URL("./remote/shepherdr.mjs", import.meta.url)),
|
|
187
|
+
);
|
|
188
|
+
await deploy(config, source);
|
|
189
|
+
const child = spawnConnector(config, remoteCommand(config));
|
|
190
|
+
const client = new RemoteHerdrClient(child, onClose);
|
|
191
|
+
try {
|
|
192
|
+
await client.ready();
|
|
193
|
+
return client;
|
|
194
|
+
} catch (error) {
|
|
195
|
+
client.close();
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async request<T>(
|
|
201
|
+
method: string,
|
|
202
|
+
params: object = {},
|
|
203
|
+
timeoutMs = 10_000,
|
|
204
|
+
): Promise<T> {
|
|
205
|
+
return (await this.call(
|
|
206
|
+
{ op: "request", method, params, timeoutMs },
|
|
207
|
+
timeoutMs + 1_000,
|
|
208
|
+
)) as T;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async subscribe(
|
|
212
|
+
subscriptions: object[],
|
|
213
|
+
onEvent: (event: HerdrEvent) => void,
|
|
214
|
+
onDisconnect: (error?: Error) => void,
|
|
215
|
+
): Promise<() => void> {
|
|
216
|
+
const id = randomUUID();
|
|
217
|
+
this.subscriptions.set(id, { onEvent, onDisconnect });
|
|
218
|
+
try {
|
|
219
|
+
await this.call({ id, op: "subscribe", subscriptions }, 11_000);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.subscriptions.delete(id);
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
return () => {
|
|
225
|
+
if (!this.subscriptions.delete(id) || this.closed) return;
|
|
226
|
+
void this.call({ op: "unsubscribe", subscription: id }).catch(
|
|
227
|
+
() => undefined,
|
|
228
|
+
);
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async latest(path?: string): Promise<LatestAssistant | undefined> {
|
|
233
|
+
return (await this.call({ op: "latest", path })) as
|
|
234
|
+
| LatestAssistant
|
|
235
|
+
| undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async directory(
|
|
239
|
+
value: string | undefined,
|
|
240
|
+
fallback: string,
|
|
241
|
+
): Promise<string> {
|
|
242
|
+
return (await this.call({ op: "directory", value, fallback })) as string;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
close(): void {
|
|
246
|
+
if (this.closed) return;
|
|
247
|
+
this.closed = true;
|
|
248
|
+
this.child.kill();
|
|
249
|
+
this.failPending(new Error("remote Shepherdr bridge closed"), false);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private ready(): Promise<void> {
|
|
253
|
+
return new Promise((resolve, reject) => {
|
|
254
|
+
const timer = setTimeout(() => {
|
|
255
|
+
this.close();
|
|
256
|
+
reject(new Error("remote Shepherdr bridge did not become ready"));
|
|
257
|
+
}, READY_TIMEOUT_MS);
|
|
258
|
+
timer.unref();
|
|
259
|
+
this.pending.set("ready", {
|
|
260
|
+
timer,
|
|
261
|
+
resolve: (value) => {
|
|
262
|
+
const ready = value as { version?: unknown };
|
|
263
|
+
if (ready.version !== BRIDGE_VERSION) {
|
|
264
|
+
reject(new Error("remote Shepherdr bridge version mismatch"));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
resolve();
|
|
268
|
+
},
|
|
269
|
+
reject,
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private call(
|
|
275
|
+
message: Record<string, unknown>,
|
|
276
|
+
timeoutMs = 10_000,
|
|
277
|
+
): Promise<unknown> {
|
|
278
|
+
if (this.closed)
|
|
279
|
+
return Promise.reject(
|
|
280
|
+
new Error("remote Shepherdr bridge is unavailable"),
|
|
281
|
+
);
|
|
282
|
+
const id = typeof message["id"] === "string" ? message["id"] : randomUUID();
|
|
283
|
+
return new Promise((resolve, reject) => {
|
|
284
|
+
const timer = setTimeout(() => {
|
|
285
|
+
this.disconnected(
|
|
286
|
+
new Error(`remote Shepherdr ${String(message["op"])} timed out`),
|
|
287
|
+
);
|
|
288
|
+
}, timeoutMs);
|
|
289
|
+
timer.unref();
|
|
290
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
291
|
+
this.child.stdin.write(
|
|
292
|
+
`${JSON.stringify({ ...message, id })}\n`,
|
|
293
|
+
(error) => {
|
|
294
|
+
if (!error) return;
|
|
295
|
+
const pending = this.pending.get(id);
|
|
296
|
+
if (!pending) return;
|
|
297
|
+
this.pending.delete(id);
|
|
298
|
+
clearTimeout(pending.timer);
|
|
299
|
+
pending.reject(error);
|
|
300
|
+
},
|
|
301
|
+
);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private consume(chunk: string): void {
|
|
306
|
+
this.input += chunk;
|
|
307
|
+
if (Buffer.byteLength(this.input) > MAX_FRAME_BYTES) {
|
|
308
|
+
this.disconnected(
|
|
309
|
+
new Error("remote Shepherdr bridge frame is too large"),
|
|
310
|
+
);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
for (;;) {
|
|
314
|
+
const newline = this.input.indexOf("\n");
|
|
315
|
+
if (newline < 0) break;
|
|
316
|
+
const line = this.input.slice(0, newline);
|
|
317
|
+
this.input = this.input.slice(newline + 1);
|
|
318
|
+
if (!line) continue;
|
|
319
|
+
let value: Record<string, unknown>;
|
|
320
|
+
try {
|
|
321
|
+
value = JSON.parse(line) as Record<string, unknown>;
|
|
322
|
+
} catch (error) {
|
|
323
|
+
this.disconnected(
|
|
324
|
+
new Error(
|
|
325
|
+
`remote Shepherdr bridge returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
|
|
326
|
+
),
|
|
327
|
+
);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (value["type"] === "ready") {
|
|
331
|
+
this.resolvePending("ready", value);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const subscription = value["subscription"];
|
|
335
|
+
if (typeof subscription === "string") {
|
|
336
|
+
const callbacks = this.subscriptions.get(subscription);
|
|
337
|
+
const event = value["event"];
|
|
338
|
+
if (callbacks && event && typeof event === "object") {
|
|
339
|
+
try {
|
|
340
|
+
callbacks.onEvent(event as HerdrEvent);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
this.disconnected(
|
|
343
|
+
new Error(
|
|
344
|
+
`Shepherdr event handling failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
345
|
+
{ cause: error },
|
|
346
|
+
),
|
|
347
|
+
);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const id = value["id"];
|
|
354
|
+
if (typeof id !== "string") continue;
|
|
355
|
+
if (value["ok"] === true) this.resolvePending(id, value["result"]);
|
|
356
|
+
else {
|
|
357
|
+
const detail = value["error"] as BridgeError | undefined;
|
|
358
|
+
const error = new Error(
|
|
359
|
+
detail?.message ?? "remote Shepherdr bridge request failed",
|
|
360
|
+
) as Error & {
|
|
361
|
+
code?: string;
|
|
362
|
+
herdrResponse?: true;
|
|
363
|
+
};
|
|
364
|
+
if (detail?.code) error.code = detail.code;
|
|
365
|
+
if (detail?.herdrResponse) error.herdrResponse = true;
|
|
366
|
+
this.rejectPending(id, error);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private resolvePending(id: string, value: unknown): void {
|
|
372
|
+
const pending = this.pending.get(id);
|
|
373
|
+
if (!pending) return;
|
|
374
|
+
this.pending.delete(id);
|
|
375
|
+
clearTimeout(pending.timer);
|
|
376
|
+
pending.resolve(value);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private rejectPending(id: string, error: Error): void {
|
|
380
|
+
const pending = this.pending.get(id);
|
|
381
|
+
if (!pending) return;
|
|
382
|
+
this.pending.delete(id);
|
|
383
|
+
clearTimeout(pending.timer);
|
|
384
|
+
pending.reject(error);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
private disconnected(error: Error): void {
|
|
388
|
+
if (this.closed) return;
|
|
389
|
+
this.closed = true;
|
|
390
|
+
this.child.kill();
|
|
391
|
+
this.failPending(error, true);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private failPending(error: Error, notify: boolean): void {
|
|
395
|
+
for (const pending of this.pending.values()) {
|
|
396
|
+
clearTimeout(pending.timer);
|
|
397
|
+
pending.reject(error);
|
|
398
|
+
}
|
|
399
|
+
this.pending.clear();
|
|
400
|
+
let callbackFailure: unknown;
|
|
401
|
+
for (const callbacks of this.subscriptions.values()) {
|
|
402
|
+
try {
|
|
403
|
+
callbacks.onDisconnect(error);
|
|
404
|
+
} catch (failure) {
|
|
405
|
+
callbackFailure ??= failure;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
this.subscriptions.clear();
|
|
409
|
+
if (notify) {
|
|
410
|
+
this.onClose(
|
|
411
|
+
callbackFailure === undefined
|
|
412
|
+
? error
|
|
413
|
+
: new Error(
|
|
414
|
+
`${error.message}; disconnect handler failed: ${callbackFailure instanceof Error ? callbackFailure.message : String(callbackFailure)}`,
|
|
415
|
+
{ cause: callbackFailure },
|
|
416
|
+
),
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
package/src/session-reader.ts
CHANGED
|
@@ -1,80 +1,97 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { open, stat } from "node:fs/promises";
|
|
2
2
|
import type { LatestAssistant } from "./types.js";
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
assistant?: LatestAssistant;
|
|
6
|
-
parentId?: string;
|
|
7
|
-
}
|
|
4
|
+
const READ_CHUNK_BYTES = 64 * 1024;
|
|
8
5
|
|
|
9
|
-
function
|
|
10
|
-
|
|
6
|
+
function assistantFromEntry(
|
|
7
|
+
entry: Record<string, unknown>,
|
|
11
8
|
): LatestAssistant | undefined {
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
9
|
+
const message = entry["message"];
|
|
10
|
+
if (
|
|
11
|
+
typeof message !== "object" ||
|
|
12
|
+
message === null ||
|
|
13
|
+
!("role" in message) ||
|
|
14
|
+
message.role !== "assistant"
|
|
15
|
+
) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
const text: string[] = [];
|
|
19
|
+
if ("content" in message && typeof message.content === "string") {
|
|
20
|
+
text.push(message.content);
|
|
21
|
+
} else if ("content" in message && Array.isArray(message.content)) {
|
|
22
|
+
for (const part of message.content) {
|
|
23
|
+
if (
|
|
24
|
+
typeof part === "object" &&
|
|
25
|
+
part !== null &&
|
|
26
|
+
"type" in part &&
|
|
27
|
+
part.type === "text" &&
|
|
28
|
+
"text" in part &&
|
|
29
|
+
typeof part.text === "string"
|
|
30
|
+
) {
|
|
31
|
+
text.push(part.text);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const joined = text.join("");
|
|
36
|
+
const stopReason =
|
|
37
|
+
"stopReason" in message && typeof message.stopReason === "string"
|
|
38
|
+
? message.stopReason
|
|
39
|
+
: undefined;
|
|
40
|
+
if (!joined && stopReason !== "error") return undefined;
|
|
41
|
+
return {
|
|
42
|
+
id: entry["id"] as string,
|
|
43
|
+
text: joined,
|
|
44
|
+
...(stopReason ? { stopReason } : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function latestAssistant(
|
|
49
|
+
path: string,
|
|
50
|
+
size: number,
|
|
51
|
+
): Promise<LatestAssistant | undefined> {
|
|
52
|
+
const file = await open(path, "r");
|
|
53
|
+
let targetId: string | undefined;
|
|
54
|
+
const inspect = (line: Buffer): LatestAssistant | null | undefined => {
|
|
55
|
+
if (line.length === 0) return undefined;
|
|
15
56
|
let entry: Record<string, unknown>;
|
|
16
57
|
try {
|
|
17
|
-
entry = JSON.parse(line) as Record<string, unknown>;
|
|
58
|
+
entry = JSON.parse(line.toString("utf8")) as Record<string, unknown>;
|
|
18
59
|
} catch {
|
|
19
|
-
|
|
60
|
+
return undefined;
|
|
20
61
|
}
|
|
21
|
-
if (typeof entry["id"] !== "string")
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
) {
|
|
47
|
-
text.push(part.text);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
const joined = text.join("");
|
|
52
|
-
const stopReason =
|
|
53
|
-
"stopReason" in message && typeof message.stopReason === "string"
|
|
54
|
-
? message.stopReason
|
|
55
|
-
: undefined;
|
|
56
|
-
if (joined || stopReason === "error") {
|
|
57
|
-
node.assistant = {
|
|
58
|
-
id: entry["id"],
|
|
59
|
-
text: joined,
|
|
60
|
-
...(stopReason ? { stopReason } : {}),
|
|
61
|
-
};
|
|
62
|
+
if (typeof entry["id"] !== "string") return undefined;
|
|
63
|
+
targetId ??= entry["id"];
|
|
64
|
+
if (entry["id"] !== targetId) return undefined;
|
|
65
|
+
const assistant = assistantFromEntry(entry);
|
|
66
|
+
if (assistant) return assistant;
|
|
67
|
+
if (typeof entry["parentId"] !== "string") return null;
|
|
68
|
+
targetId = entry["parentId"];
|
|
69
|
+
return undefined;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
let position = size;
|
|
74
|
+
let partial = Buffer.alloc(0);
|
|
75
|
+
while (position > 0) {
|
|
76
|
+
const length = Math.min(READ_CHUNK_BYTES, position);
|
|
77
|
+
position -= length;
|
|
78
|
+
const chunk = Buffer.allocUnsafe(length);
|
|
79
|
+
const { bytesRead } = await file.read(chunk, 0, length, position);
|
|
80
|
+
const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
|
|
81
|
+
let lineEnd = data.length;
|
|
82
|
+
for (let index = data.length - 1; index >= 0; index -= 1) {
|
|
83
|
+
if (data[index] !== 0x0a) continue;
|
|
84
|
+
const result = inspect(data.subarray(index + 1, lineEnd));
|
|
85
|
+
if (result !== undefined) return result ?? undefined;
|
|
86
|
+
lineEnd = index;
|
|
62
87
|
}
|
|
88
|
+
partial = data.subarray(0, lineEnd);
|
|
63
89
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const visited = new Set<string>();
|
|
69
|
-
let current = leafId;
|
|
70
|
-
while (current && !visited.has(current)) {
|
|
71
|
-
visited.add(current);
|
|
72
|
-
const node = nodes.get(current);
|
|
73
|
-
if (!node) break;
|
|
74
|
-
if (node.assistant) return node.assistant;
|
|
75
|
-
current = node.parentId;
|
|
90
|
+
const result = inspect(partial);
|
|
91
|
+
return result ?? undefined;
|
|
92
|
+
} finally {
|
|
93
|
+
await file.close();
|
|
76
94
|
}
|
|
77
|
-
return undefined;
|
|
78
95
|
}
|
|
79
96
|
|
|
80
97
|
export class SessionReader {
|
|
@@ -96,9 +113,7 @@ export class SessionReader {
|
|
|
96
113
|
if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs) {
|
|
97
114
|
return cached.result;
|
|
98
115
|
}
|
|
99
|
-
const result =
|
|
100
|
-
(await readFile(path, "utf8")).split("\n"),
|
|
101
|
-
);
|
|
116
|
+
const result = await latestAssistant(path, metadata.size);
|
|
102
117
|
this.cache.set(path, {
|
|
103
118
|
mtimeMs: metadata.mtimeMs,
|
|
104
119
|
result,
|
|
@@ -107,3 +122,7 @@ export class SessionReader {
|
|
|
107
122
|
return result;
|
|
108
123
|
}
|
|
109
124
|
}
|
|
125
|
+
|
|
126
|
+
export interface AssistantReader {
|
|
127
|
+
latest(path?: string): Promise<LatestAssistant | undefined>;
|
|
128
|
+
}
|
package/src/settlement.ts
CHANGED
|
@@ -4,10 +4,10 @@ import type {
|
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { activityTask, isSettledStatus } from "./activity.js";
|
|
6
6
|
import { getAgent, getSnapshot, sessionPath } from "./herdr.js";
|
|
7
|
-
import type {
|
|
7
|
+
import type { HerdrConnection } from "./herdr-client.js";
|
|
8
8
|
import { injectAgentEvent } from "./messages.js";
|
|
9
9
|
import type { MonitorState } from "./monitor-state.js";
|
|
10
|
-
import { SessionReader } from "./session-reader.js";
|
|
10
|
+
import { type AssistantReader, SessionReader } from "./session-reader.js";
|
|
11
11
|
import type {
|
|
12
12
|
LatestAssistant,
|
|
13
13
|
MonitoredAgent,
|
|
@@ -42,11 +42,15 @@ export interface SettlementLifecycle {
|
|
|
42
42
|
}
|
|
43
43
|
|
|
44
44
|
export class SettlementCollector {
|
|
45
|
-
private readonly client:
|
|
46
|
-
private readonly reader
|
|
45
|
+
private readonly client: HerdrConnection;
|
|
46
|
+
private readonly reader: AssistantReader;
|
|
47
47
|
|
|
48
|
-
constructor(
|
|
48
|
+
constructor(
|
|
49
|
+
client: HerdrConnection,
|
|
50
|
+
reader: AssistantReader = new SessionReader(),
|
|
51
|
+
) {
|
|
49
52
|
this.client = client;
|
|
53
|
+
this.reader = reader;
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
|
|
@@ -56,10 +60,6 @@ export class SettlementCollector {
|
|
|
56
60
|
async collect(
|
|
57
61
|
record: MonitoredAgent,
|
|
58
62
|
): Promise<CollectedSettlement | undefined> {
|
|
59
|
-
const agent = await getAgent(this.client, record.paneId);
|
|
60
|
-
if (agent.terminal_id !== record.terminalId || agent.agent !== "pi") {
|
|
61
|
-
return undefined;
|
|
62
|
-
}
|
|
63
63
|
const [current, snapshot] = await Promise.all([
|
|
64
64
|
getAgent(this.client, record.paneId),
|
|
65
65
|
getSnapshot(this.client),
|
|
@@ -94,20 +94,27 @@ export class SettlementReporter {
|
|
|
94
94
|
private readonly collector: SettlementCollector;
|
|
95
95
|
private readonly persist: () => void;
|
|
96
96
|
private readonly pi: ExtensionAPI;
|
|
97
|
+
private readonly machine: string;
|
|
98
|
+
private readonly operatorPrefix: string;
|
|
97
99
|
private readonly reporting = new Set<string>();
|
|
98
100
|
private readonly retries = new Map<string, NodeJS.Timeout>();
|
|
99
101
|
private readonly state: MonitorState;
|
|
100
102
|
|
|
101
103
|
constructor(
|
|
102
104
|
pi: ExtensionAPI,
|
|
103
|
-
client:
|
|
105
|
+
client: HerdrConnection,
|
|
104
106
|
state: MonitorState,
|
|
105
107
|
persist: () => void,
|
|
108
|
+
reader?: AssistantReader,
|
|
109
|
+
machine = "local",
|
|
110
|
+
operatorPrefix = "herdr",
|
|
106
111
|
) {
|
|
107
112
|
this.pi = pi;
|
|
108
|
-
this.collector = new SettlementCollector(client);
|
|
113
|
+
this.collector = new SettlementCollector(client, reader);
|
|
109
114
|
this.state = state;
|
|
110
115
|
this.persist = persist;
|
|
116
|
+
this.machine = machine;
|
|
117
|
+
this.operatorPrefix = operatorPrefix;
|
|
111
118
|
}
|
|
112
119
|
|
|
113
120
|
latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
|
|
@@ -142,6 +149,8 @@ export class SettlementReporter {
|
|
|
142
149
|
if (activityTask(current.activity) !== task) return;
|
|
143
150
|
injectAgentEvent(this.pi, lifecycle.context, {
|
|
144
151
|
agent: settlement.agent,
|
|
152
|
+
machine: this.machine,
|
|
153
|
+
operatorPrefix: this.operatorPrefix,
|
|
145
154
|
...(settlement.status === request.status && request.blockedMessage
|
|
146
155
|
? { blockedMessage: request.blockedMessage }
|
|
147
156
|
: {}),
|