@howaboua/pi-shepherdr 0.1.5 → 0.2.0

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
@@ -17,6 +17,7 @@ import {
17
17
  import type {
18
18
  HerdrEvent,
19
19
  MonitoredAgent,
20
+ MonitoringIssue,
20
21
  PaneInfo,
21
22
  SessionView,
22
23
  } from "./types.js";
@@ -24,10 +25,12 @@ import type {
24
25
  interface AgentMonitorOptions {
25
26
  client: HerdrConnection;
26
27
  machine: string;
28
+ machineLabel: () => string;
27
29
  onChange: () => void;
28
30
  onRefresh: () => void;
29
31
  operatorPrefix: string;
30
- onWarning: (message: string) => void;
32
+ onWarning: (issue: MonitoringIssue) => void;
33
+ onRecovered: () => void;
31
34
  reader?: AssistantReader;
32
35
  reconnect: boolean;
33
36
  selfPaneId?: string;
@@ -39,7 +42,6 @@ export class AgentMonitor {
39
42
  private readonly onChange: () => void;
40
43
  private readonly onRefresh: () => void;
41
44
  private readonly selfPaneId: string | undefined;
42
- private readonly onWarning: (message: string) => void;
43
45
  private readonly state = new MonitorState();
44
46
  private readonly events: MonitorEvents;
45
47
  private readonly settlements: SettlementReporter;
@@ -52,22 +54,28 @@ export class AgentMonitor {
52
54
  this.onChange = options.onChange;
53
55
  this.onRefresh = options.onRefresh;
54
56
  this.selfPaneId = options.selfPaneId;
55
- this.onWarning = options.onWarning;
56
57
  this.settlements = new SettlementReporter(
57
58
  pi,
58
59
  this.client,
59
60
  this.state,
60
- () => this.persist(),
61
+ () => {
62
+ this.persist();
63
+ this.refreshAfterEvent();
64
+ },
61
65
  options.reader,
62
- this.machine,
63
- options.operatorPrefix,
66
+ {
67
+ machine: this.machine,
68
+ label: options.machineLabel,
69
+ operatorPrefix: options.operatorPrefix,
70
+ },
64
71
  );
65
72
  this.events = new MonitorEvents({
66
73
  client: this.client,
67
74
  reconnect: options.reconnect,
68
75
  onEvent: (event) => this.handleEvent(event),
69
- onReconnect: () => this.reconcileNow(),
70
- onWarning: (message) => this.onWarning(message),
76
+ reconcile: () => this.reconcileNow(),
77
+ onWarning: options.onWarning,
78
+ onRecovered: options.onRecovered,
71
79
  targets: () => this.list().map((record) => record.paneId),
72
80
  });
73
81
  }
@@ -104,10 +112,6 @@ export class AgentMonitor {
104
112
  return this.state.list();
105
113
  }
106
114
 
107
- isMonitored(paneId: string): boolean {
108
- return this.state.isMonitored(paneId);
109
- }
110
-
111
115
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
112
116
  return this.watchPanel(panel, true);
113
117
  }
@@ -131,7 +135,6 @@ export class AgentMonitor {
131
135
  );
132
136
  this.persist();
133
137
  await this.events.refresh();
134
- await this.reconcile(this.activationGeneration, this.context);
135
138
  if (reportCurrent && isSettledStatus(panel.agent_status)) {
136
139
  await this.report({ record, status: panel.agent_status });
137
140
  }
@@ -205,6 +208,10 @@ export class AgentMonitor {
205
208
  await this.reconcile(this.activationGeneration, this.context);
206
209
  }
207
210
 
211
+ retryMonitoring(): Promise<void> {
212
+ return this.events.retry();
213
+ }
214
+
208
215
  private persist(): void {
209
216
  this.onChange();
210
217
  }
@@ -257,14 +264,14 @@ export class AgentMonitor {
257
264
  new Error(`${parsed.paneId} closed before its work settled`),
258
265
  );
259
266
  this.persist();
260
- void this.events.refresh();
267
+ this.refreshAfterEvent();
261
268
  }
262
269
  return;
263
270
  }
264
271
  if (parsed.type === "moved") {
265
272
  if (!this.state.movePane(parsed.previousPaneId, parsed.pane)) return;
266
273
  this.persist();
267
- void this.events.refresh();
274
+ this.refreshAfterEvent();
268
275
  return;
269
276
  }
270
277
  const result = this.state.applyStatus(parsed.paneId, parsed.status);
@@ -279,6 +286,11 @@ export class AgentMonitor {
279
286
  }
280
287
  }
