@howaboua/pi-shepherdr 0.1.4 → 0.1.6

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
  }
@@ -137,7 +181,8 @@ export class SettlementReporter {
137
181
  private readonly pi: ExtensionAPI;
138
182
  private readonly machine: string;
139
183
  private readonly operatorPrefix: string;
140
- private readonly reporting = new Set<string>();
184
+ private readonly reporting = new Map<string, SettledAgentStatus>();
185
+ private readonly pendingBlocked = new Map<string, PendingBlockedSettlement>();
141
186
  private readonly claims = new Map<string, SettlementClaim>();
142
187
  private readonly retries = new Map<string, NodeJS.Timeout>();
143
188
  private readonly state: MonitorState;
@@ -169,6 +214,7 @@ export class SettlementReporter {
169
214
 
170
215
  stop(): void {
171
216
  this.reporting.clear();
217
+ this.pendingBlocked.clear();
172
218
  for (const claim of this.claims.values()) {
173
219
  claim.cleanup();
174
220
  claim.reject(new Error("Shepherdr monitor stopped"));
@@ -233,20 +279,54 @@ export class SettlementReporter {
233
279
  attemptId: activityAttemptId(request.record.activity),
234
280
  count: 0,
235
281
  };
236
- const key = `${lifecycle.generation}:${request.record.terminalId}`;
237
- if (this.reporting.has(key)) return;
238
- this.reporting.add(key);
282
+ const key = `${lifecycle.generation}:${attemptKey(
283
+ request.record.terminalId,
284
+ retryState.attemptId,
285
+ )}`;
286
+ const activeStatus = this.reporting.get(key);
287
+ if (activeStatus) {
288
+ if (request.status === "blocked" && activeStatus !== "blocked") {
289
+ this.pendingBlocked.set(key, {
290
+ lifecycle,
291
+ request,
292
+ ...(retry ? { retry } : {}),
293
+ });
294
+ }
295
+ return;
296
+ }
297
+ this.reporting.set(key, request.status);
239
298
  try {
240
- const settlement = await this.collector.collect(request.record);
299
+ const settlement = await this.collector.collect(
300
+ request.record,
301
+ request.status === "blocked" ? "blocked" : undefined,
302
+ );
241
303
  if (!settlement || !lifecycle.isCurrent()) return;
304
+ if (this.pendingBlocked.has(key)) return;
242
305
  const current = this.state.byPane(settlement.agent.pane_id);
243
306
  if (!current || current.terminalId !== request.record.terminalId) return;
244
- if (activityTask(current.activity) !== task) return;
245
- if (activityAttemptId(current.activity) !== retryState.attemptId) return;
307
+ if (
308
+ activityTask(current.activity) !== task ||
309
+ activityAttemptId(current.activity) !== retryState.attemptId
310
+ ) {
311
+ if (request.status !== "blocked") return;
312
+ this.clearRetry(request.record.terminalId, retryState.attemptId);
313
+ this.deliverSettlement(
314
+ lifecycle,
315
+ request.record,
316
+ settlement,
317
+ retryState.attemptId,
318
+ request.blockedMessage,
319
+ undefined,
320
+ );
321
+ return;
322
+ }
246
323
  const retryRequest = task ? { ...request, task } : request;
247
324
  const expectedUser = activityExpectedUser(current.activity);
325
+ const blocked = settlement.status === "blocked";
326
+ // A blocked status is authoritative even when Pi has not persisted the turn.
248
327
  // Pi persists expanded skills/templates, not the submitted command text.
249
328
  if (
329
+ !blocked &&
250
330
  expectedUser &&
251
331
  (settlement.session.assistantAfterUser !== true ||
252
332
  !settlement.session.user ||
@@ -262,10 +342,10 @@ export class SettlementReporter {
262
342
  return;
263
343
  }
264
344
  const newReply =
265
- settlement.reply?.id !== current.lastAssistantId
345
+ !blocked && settlement.reply?.id !== current.lastAssistantId
266
346
  ? settlement.reply
267
347
  : undefined;
268
- if (request.requireNewReply && !newReply && !settlement.ask) {
348
+ if (!blocked && request.requireNewReply && !newReply) {
269
349
  if (!this.retry(lifecycle, retryRequest, retryState)) {
270
350
  this.failReconciliation(
271
351
  lifecycle,
@@ -280,48 +360,52 @@ export class SettlementReporter {
280
360
  ? request.blockedMessage
281
361
  : undefined;
282
362
  const attemptId = activityAttemptId(current.activity);
283
- const claim = attemptId ? this.claims.get(attemptId) : undefined;
284
363
  if (
285
364
  this.state.complete(
286
365
  current.terminalId,
287
366
  settlement.status,
288
367
  task,
289
- settlement.reply?.id,
368
+ newReply?.id,
290
369
  )
291
370
  ) {
292
- this.clearRetry(current.terminalId);
371
+ this.clearRetry(current.terminalId, retryState.attemptId);
293
372
  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
- }
373
+ this.deliverSettlement(
374
+ lifecycle,
375
+ current,
376
+ settlement,
377
+ attemptId,
378
+ blockedMessage,
379
+ newReply,
380
+ );
322
381
  }
323
382
  } catch (error) {
324
383
  if (!lifecycle.isCurrent()) return;
384
+ if (request.status === "blocked") {
385
+ const current = this.state.byTerminal(request.record.terminalId);
386
+ if (current) {
387
+ const currentOwnsAttempt =
388
+ activityTask(current.activity) === task &&
389
+ activityAttemptId(current.activity) === retryState.attemptId;
390
+ this.clearRetry(request.record.terminalId, retryState.attemptId);
391
+ if (
392
+ currentOwnsAttempt &&
393
+ this.state.complete(current.terminalId, "blocked", task)
394
+ ) {
395
+ this.persist();
396
+ }
397
+ this.deliverSettlement(
398
+ lifecycle,
399
+ currentOwnsAttempt ? current : request.record,
400
+ blockedSettlement(current),
401
+ retryState.attemptId,
402
+ request.blockedMessage,
403
+ undefined,
404
+ );
405
+ }
406
+ return;
407
+ }
408
+ if (this.pendingBlocked.has(key)) return;
325
409
  if (retryState.count === 0) {
326
410
  lifecycle.context.ui.notify(
327
411
  `Could not collect ${request.record.name ?? request.record.paneId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -345,13 +429,58 @@ export class SettlementReporter {
345
429
  }
346
430
  } finally {
347
431
  this.reporting.delete(key);
432
+ const pending = this.pendingBlocked.get(key);
433
+ if (pending) {
434
+ this.pendingBlocked.delete(key);
435
+ void this.report(pending.lifecycle, pending.request, pending.retry);
436
+ }
348
437
  }
349
438
  }
350
439
 
351
- private clearRetry(terminalId: string): void {
352
- const retry = this.retries.get(terminalId);
440
+ private deliverSettlement(
441
+ lifecycle: SettlementLifecycle,
442
+ record: MonitoredAgent,
443
+ settlement: CollectedSettlementWithSession,
444
+ attemptId: string | undefined,
445
+ blockedMessage: string | undefined,
446
+ reply: LatestAssistant | undefined,
447
+ ): void {
448
+ const claim = attemptId ? this.claims.get(attemptId) : undefined;
449
+ if (claim && attemptId) {
450
+ this.claims.delete(attemptId);
451
+ claim.cleanup();
452
+ const {
453
+ reply: _latestReply,
454
+ session: _session,
455
+ ...claimedSettlement
456
+ } = settlement;
457
+ claim.resolve({
458
+ ...claimedSettlement,
459
+ record,
460
+ ...(blockedMessage ? { blockedMessage } : {}),
461
+ ...(reply ? { reply } : {}),
462
+ });
463
+ return;
464
+ }
465
+ injectAgentEvent(this.pi, lifecycle.context, {
466
+ agent: settlement.agent,
467
+ agentToolName: "agents",
468
+ ...(settlement.ask ? { ask: settlement.ask } : {}),
469
+ machine: this.machine,
470
+ operatorPrefix: this.operatorPrefix,
471
+ ...(blockedMessage ? { blockedMessage } : {}),
472
+ labels: settlement.labels,
473
+ record,
474
+ ...(reply ? { reply } : {}),
475
+ status: settlement.status,
476
+ });
477
+ }
478
+
479
+ private clearRetry(terminalId: string, attemptId: string | undefined): void {
480
+ const key = attemptKey(terminalId, attemptId);
481
+ const retry = this.retries.get(key);
353
482
  if (retry) clearTimeout(retry);
354
- this.retries.delete(terminalId);
483
+ this.retries.delete(key);
355
484
  }
356
485
 
357
486
  private retry(
@@ -371,19 +500,29 @@ export class SettlementReporter {
371
500
  ) {
372
501
  return false;
373
502
  }
374
- if (this.retries.has(request.record.terminalId)) return true;
503
+ const key = attemptKey(request.record.terminalId, retry.attemptId);
504
+ if (this.retries.has(key)) return true;
375
505
  const timer = setTimeout(() => {
376
- this.retries.delete(request.record.terminalId);
506
+ this.retries.delete(key);
377
507
  if (!lifecycle.isCurrent()) return;
378
508
  const current = this.state.byTerminal(request.record.terminalId);
379
509
  if (!current) return;
510
+ const currentOwnsAttempt =
511
+ activityAttemptId(current.activity) === retry.attemptId &&
512
+ activityTask(current.activity) ===
513
+ (request.task ?? activityTask(request.record.activity));
380
514
  void this.report(
381
515
  lifecycle,
382
- { ...request, record: current },
516
+ {
517
+ ...request,
518
+ record: currentOwnsAttempt
519
+ ? current
520
+ : { ...current, activity: request.record.activity },
521
+ },
383
522
  { ...retry, count: retry.count + 1 },
384
523
  );
385
524
  }, delay);
386
- this.retries.set(request.record.terminalId, timer);
525
+ this.retries.set(key, timer);
387
526
  timer.unref();
388
527
  return true;
389
528
  }
@@ -393,7 +532,8 @@ export class SettlementReporter {
393
532
  record: MonitoredAgent,
394
533
  reason: string,
395
534
  ): void {
396
- this.clearRetry(record.terminalId);
535
+ const attemptId = activityAttemptId(record.activity);
536
+ this.clearRetry(record.terminalId, attemptId);
397
537
  const message =
398
538
  (record.name ?? record.paneId) +
399
539
  " settled, but " +
@@ -401,7 +541,6 @@ export class SettlementReporter {
401
541
  " after " +
402
542
  SETTLEMENT_RETRY_WINDOW_SECONDS +
403
543
  " seconds";
404
- const attemptId = activityAttemptId(record.activity);
405
544
  if (attemptId) this.releaseAttempt(attemptId, new Error(message));
406
545
  lifecycle.context.ui.notify(message, "warning");
407
546
  }
package/src/types.ts CHANGED
@@ -75,9 +75,15 @@ export interface MonitoredAgent {
75
75
 
76
76
  type MachineConnectionStatus = "connected" | "connecting" | "unavailable";
77
77
 
78
+ export interface MonitoringIssue {
79
+ state: "degraded" | "unavailable";
80
+ message: string;
81
+ }
82
+
78
83
  export interface MachineStatus {
79
84
  local: boolean;
80
85
  name: string;
86
+ monitoringIssue?: MonitoringIssue;
81
87
  reason?: string;
82
88
  status: MachineConnectionStatus;
83
89
  }
package/src/widget.ts CHANGED
@@ -35,9 +35,12 @@ 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
45
  const name = `${agent.machine} / ${agent.name ?? agent.paneId}`;
43
46
  const location = agent.cwd ? basename(agent.cwd) : agent.paneId;
@@ -45,7 +48,12 @@ function agentLine(
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
  }
@@ -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.name}`;
101
+ lines.push(
102
+ `${theme.fg("muted", "│")} ${theme.fg("warning", `${machine.name} monitoring ${status} · ${recovery}`)}`,
103
+ );
104
+ }
84
105
  lines.push(theme.fg("muted", "╰─"));
85
106
  ctx.ui.setWidget(WIDGET_ID, lines, { placement: "aboveEditor" });
86
107
  }