@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/src/monitor.ts CHANGED
@@ -4,51 +4,81 @@ import type {
4
4
  } from "@earendil-works/pi-coding-agent";
5
5
  import { isSettledStatus } from "./activity.js";
6
6
  import { getSnapshot } from "./herdr.js";
7
- import { HerdrClient, isHerdrResponseError } from "./herdr-client.js";
7
+ import { type HerdrConnection, isHerdrResponseError } from "./herdr-client.js";
8
8
  import { parseMonitorEvent } from "./monitor-event.js";
9
9
  import { MonitorEvents } from "./monitor-events.js";
10
10
  import { MonitorState, type WorkAttempt } from "./monitor-state.js";
11
+ import type { AssistantReader } from "./session-reader.js";
11
12
  import { SettlementReporter, type SettlementRequest } from "./settlement.js";
12
13
  import type { HerdrEvent, MonitoredAgent, PaneInfo } from "./types.js";
13
- import { renderAgentWidget } from "./widget.js";
14
14
 
15
- const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
16
-
17
- interface MonitorStateEntry {
18
- agents: MonitoredAgent[];
15
+ interface AgentMonitorOptions {
16
+ client: HerdrConnection;
17
+ machine: string;
18
+ onChange: () => void;
19
+ onRefresh: () => void;
20
+ operatorPrefix: string;
21
+ onWarning: (message: string) => void;
22
+ reader?: AssistantReader;
23
+ reconnect: boolean;
24
+ selfPaneId?: string;
19
25
  }
20
26
 
21
27
  export class AgentMonitor {
22
- readonly client: HerdrClient;
23
- private readonly pi: ExtensionAPI;
28
+ readonly client: HerdrConnection;
29
+ readonly machine: string;
30
+ private readonly onChange: () => void;
31
+ private readonly onRefresh: () => void;
32
+ private readonly selfPaneId: string | undefined;
33
+ private readonly onWarning: (message: string) => void;
24
34
  private readonly state = new MonitorState();
25
35
  private readonly events: MonitorEvents;
26
36
  private readonly settlements: SettlementReporter;
27
37
  private context: ExtensionContext | undefined;
28
38
  private activationGeneration = 0;
29
39
 
30
- constructor(pi: ExtensionAPI, client = new HerdrClient()) {
31
- this.pi = pi;
32
- this.client = client;
33
- this.settlements = new SettlementReporter(pi, client, this.state, () =>
34
- this.persist(),
40
+ constructor(pi: ExtensionAPI, options: AgentMonitorOptions) {
41
+ this.client = options.client;
42
+ this.machine = options.machine;
43
+ this.onChange = options.onChange;
44
+ this.onRefresh = options.onRefresh;
45
+ this.selfPaneId = options.selfPaneId;
46
+ this.onWarning = options.onWarning;
47
+ this.settlements = new SettlementReporter(
48
+ pi,
49
+ this.client,
50
+ this.state,
51
+ () => this.persist(),
52
+ options.reader,
53
+ this.machine,
54
+ options.operatorPrefix,
35
55
  );
36
56
  this.events = new MonitorEvents({
37
- client,
57
+ client: this.client,
58
+ reconnect: options.reconnect,
38
59
  onEvent: (event) => this.handleEvent(event),
39
60
  onReconnect: () => this.reconcileNow(),
40
- onWarning: (message) => this.context?.ui.notify(message, "warning"),
61
+ onWarning: (message) => this.onWarning(message),
41
62
  targets: () => this.list().map((record) => record.paneId),
42
63
  });
43
64
  }
44
65
 
45
- async activate(ctx: ExtensionContext): Promise<void> {
66
+ async activate(
67
+ ctx: ExtensionContext,
68
+ restored: unknown[] = [],
69
+ ): Promise<void> {
46
70
  this.deactivate();
47
71
  const generation = this.activationGeneration;
48
72
  this.context = ctx;
49
- this.restore(ctx);
50
- renderAgentWidget(this.context, this.list());
51
- await this.reconcile(generation, ctx);
73
+ const dropped = this.state.restore(restored, this.selfPaneId);
74
+ if (dropped > 0) {
75
+ ctx.ui.notify(
76
+ `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"} for ${this.machine}`,
77
+ "warning",
78
+ );
79
+ }
80
+ this.onRefresh();
81
+ await this.reconcile(generation, ctx, dropped > 0);
52
82
  if (generation !== this.activationGeneration || ctx !== this.context)
53
83
  return;
54
84
  await this.events.start();
@@ -56,7 +86,6 @@ export class AgentMonitor {
56
86
 
57
87
  deactivate(): void {
58
88
  this.activationGeneration += 1;
59
- renderAgentWidget(this.context, []);
60
89
  this.context = undefined;
61
90
  this.events.stop();
62
91
  this.settlements.stop();
@@ -71,7 +100,7 @@ export class AgentMonitor {
71
100
  }
72
101
 
73
102
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
74
- if (panel.pane_id === process.env["HERDR_PANE_ID"]) {
103
+ if (panel.pane_id === this.selfPaneId) {
75
104
  throw new Error("refusing to monitor the controlling Pi session");
76
105
  }
77
106
  const reply = await this.settlements.latest(panel);
@@ -129,54 +158,36 @@ export class AgentMonitor {
129
158
  await this.reconcile(this.activationGeneration, this.context);
130
159
  }
131
160
 
132
- private restore(ctx: ExtensionContext): void {
133
- let latest: MonitorStateEntry | undefined;
134
- for (const entry of ctx.sessionManager.getBranch()) {
135
- if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
136
- continue;
137
- const data = entry.data as Partial<MonitorStateEntry>;
138
- if (Array.isArray(data?.agents)) {
139
- latest = { agents: data.agents };
140
- }
141
- }
142
- const dropped = this.state.restore(
143
- latest?.agents ?? [],
144
- process.env["HERDR_PANE_ID"],
145
- );
146
- if (dropped > 0) {
147
- ctx.ui.notify(
148
- `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"}`,
149
- "warning",
150
- );
151
- }
152
- }
153
-
154
161
  private persist(): void {
155
- this.pi.appendEntry(MONITOR_STATE_TYPE, { agents: this.list() });
156
- renderAgentWidget(this.context, this.list());
162
+ this.onChange();
157
163
  }
158
164
 
159
165
  private async reconcile(
160
166
  generation: number,
161
167
  context: ExtensionContext | undefined,
168
+ persistRestoration = false,
162
169
  ): Promise<void> {
163
170
  if (
164
171
  !context ||
165
172
  generation !== this.activationGeneration ||
166
- context !== this.context ||
167
- this.list().length === 0
173
+ context !== this.context
168
174
  ) {
169
175
  return;
170
176
  }
177
+ if (this.list().length === 0) {
178
+ if (persistRestoration) this.persist();
179
+ else this.onRefresh();
180
+ return;
181
+ }
171
182
  const snapshot = await getSnapshot(this.client);
172
183
  if (generation !== this.activationGeneration || context !== this.context)
173
184
  return;
174
185
  const { changed, completions } = this.state.reconcile(
175
186
  snapshot,
176
- process.env["HERDR_PANE_ID"],
187
+ this.selfPaneId,
177
188
  );
178
- if (changed) this.persist();
179
- else renderAgentWidget(this.context, this.list());
189
+ if (changed || persistRestoration) this.persist();
190
+ else this.onRefresh();
180
191
  for (const completion of completions) {
181
192
  void this.report(completion);
182
193
  }
@@ -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
+ });