@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/settlement.ts CHANGED
@@ -60,6 +60,30 @@ const SETTLEMENT_RETRY_WINDOW_SECONDS = Math.ceil(
60
60
  SETTLEMENT_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0) / 1_000,
61
61
  );
62
62
 
63
+ function attemptKey(terminalId: string, attemptId: string | undefined): string {
64
+ return JSON.stringify([terminalId, attemptId ?? null]);
65
+ }
66
+
67
+ function blockedSettlement(
68
+ record: MonitoredAgent,
69
+ ): CollectedSettlementWithSession {
70
+ return {
71
+ agent: {
72
+ agent: "pi",
73
+ agent_status: "blocked",
74
+ ...(record.cwd ? { cwd: record.cwd } : {}),
75
+ ...(record.name ? { name: record.name } : {}),
76
+ pane_id: record.paneId,
77
+ tab_id: record.tabId,
78
+ terminal_id: record.terminalId,
79
+ workspace_id: record.workspaceId,
80
+ },
81
+ labels: {},
82
+ session: {},
83
+ status: "blocked",
84
+ };
85
+ }
86
+
63
87
  export interface SettlementRequest {
64
88
  blockedMessage?: string;
65
89
  record: MonitoredAgent;
@@ -74,6 +98,12 @@ export interface SettlementLifecycle {
74
98
  isCurrent: () => boolean;
75
99
  }
76
100
 
101
+ interface PendingBlockedSettlement {
102
+ lifecycle: SettlementLifecycle;
103
+ request: SettlementRequest;
104
+ retry?: SettlementRetry;
105
+ }
106
+
77
107
  export class SettlementCollector {
78
108
  private readonly client: HerdrConnection;
79
109
  private readonly reader: AssistantReader;
@@ -86,8 +116,13 @@ export class SettlementCollector {
86
116
  this.reader = reader;
87
117
  }
88
118
 
89
- latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
90
- return this.reader.latest(sessionPath(panel));
119
+ async latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
120
+ try {
121
+ return await this.reader.latest(sessionPath(panel));
122
+ } catch (error) {
123
+ if (panel.agent_status !== "blocked") throw error;
124
+ return undefined;
125
+ }
91
126
  }
92
127
 
93
128
  view(panel: PaneInfo): Promise<SessionView> {
@@ -96,19 +131,30 @@ export class SettlementCollector {
96
131
 
97
132
  async collect(
98
133
  record: MonitoredAgent,
134
+ reportedStatus?: "blocked",
99
135
  ): Promise<CollectedSettlementWithSession | undefined> {
100
136
  const [current, snapshot] = await Promise.all([
101
137
  getAgent(this.client, record.paneId),
102
138
  getSnapshot(this.client),
103
139
  ]);
104
- if (
105
- current.terminal_id !== record.terminalId ||
106
- current.agent !== "pi" ||
107
- !isSettledStatus(current.agent_status)
108
- ) {
109
- return undefined;
140
+ if (current.terminal_id !== record.terminalId || current.agent !== "pi") {
141
+ return reportedStatus === "blocked"
142
+ ? blockedSettlement(record)
143
+ : undefined;
144
+ }
145
+ const status =
146
+ reportedStatus ??
147
+ (isSettledStatus(current.agent_status)
148
+ ? current.agent_status
149
+ : undefined);
150
+ if (!status) return undefined;
151
+ let view: SessionView;
152
+ try {
153
+ view = await this.reader.view(sessionPath(current));
154
+ } catch (error) {
155
+ if (status !== "blocked") throw error;
156
+ view = {};
110
157
  }
111
- const view = await this.reader.view(sessionPath(current));
112
158
  const workspace = snapshot.workspaces.find(
113
159
  (candidate) => candidate.workspace_id === current.workspace_id,
114
160
  )?.label;
@@ -122,11 +168,9 @@ export class SettlementCollector {
122
168
  ...(tab ? { tab } : {}),
123
169
  },
124
170
  ...(view.assistant ? { reply: view.assistant } : {}),
125
- ...(current.agent_status === "blocked" && view.ask
126
- ? { ask: view.ask }
127
- : {}),
171
+ ...(status === "blocked" && view.ask ? { ask: view.ask } : {}),
128
172
  session: view,
129
- status: current.agent_status,
173
+ status,
130
174
  };
131
175
  }
132
176
  }
@@ -135,9 +179,13 @@ export class SettlementReporter {
135
179
  private readonly collector: SettlementCollector;
136
180
  private readonly persist: () => void;
137
181
  private readonly pi: ExtensionAPI;
138
- private readonly machine: string;
139
- private readonly operatorPrefix: string;
140
- private readonly reporting = new Set<string>();
182
+ private readonly origin: {
183
+ machine: string;
184
+ label: () => string;
185
+ operatorPrefix: string;
186
+ };
187
+ private readonly reporting = new Map<string, SettledAgentStatus>();
188
+ private readonly pendingBlocked = new Map<string, PendingBlockedSettlement>();
141
189
  private readonly claims = new Map<string, SettlementClaim>();
142
190
  private readonly retries = new Map<string, NodeJS.Timeout>();
143
191
  private readonly state: MonitorState;
@@ -147,16 +195,14 @@ export class SettlementReporter {
147
195
  client: HerdrConnection,
148
196
  state: MonitorState,
149
197
  persist: () => void,
150
- reader?: AssistantReader,
151
- machine = "local",
152
- operatorPrefix = "herdr",
198
+ reader: AssistantReader | undefined,
199
+ origin: { machine: string; label: () => string; operatorPrefix: string },
153
200
  ) {
154
201
  this.pi = pi;
155
202
  this.collector = new SettlementCollector(client, reader);
156
203
  this.state = state;
157
204
  this.persist = persist;
158
- this.machine = machine;
159
- this.operatorPrefix = operatorPrefix;
205
+ this.origin = origin;
160
206
  }
161
207
 
162
208
  latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
@@ -169,6 +215,7 @@ export class SettlementReporter {
169
215
 
170
216
  stop(): void {
171
217
  this.reporting.clear();
218
+ this.pendingBlocked.clear();
172
219
  for (const claim of this.claims.values()) {
173
220
  claim.cleanup();
174
221
  claim.reject(new Error("Shepherdr monitor stopped"));
@@ -233,39 +280,73 @@ export class SettlementReporter {
233
280
  attemptId: activityAttemptId(request.record.activity),
234
281
  count: 0,
235
282
  };
236
- const key = `${lifecycle.generation}:${request.record.terminalId}`;
237
- if (this.reporting.has(key)) return;
238
- this.reporting.add(key);
283
+ const key = `${lifecycle.generation}:${attemptKey(
284
+ request.record.terminalId,
285
+ retryState.attemptId,
286
+ )}`;
287
+ const activeStatus = this.reporting.get(key);
288
+ if (activeStatus) {
289
+ if (request.status === "blocked" && activeStatus !== "blocked") {
290
+ this.pendingBlocked.set(key, {
291
+ lifecycle,
292
+ request,
293
+ ...(retry ? { retry } : {}),
294
+ });
295
+ }
296
+ return;
297
+ }
298
+ this.reporting.set(key, request.status);
239
299
  try {
240
- const settlement = await this.collector.collect(request.record);
300
+ const settlement = await this.collector.collect(
301
+ request.record,
302
+ request.status === "blocked" ? "blocked" : undefined,
303
+ );
241
304
  if (!settlement || !lifecycle.isCurrent()) return;
305
+ if (this.pendingBlocked.has(key)) return;
242
306
  const current = this.state.byPane(settlement.agent.pane_id);
243
307
  if (!current || current.terminalId !== request.record.terminalId) return;
244
- if (activityTask(current.activity) !== task) return;
245
- if (activityAttemptId(current.activity) !== retryState.attemptId) return;
308
+ if (
309
+ activityTask(current.activity) !== task ||
310
+ activityAttemptId(current.activity) !== retryState.attemptId
311
+ ) {
312
+ if (request.status !== "blocked") return;
313
+ this.clearRetry(request.record.terminalId, retryState.attemptId);
314
+ this.deliverSettlement(
315
+ lifecycle,
316
+ request.record,
317
+ settlement,
318
+ retryState.attemptId,
319
+ request.blockedMessage,
320
+ undefined,
321
+ );
322
+ return;
323
+ }
246
324
  const retryRequest = task ? { ...request, task } : request;
247
325
  const expectedUser = activityExpectedUser(current.activity);
326
+ const blocked = settlement.status === "blocked";
327
+ // A blocked status is authoritative even when Pi has not persisted the turn.
248
328
  // Pi persists expanded skills/templates, not the submitted command text.
249
329
  if (
330
+ !blocked &&
250
331
  expectedUser &&
251
- (settlement.session.assistantAfterUser !== true ||
252
- !settlement.session.user ||
253
- settlement.session.user.id === expectedUser.after)
332
+ (settlement.session.assistantAfterInput !== true ||
333
+ !settlement.session.input ||
334
+ settlement.session.input.id === expectedUser.after)
254
335
  ) {
255
336
  if (!this.retry(lifecycle, retryRequest, retryState)) {
256
337
  this.failReconciliation(
257
338
  lifecycle,
258
339
  current,
259
- "the submitted user message and reply were not persisted",
340
+ "the submitted input and reply were not persisted",
260
341
  );
261
342
  }
262
343
  return;
263
344
  }
264
345
  const newReply =
265
- settlement.reply?.id !== current.lastAssistantId
346
+ !blocked && settlement.reply?.id !== current.lastAssistantId
266
347
  ? settlement.reply
267
348
  : undefined;
268
- if (request.requireNewReply && !newReply && !settlement.ask) {
349
+ if (!blocked && request.requireNewReply && !newReply) {
269
350
  if (!this.retry(lifecycle, retryRequest, retryState)) {
270
351
  this.failReconciliation(
271
352
  lifecycle,
@@ -280,48 +361,52 @@ export class SettlementReporter {
280
361
  ? request.blockedMessage
281
362
  : undefined;
282
363
  const attemptId = activityAttemptId(current.activity);
283
- const claim = attemptId ? this.claims.get(attemptId) : undefined;
284
364
  if (
285
365
  this.state.complete(
286
366
  current.terminalId,
287
367
  settlement.status,
288
368
  task,
289
- settlement.reply?.id,
369
+ newReply?.id,
290
370
  )
291
371
  ) {
292
- this.clearRetry(current.terminalId);
372
+ this.clearRetry(current.terminalId, retryState.attemptId);
293
373
  this.persist();
294
- if (claim && attemptId) {
295
- this.claims.delete(attemptId);
296
- claim.cleanup();
297
- const {
298
- reply: _latestReply,
299
- session: _session,
300
- ...claimedSettlement
301
- } = settlement;
302
- claim.resolve({
303
- ...claimedSettlement,
304
- record: current,
305
- ...(blockedMessage ? { blockedMessage } : {}),
306
- ...(newReply ? { reply: newReply } : {}),
307
- });
308
- } else {
309
- injectAgentEvent(this.pi, lifecycle.context, {
310
- agent: settlement.agent,
311
- agentToolName: "agents",
312
- ...(settlement.ask ? { ask: settlement.ask } : {}),
313
- machine: this.machine,
314
- operatorPrefix: this.operatorPrefix,
315
- ...(blockedMessage ? { blockedMessage } : {}),
316
- labels: settlement.labels,
317
- record: current,
318
- ...(newReply ? { reply: newReply } : {}),
319
- status: settlement.status,
320
- });
321
- }
374
+ this.deliverSettlement(
375
+ lifecycle,
376
+ current,
377
+ settlement,
378
+ attemptId,
379
+ blockedMessage,
380
+ newReply,
381
+ );
322
382
  }
323
383
  } catch (error) {
324
384
  if (!lifecycle.isCurrent()) return;
385
+ if (request.status === "blocked") {
386
+ const current = this.state.byTerminal(request.record.terminalId);
387
+ if (current) {
388
+ const currentOwnsAttempt =
389
+ activityTask(current.activity) === task &&
390
+ activityAttemptId(current.activity) === retryState.attemptId;
391
+ this.clearRetry(request.record.terminalId, retryState.attemptId);
392
+ if (
393
+ currentOwnsAttempt &&
394
+ this.state.complete(current.terminalId, "blocked", task)
395
+ ) {
396
+ this.persist();
397
+ }
398
+ this.deliverSettlement(
399
+ lifecycle,
400
+ currentOwnsAttempt ? current : request.record,
401
+ blockedSettlement(current),
402
+ retryState.attemptId,
403
+ request.blockedMessage,
404
+ undefined,
405
+ );
406
+ }
407
+ return;
408
+ }
409
+ if (this.pendingBlocked.has(key)) return;
325
410
  if (retryState.count === 0) {
326
411
  lifecycle.context.ui.notify(
327
412
  `Could not collect ${request.record.name ?? request.record.paneId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -345,13 +430,59 @@ export class SettlementReporter {
345
430
  }
346
431
  } finally {
347
432
  this.reporting.delete(key);
433
+ const pending = this.pendingBlocked.get(key);
434
+ if (pending) {
435
+ this.pendingBlocked.delete(key);
436
+ void this.report(pending.lifecycle, pending.request, pending.retry);
437
+ }
348
438
  }
349
439
  }
350
440
 
351
- private clearRetry(terminalId: string): void {
352
- const retry = this.retries.get(terminalId);
441
+ private deliverSettlement(
442
+ lifecycle: SettlementLifecycle,
443
+ record: MonitoredAgent,
444
+ settlement: CollectedSettlementWithSession,
445
+ attemptId: string | undefined,
446
+ blockedMessage: string | undefined,
447
+ reply: LatestAssistant | undefined,
448
+ ): void {
449
+ const claim = attemptId ? this.claims.get(attemptId) : undefined;
450
+ if (claim && attemptId) {
451
+ this.claims.delete(attemptId);
452
+ claim.cleanup();
453
+ const {
454
+ reply: _latestReply,
455
+ session: _session,
456
+ ...claimedSettlement
457
+ } = settlement;
458
+ claim.resolve({
459
+ ...claimedSettlement,
460
+ record,
461
+ ...(blockedMessage ? { blockedMessage } : {}),
462
+ ...(reply ? { reply } : {}),
463
+ });
464
+ return;
465
+ }
466
+ injectAgentEvent(this.pi, lifecycle.context, {
467
+ agent: settlement.agent,
468
+ agentToolName: "agents",
469
+ ...(settlement.ask ? { ask: settlement.ask } : {}),
470
+ machine: this.origin.machine,
471
+ machineLabel: this.origin.label(),
472
+ operatorPrefix: this.origin.operatorPrefix,
473
+ ...(blockedMessage ? { blockedMessage } : {}),
474
+ labels: settlement.labels,
475
+ record,
476
+ ...(reply ? { reply } : {}),
477
+ status: settlement.status,
478
+ });
479
+ }
480
+
481
+ private clearRetry(terminalId: string, attemptId: string | undefined): void {
482
+ const key = attemptKey(terminalId, attemptId);
483
+ const retry = this.retries.get(key);
353
484
  if (retry) clearTimeout(retry);
354
- this.retries.delete(terminalId);
485
+ this.retries.delete(key);
355
486
  }
356
487
 
357
488
  private retry(
@@ -371,19 +502,29 @@ export class SettlementReporter {
371
502
  ) {
372
503
  return false;
373
504
  }
374
- if (this.retries.has(request.record.terminalId)) return true;
505
+ const key = attemptKey(request.record.terminalId, retry.attemptId);
506
+ if (this.retries.has(key)) return true;
375
507
  const timer = setTimeout(() => {
376
- this.retries.delete(request.record.terminalId);
508
+ this.retries.delete(key);
377
509
  if (!lifecycle.isCurrent()) return;
378
510
  const current = this.state.byTerminal(request.record.terminalId);
379
511
  if (!current) return;
512
+ const currentOwnsAttempt =
513
+ activityAttemptId(current.activity) === retry.attemptId &&
514
+ activityTask(current.activity) ===
515
+ (request.task ?? activityTask(request.record.activity));
380
516
  void this.report(
381
517
  lifecycle,
382
- { ...request, record: current },
518
+ {
519
+ ...request,
520
+ record: currentOwnsAttempt
521
+ ? current
522
+ : { ...current, activity: request.record.activity },
523
+ },
383
524
  { ...retry, count: retry.count + 1 },
384
525
  );
385
526
  }, delay);
386
- this.retries.set(request.record.terminalId, timer);
527
+ this.retries.set(key, timer);
387
528
  timer.unref();
388
529
  return true;
389
530
  }
@@ -393,7 +534,8 @@ export class SettlementReporter {
393
534
  record: MonitoredAgent,
394
535
  reason: string,
395
536
  ): void {
396
- this.clearRetry(record.terminalId);
537
+ const attemptId = activityAttemptId(record.activity);
538
+ this.clearRetry(record.terminalId, attemptId);
397
539
  const message =
398
540
  (record.name ?? record.paneId) +
399
541
  " settled, but " +
@@ -401,7 +543,6 @@ export class SettlementReporter {
401
543
  " after " +
402
544
  SETTLEMENT_RETRY_WINDOW_SECONDS +
403
545
  " seconds";
404
- const attemptId = activityAttemptId(record.activity);
405
546
  if (attemptId) this.releaseAttempt(attemptId, new Error(message));
406
547
  lifecycle.context.ui.notify(message, "warning");
407
548
  }
package/src/types.ts CHANGED
@@ -39,6 +39,7 @@ export interface PaneInfo {
39
39
  launch_pending?: boolean;
40
40
  name?: string | null;
41
41
  pane_id: string;
42
+ title?: string | null;
42
43
  tab_id: string;
43
44
  terminal_id: string;
44
45
  workspace_id: string;
@@ -63,6 +64,7 @@ export interface SessionSnapshot {
63
64
  }
64
65
 
65
66
  export interface MonitoredAgent {
67
+ readonly scope: "task" | "persistent";
66
68
  readonly activity: AgentActivity;
67
69
  readonly cwd?: string;
68
70
  readonly lastAssistantId?: string;
@@ -75,9 +77,18 @@ export interface MonitoredAgent {
75
77
 
76
78
  type MachineConnectionStatus = "connected" | "connecting" | "unavailable";
77
79
 
80
+ export interface MonitoringIssue {
81
+ state: "degraded" | "unavailable";
82
+ message: string;
83
+ }
84
+
78
85
  export interface MachineStatus {
79
86
  local: boolean;
80
- name: string;
87
+ id: string;
88
+ label?: string;
89
+ target?: string;
90
+ session?: string;
91
+ monitoringIssue?: MonitoringIssue;
81
92
  reason?: string;
82
93
  status: MachineConnectionStatus;
83
94
  }
@@ -90,7 +101,7 @@ export interface LatestAssistant {
90
101
  text: string;
91
102
  }
92
103
 
93
- export interface LatestUser {
104
+ export interface LatestInput {
94
105
  id: string;
95
106
  text: string;
96
107
  }
@@ -109,8 +120,8 @@ export interface PendingAsk {
109
120
  export interface SessionView {
110
121
  ask?: PendingAsk;
111
122
  assistant?: LatestAssistant;
112
- assistantAfterUser?: boolean;
113
- user?: LatestUser;
123
+ assistantAfterInput?: boolean;
124
+ input?: LatestInput;
114
125
  }
115
126
 
116
127
  export interface HerdrEvent {
package/src/widget.ts CHANGED
@@ -35,17 +35,25 @@ function agentLine(
35
35
  ): string {
36
36
  const theme = ctx.ui.theme;
37
37
  const status = activityStatus(agent.activity);
38
- const connected = machines.get(agent.machine)?.status === "connected";
38
+ const machine = machines.get(agent.machine);
39
+ const connected = machine?.status === "connected";
39
40
  const appearance = connected
40
- ? statusAppearance(status)
41
+ ? machine.monitoringIssue
42
+ ? ({ icon: "?", tone: "warning" } as const)
43
+ : statusAppearance(status)
41
44
  : ({ icon: "?", tone: "error" } as const);
42
- const name = `${agent.machine} / ${agent.name ?? agent.paneId}`;
45
+ const name = `${machine?.label ?? agent.machine} / ${agent.name ?? agent.paneId}`;
43
46
  const location = agent.cwd ? basename(agent.cwd) : agent.paneId;
44
47
  return [
45
48
  theme.fg("muted", "│"),
46
49
  theme.fg(appearance.tone, appearance.icon),
47
50
  theme.fg("accent", name),
48
- theme.fg(appearance.tone, connected ? status : "offline"),
51
+ theme.fg(
52
+ appearance.tone,
53
+ connected
54
+ ? `${status}${machine.monitoringIssue ? " (last seen)" : ""}`
55
+ : "offline",
56
+ ),
49
57
  theme.fg("dim", `· ${location}`),
50
58
  ].join(" ");
51
59
  }
@@ -68,7 +76,7 @@ export function renderAgentWidget(
68
76
  (left.name ?? left.paneId).localeCompare(right.name ?? right.paneId),
69
77
  );
70
78
  const machinesByName = new Map(
71
- machines.map((machine) => [machine.name, machine]),
79
+ machines.map((machine) => [machine.id, machine]),
72
80
  );
73
81
  const lines = [
74
82
  `${theme.fg("accent", "╭─ herdr agents")} ${theme.fg("dim", `${agents.length} · ${machines.filter((machine) => machine.status === "connected").length}/${machines.length} machines`)}`,
@@ -81,6 +89,19 @@ export function renderAgentWidget(
81
89
  `${theme.fg("muted", "│")} ${theme.fg("dim", `+${ordered.length - MAX_VISIBLE_AGENTS} more`)}`,
82
90
  );
83
91
  }
92
+ for (const machine of machines) {
93
+ if (!machine.monitoringIssue) continue;
94
+ const status =
95
+ machine.monitoringIssue.state === "degraded"
96
+ ? "incomplete"
97
+ : "unavailable";
98
+ const recovery = machine.local
99
+ ? "retrying"
100
+ : `/herdr connect ${machine.id}`;
101
+ lines.push(
102
+ `${theme.fg("muted", "│")} ${theme.fg("warning", `${machine.id} monitoring ${status} · ${recovery}`)}`,
103
+ );
104
+ }
84
105
  lines.push(theme.fg("muted", "╰─"));
85
106
  ctx.ui.setWidget(WIDGET_ID, lines, { placement: "aboveEditor" });
86
107
  }