281
288
 
289
+ private refreshAfterEvent(): void {
290
+ // MonitorEvents reports failures through onWarning before rejecting awaited updates.
291
+ void this.events.refresh().catch(() => undefined);
292
+ }
293
+
282
294
  private report(request: SettlementRequest): Promise<void> {
283
295
  const generation = this.activationGeneration;
284
296
  const context = this.context;
@@ -4,7 +4,7 @@ import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
 
7
- const BRIDGE_VERSION = 3;
7
+ const BRIDGE_VERSION = 5;
8
8
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
9
9
  const READ_CHUNK_BYTES = 64 * 1024;
10
10
  const subscriptions = new Map();
@@ -24,11 +24,17 @@ function expandHome(path) {
24
24
  }
25
25
 
26
26
  function socketPath() {
27
- const explicit = argument("socket");
28
- if (explicit) return expandHome(explicit);
29
27
  const root = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
30
28
  const session = argument("session");
31
- return session
29
+ if (
30
+ !session ||
31
+ !/^[a-zA-Z0-9_.-]{1,64}$/.test(session) ||
32
+ session === "." ||
33
+ session === ".."
34
+ ) {
35
+ throw new Error("A valid Herdr --session is required");
36
+ }
37
+ return session !== "default"
32
38
  ? join(root, "herdr", "sessions", session, "herdr.sock")
33
39
  : join(root, "herdr", "herdr.sock");
34
40
  }
@@ -145,16 +151,24 @@ function subscribe(id, requested) {
145
151
  const requestId = `pi-shepherdr-bridge:subscribe:${crypto.randomUUID()}`;
146
152
  let acknowledged = false;
147
153
  let closed = false;
154
+ let ended = false;
148
155
  let socket;
149
- const timer = setTimeout(() => {
150
- socket.destroy();
151
- reject(new Error("Herdr events.subscribe timed out"));
152
- }, 10_000);
156
+ const timer = setTimeout(
157
+ () => disconnected(new Error("Herdr events.subscribe timed out")),
158
+ 10_000,
159
+ );
153
160
  timer.unref();
154
161
  const disconnected = (error) => {
162
+ if (ended) return;
163
+ ended = true;
155
164
  clearTimeout(timer);
165
+ subscriptions.delete(id);
166
+ socket.destroy();
156
167
  if (!acknowledged)
157
- reject(error ?? new Error("Herdr subscription disconnected"));
168
+ reject(
169
+ error ??
170
+ new Error("Herdr events.subscribe closed before acknowledgement"),
171
+ );
158
172
  else if (!closed) {
159
173
  process.stderr.write(
160
174
  `Herdr monitoring disconnected${error ? `: ${error.message}` : ""}\n`,
@@ -171,6 +185,7 @@ function subscribe(id, requested) {
171
185
  params: { subscriptions: requested },
172
186
  },
173
187
  (value) => {
188
+ if (ended) return;
174
189
  if (!acknowledged && value.id === requestId) {
175
190
  if (value.error !== undefined) {
176
191
  disconnected(errorFromResponse(value.error));
@@ -188,10 +203,6 @@ function subscribe(id, requested) {
188
203
  }
189
204
  acknowledged = true;
190
205
  clearTimeout(timer);
191
- subscriptions.set(id, () => {
192
- closed = true;
193
- socket.destroy();
194
- });
195
206
  resolveSubscription();
196
207
  return;
197
208
  }
@@ -209,6 +220,10 @@ function subscribe(id, requested) {
209
220
  },
210
221
  disconnected,
211
222
  );
223
+ subscriptions.set(id, () => {
224
+ closed = true;
225
+ disconnected(new Error("Herdr subscription cancelled"));
226
+ });
212
227
  });
213
228
  }
214
229
 
@@ -238,7 +253,7 @@ function assistantFromMessage(id, message) {
238
253
  };
239
254
  }
240
255
 
241
- function userFromMessage(id, message) {
256
+ function inputFromMessage(id, message) {
242
257
  if (message.role !== "user") return undefined;
243
258
  const text = [];
244
259
  if (typeof message.content === "string") text.push(message.content);
@@ -287,20 +302,22 @@ function askCall(value) {
287
302
  typeof value !== "object" ||
288
303
  value.type !== "toolCall" ||
289
304
  value.name !== "ask" ||
290
- typeof value.id !== "string" ||
291
- !value.arguments ||
292
- typeof value.arguments !== "object"
305
+ typeof value.id !== "string"
293
306
  )
294
307
  return undefined;
295
- const prompts = (
296
- Array.isArray(value.arguments.prompts) ? value.arguments.prompts : []
297
- )
308
+ return askFromInput(value.id, value.arguments);
309
+ }
310
+
311
+ function askFromInput(toolCallId, input) {
312
+ if (!input || typeof input !== "object" || Array.isArray(input))
313
+ return undefined;
314
+ const prompts = (Array.isArray(input.prompts) ? input.prompts : [])
298
315
  .map(askPrompt)
299
316
  .filter(Boolean);
300
317
  if (prompts.length === 0) return undefined;
301
318
  return {
302
- toolCallId: value.id,
303
- handoff: value.arguments.handoff === true,
319
+ toolCallId,
320
+ handoff: input.handoff === true,
304
321
  prompts,
305
322
  };
306
323
  }
@@ -312,15 +329,15 @@ async function sessionView(path, size) {
312
329
  let assistantDepth;
313
330
  let ask;
314
331
  let depth = 0;
315
- let user;
316
- let userDepth;
332
+ let input;
333
+ let inputDepth;
317
334
  const resolved = new Set();
318
335
  const result = () => ({
319
336
  ...(assistant ? { assistant } : {}),
320
337
  ...(ask ? { ask } : {}),
321
- ...(user ? { user } : {}),
322
- ...(assistantDepth !== undefined && userDepth !== undefined
323
- ? { assistantAfterUser: assistantDepth < userDepth }
338
+ ...(input ? { input } : {}),
339
+ ...(assistantDepth !== undefined && inputDepth !== undefined
340
+ ? { assistantAfterInput: assistantDepth < inputDepth }
324
341
  : {}),
325
342
  });
326
343
  const inspect = (line) => {
@@ -336,6 +353,29 @@ async function sessionView(path, size) {
336
353
  if (entry.id !== targetId) return false;
337
354
  const currentDepth = depth;
338
355
  depth += 1;
356
+ if (entry.type === "custom" && entry.customType === "pi-ask-active") {
357
+ const update = entry.data;
358
+ if (update?.version === 1 && typeof update.id === "string") {
359
+ if (update.state === "closed") resolved.add(update.id);
360
+ else if (
361
+ update.state === "active" &&
362
+ !ask &&
363
+ !resolved.has(update.id)
364
+ ) {
365
+ ask = askFromInput(update.id, update);
366
+ }
367
+ }
368
+ }
369
+ if (
370
+ !input &&
371
+ entry.type === "custom_message" &&
372
+ entry.customType === "herdr-agent-message" &&
373
+ typeof entry.content === "string" &&
374
+ entry.content
375
+ ) {
376
+ input = { id: entry.id, text: entry.content };
377
+ inputDepth = currentDepth;
378
+ }
339
379
  const message = entry.message;
340
380
  if (message && typeof message === "object") {
341
381
  if (
@@ -347,9 +387,9 @@ async function sessionView(path, size) {
347
387
  assistant = assistantFromMessage(entry.id, message);
348
388
  if (assistant) assistantDepth = currentDepth;
349
389
  }
350
- if (!user) {
351
- user = userFromMessage(entry.id, message);
352
- if (user) userDepth = currentDepth;
390
+ if (!input) {
391
+ input = inputFromMessage(entry.id, message);
392
+ if (input) inputDepth = currentDepth;
353
393
  }
354
394
  if (
355
395
  !ask &&
@@ -3,11 +3,11 @@ import { randomUUID } from "node:crypto";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import type { HerdrConnection } from "./herdr-client.js";
6
- import type { RemoteMachineConfig } from "./machines-config.js";
6
+ import type { SshMachine } from "./machine-catalog.js";
7
7
  import type { AssistantReader } from "./session-reader.js";
8
8
  import type { HerdrEvent, LatestAssistant, SessionView } from "./types.js";
9
9
 
10
- const BRIDGE_VERSION = 3;
10
+ const BRIDGE_VERSION = 5;
11
11
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
12
12
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
13
13
  const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
@@ -73,26 +73,28 @@ function executablePath(path: string): string {
73
73
  : shellQuote(path);
74
74
  }
75
75
 
76
- function remoteCommand(config: RemoteMachineConfig): string {
76
+ function remoteCommand(config: SshMachine): string {
77
77
  const args = [
78
78
  "exec",
79
- shellQuote(config.node),
79
+ "node",
80
80
  executablePath(REMOTE_HELPER),
81
- ...(config.socket ? ["--socket", shellQuote(config.socket)] : []),
82
- ...(config.session ? ["--session", shellQuote(config.session)] : []),
81
+ "--session",
82
+ shellQuote(config.session),
83
83
  ];
84
84
  return args.join(" ");
85
85
  }
86
86
 
87
87
  function spawnConnector(
88
- config: RemoteMachineConfig,
88
+ config: SshMachine,
89
89
  command: string,
90
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
- });
91
+ return spawn(
92
+ "ssh",
93
+ ["-T", "-o", "BatchMode=yes", "--", config.target, command],
94
+ {
95
+ stdio: ["pipe", "pipe", "pipe"],
96
+ },
97
+ );
96
98
  }
97
99
 
98
100
  function appendBounded(current: string, chunk: Buffer): string {
@@ -102,12 +104,9 @@ function appendBounded(current: string, chunk: Buffer): string {
102
104
  : next.slice(next.length - MAX_DIAGNOSTIC_BYTES);
103
105
  }
104
106
 
105
- async function deploy(
106
- config: RemoteMachineConfig,
107
- source: Buffer,
108
- ): Promise<void> {
107
+ async function deploy(config: SshMachine, source: Buffer): Promise<void> {
109
108
  const command = [
110
- shellQuote(config.node),
109
+ "node",
111
110
  "-e",
112
111
  shellQuote(DEPLOY_SOURCE),
113
112
  shellQuote(REMOTE_HELPER),
@@ -179,7 +178,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
179
178
  }
180
179
 
181
180
  static async connect(
182
- config: RemoteMachineConfig,
181
+ config: SshMachine,
183
182
  onClose: (error: Error) => void,
184
183
  ): Promise<RemoteHerdrClient> {
185
184
  const source = await readFile(
@@ -212,21 +211,29 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
212
211
  subscriptions: object[],
213
212
  onEvent: (event: HerdrEvent) => void,
214
213
  onDisconnect: (error?: Error) => void,
214
+ signal?: AbortSignal,
215
215
  ): Promise<() => void> {
216
+ signal?.throwIfAborted();
216
217
  const id = randomUUID();
217
218
  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 () => {
219
+ const unsubscribe = () => {
220
+ signal?.removeEventListener("abort", unsubscribe);
225
221
  if (!this.subscriptions.delete(id) || this.closed) return;
226
222
  void this.call({ op: "unsubscribe", subscription: id }).catch(
227
223
  () => undefined,
228
224
  );
229
225
  };
226
+ try {
227
+ const ready = this.call({ id, op: "subscribe", subscriptions }, 11_000);
228
+ signal?.addEventListener("abort", unsubscribe, { once: true });
229
+ if (signal?.aborted) unsubscribe();
230
+ await ready;
231
+ signal?.throwIfAborted();
232
+ } catch (error) {
233
+ unsubscribe();
234
+ throw error;
235
+ }
236
+ return unsubscribe;
230
237
  }
231
238
 
232
239
  async latest(path?: string): Promise<LatestAssistant | undefined> {
@@ -1,7 +1,7 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import type {
3
3
  LatestAssistant,
4
- LatestUser,
4
+ LatestInput,
5
5
  PendingAsk,
6
6
  SessionView,
7
7
  } from "./types.js";
@@ -43,10 +43,10 @@ function assistantFromMessage(
43
43
  };
44
44
  }
45
45
 
46
- function userFromMessage(
46
+ function inputFromMessage(
47
47
  id: string,
48
48
  message: Record<string, unknown>,
49
- ): LatestUser | undefined {
49
+ ): LatestInput | undefined {
50
50
  if (message["role"] !== "user") return undefined;
51
51
  const text: string[] = [];
52
52
  if (typeof message["content"] === "string") {
@@ -101,14 +101,21 @@ function askCall(value: unknown): PendingAsk | undefined {
101
101
  ) {
102
102
  return undefined;
103
103
  }
104
- const args = record(part["arguments"]);
104
+ return askFromInput(part["id"], part["arguments"]);
105
+ }
106
+
107
+ function askFromInput(
108
+ toolCallId: string,
109
+ input: unknown,
110
+ ): PendingAsk | undefined {
111
+ const args = record(input);
105
112
  if (!args) return undefined;
106
113
  const prompts = (Array.isArray(args["prompts"]) ? args["prompts"] : [])
107
114
  .map(askPrompt)
108
115
  .filter((prompt): prompt is NonNullable<typeof prompt> => Boolean(prompt));
109
116
  if (prompts.length === 0) return undefined;
110
117
  return {
111
- toolCallId: part["id"],
118
+ toolCallId,
112
119
  handoff: args["handoff"] === true,
113
120
  prompts,
114
121
  };
@@ -134,15 +141,15 @@ async function readSessionView(
134
141
  let assistantDepth: number | undefined;
135
142
  let ask: PendingAsk | undefined;
136
143
  let depth = 0;
137
- let user: LatestUser | undefined;
138
- let userDepth: number | undefined;
144
+ let input: LatestInput | undefined;
145
+ let inputDepth: number | undefined;
139
146
  const resolved = new Set<string>();
140
147
  const result = (): SessionView => ({
141
148
  ...(assistant ? { assistant } : {}),
142
149
  ...(ask ? { ask } : {}),
143
- ...(user ? { user } : {}),
144
- ...(assistantDepth !== undefined && userDepth !== undefined
145
- ? { assistantAfterUser: assistantDepth < userDepth }
150
+ ...(input ? { input } : {}),
151
+ ...(assistantDepth !== undefined && inputDepth !== undefined
152
+ ? { assistantAfterInput: assistantDepth < inputDepth }
146
153
  : {}),
147
154
  });
148
155
  const inspect = (line: Buffer): boolean => {
@@ -159,6 +166,30 @@ async function readSessionView(
159
166
  if (id !== targetId) return false;
160
167
  const currentDepth = depth;
161
168
  depth += 1;
169
+ if (entry["type"] === "custom" && entry["customType"] === "pi-ask-active") {
170
+ const update = record(entry["data"]);
171
+ if (update?.["version"] === 1 && typeof update["id"] === "string") {
172
+ const callId = update["id"];
173
+ if (update["state"] === "closed") resolved.add(callId);
174
+ else if (
175
+ update["state"] === "active" &&
176
+ !ask &&
177
+ !resolved.has(callId)
178
+ ) {
179
+ ask = askFromInput(callId, update);
180
+ }
181
+ }
182
+ }
183
+ if (
184
+ !input &&
185
+ entry["type"] === "custom_message" &&
186
+ entry["customType"] === "herdr-agent-message" &&
187
+ typeof entry["content"] === "string" &&
188
+ entry["content"]
189
+ ) {
190
+ input = { id, text: entry["content"] };
191
+ inputDepth = currentDepth;
192
+ }
162
193
  const message = record(entry["message"]);
163
194
  if (message) {
164
195
  const resolvedId = resolvedToolCallId(message);
@@ -167,9 +198,9 @@ async function readSessionView(
167
198
  assistant = assistantFromMessage(id, message);
168
199
  if (assistant) assistantDepth = currentDepth;
169
200
  }
170
- if (!user) {
171
- user = userFromMessage(id, message);
172
- if (user) userDepth = currentDepth;
201
+ if (!input) {
202
+ input = inputFromMessage(id, message);
203
+ if (input) inputDepth = currentDepth;
173
204
  }
174
205
  if (
175
206
  !ask &&