@howaboua/pi-shepherdr 0.2.17 → 0.2.19

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.
@@ -0,0 +1,35 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { ExtensionReply } from "./types.js";
3
+
4
+ const EXTENSION_REPLY_EVENT = "@howaboua/pi-shepherdr/extension-reply/v1";
5
+
6
+ /** Producers claim synchronously and resolve only after semantic delivery/persistence. */
7
+ export async function dispatchExtensionReply(
8
+ pi: ExtensionAPI,
9
+ reply: ExtensionReply,
10
+ ): Promise<string> {
11
+ let claimed: Promise<string> | undefined;
12
+ let accepting = true;
13
+ try {
14
+ pi.events.emit(EXTENSION_REPLY_EVENT, {
15
+ ...reply,
16
+ respond(result: Promise<string> | string) {
17
+ if (!accepting || claimed)
18
+ throw new Error("Extension reply already claimed or dispatch ended");
19
+ claimed = Promise.resolve(result);
20
+ },
21
+ });
22
+ } finally {
23
+ accepting = false;
24
+ }
25
+ if (!claimed)
26
+ throw new Error(
27
+ `Reply handler for ${JSON.stringify(reply.extension)} is unavailable; reload that extension in the target session`,
28
+ );
29
+ const result = await claimed;
30
+ if (typeof result !== "string")
31
+ throw new Error(
32
+ "Extension reply handler returned an invalid receipt; inspect the target before retrying",
33
+ );
34
+ return result;
35
+ }
@@ -4,6 +4,7 @@ import { openPeerChannel } from "./remote/shepherdr-channel.mjs";
4
4
  import { requestContext } from "./remote/shepherdr-context.mjs";
5
5
  import {
6
6
  sendPeerCommands,
7
+ sendPeerExtensionReply,
7
8
  sendPeerFocus,
8
9
  sendPeerMessage,
9
10
  } from "./remote/shepherdr-peer.mjs";
@@ -66,6 +67,10 @@ export function isHerdrErrorCode(error: unknown, code: string): boolean {
66
67
  }
67
68
 
68
69
  export interface HerdrConnection {
70
+ replyExtension(
71
+ agent: PaneInfo,
72
+ reply: import("./types.js").ExtensionReply,
73
+ ): Promise<string>;
69
74
  machineIdentity(): Promise<MachineIdentity>;
70
75
  focus(agent: PaneInfo, request: FocusRequest): Promise<unknown>;
71
76
  openFocusChannel(
@@ -91,6 +96,16 @@ export interface HerdrConnection {
91
96
 
92
97
  export class HerdrClient implements HerdrConnection {
93
98
  readonly socketPath: string;
99
+ replyExtension(
100
+ agent: PaneInfo,
101
+ reply: import("./types.js").ExtensionReply,
102
+ ): Promise<string> {
103
+ return sendPeerExtensionReply(
104
+ (method, params) => this.request(method, params),
105
+ agent,
106
+ reply,
107
+ );
108
+ }
94
109
  openFocusChannel(
95
110
  agent: PaneInfo,
96
111
  request: FocusRequest,
package/src/messages.ts CHANGED
@@ -10,14 +10,15 @@ import { activityTask } from "./activity.js";
10
10
  import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
11
11
  import { getCurrentPane, getSnapshot } from "./herdr.js";
12
12
  import type { HerdrConnection } from "./herdr-client.js";
13
+ import { readExtensionMessage } from "./remote/shepherdr-session.mjs";
13
14
  import type {
15
+ ExtensionMessage,
14
16
  FocusRequest,
15
17
  LatestAssistant,
16
18
  MachineStatus,
17
19
  MonitoredAgent,
18
20
  PaneInfo,
19
21
  PeerMessage,
20
- PendingAsk,
21
22
  ScopedMonitoredAgent,
22
23
  SettledAgentStatus,
23
24
  } from "./types.js";
@@ -79,22 +80,24 @@ export function activeAgentsBriefing(
79
80
  agents: ScopedMonitoredAgent[],
80
81
  machines: MachineStatus[],
81
82
  ): string | undefined {
82
- const active = agents.filter((agent) => agent.activity.phase !== "settled");
83
- if (!active.length) return;
83
+ if (!agents.length) return;
84
84
  return [
85
- "Existing agents after context rollover. Do not duplicate their work. Status is last observed; use these machine/target values for updates.",
85
+ "Supervised agents after context rollover. Do not duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
86
86
  JSON.stringify(
87
- active.map((agent) => ({
87
+ agents.map((agent) => ({
88
88
  machine: agent.machine,
89
89
  target: agent.paneId,
90
90
  ...(agent.name ? { name: agent.name } : {}),
91
- status: agent.activity.phase,
91
+ status:
92
+ agent.activity.phase === "settled"
93
+ ? agent.activity.status
94
+ : agent.activity.phase,
92
95
  connection:
93
96
  machines.find((machine) => machine.id === agent.machine)?.status ??
94
97
  "unavailable",
95
98
  ...(agent.cwd ? { cwd: agent.cwd } : {}),
96
- ...(activityTask(agent.activity)
97
- ? { task: activityTask(agent.activity) }
99
+ ...((agent.instructions ?? activityTask(agent.activity))
100
+ ? { instructions: agent.instructions ?? activityTask(agent.activity) }
98
101
  : {}),
99
102
  })),
100
103
  ),
@@ -236,7 +239,8 @@ export async function attributeAgentPrompt(
236
239
  interface AgentEventOptions {
237
240
  agent: PaneInfo;
238
241
  agentToolName: string;
239
- ask?: PendingAsk;
242
+ codeMode?: boolean;
243
+ extensionMessages?: ExtensionMessage[];
240
244
  blockedMessage?: string;
241
245
  labels: AgentEventLabels;
242
246
  machine: string;
@@ -244,20 +248,11 @@ interface AgentEventOptions {
244
248
  operatorPrefix: string;
245
249
  record: MonitoredAgent;
246
250
  reply?: LatestAssistant;
247
- status: SettledAgentStatus | "question";
248
- }
249
-
250
- export function modelAsk(ask: PendingAsk) {
251
- return {
252
- ask_id: ask.toolCallId,
253
- ...(ask.delivery ? { delivery: ask.delivery } : {}),
254
- handoff: ask.handoff,
255
- prompts: ask.prompts,
256
- };
251
+ status: SettledAgentStatus | "extension-message";
257
252
  }
258
253
 
259
254
  interface AgentEventDetails {
260
- ask?: PendingAsk;
255
+ extensionMessages?: ExtensionMessage[];
261
256
  blockedOn?: string;
262
257
  cwd?: string;
263
258
  machine: string;
@@ -265,59 +260,23 @@ interface AgentEventDetails {
265
260
  name?: string;
266
261
  paneId: string;
267
262
  response?: string;
268
- state: "blocked" | "failed" | "finished" | "question";
263
+ state: "blocked" | "failed" | "finished" | "extension-message";
269
264
  tab?: string;
270
265
  task?: string;
271
266
  workspace?: string;
272
267
  }
273
268
 
274
- function eventAsk(value: unknown): PendingAsk | undefined {
275
- if (typeof value !== "object" || value === null) return undefined;
276
- const record = value as Record<string, unknown>;
277
- if (
278
- typeof record["toolCallId"] !== "string" ||
279
- typeof record["handoff"] !== "boolean" ||
280
- !Array.isArray(record["prompts"])
281
- ) {
282
- return undefined;
283
- }
284
- const prompts: PendingAsk["prompts"] = [];
285
- for (const value of record["prompts"]) {
286
- if (typeof value !== "object" || value === null) return undefined;
287
- const prompt = value as Record<string, unknown>;
288
- if (
289
- typeof prompt["title"] !== "string" ||
290
- typeof prompt["multiple"] !== "boolean" ||
291
- !Array.isArray(prompt["choices"])
292
- ) {
293
- return undefined;
294
- }
295
- const choices: PendingAsk["prompts"][number]["choices"] = [];
296
- for (const value of prompt["choices"]) {
297
- if (typeof value !== "object" || value === null) return undefined;
298
- const choice = value as Record<string, unknown>;
299
- if (typeof choice["label"] !== "string") return undefined;
300
- choices.push({
301
- label: choice["label"],
302
- ...(typeof choice["description"] === "string"
303
- ? { description: choice["description"] }
304
- : {}),
305
- });
306
- }
307
- prompts.push({
308
- title: prompt["title"],
309
- multiple: prompt["multiple"],
310
- choices,
311
- ...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
312
- });
313
- }
314
- if (prompts.length === 0) return undefined;
315
- return {
316
- toolCallId: record["toolCallId"],
317
- ...(record["delivery"] === "steer" ? { delivery: "steer" as const } : {}),
318
- handoff: record["handoff"],
319
- prompts,
320
- };
269
+ function eventExtensionMessages(
270
+ value: unknown,
271
+ ): ExtensionMessage[] | undefined {
272
+ if (!Array.isArray(value)) return undefined;
273
+ const messages = value.map((message) => {
274
+ if (typeof message !== "object" || message === null) return undefined;
275
+ return readExtensionMessage({ ...message, version: 1, state: "pending" });
276
+ });
277
+ return messages.every((message) => message !== undefined)
278
+ ? messages
279
+ : undefined;
321
280
  }
322
281
 
323
282
  function boundedVoicePrompt(prompt: string): string {
@@ -337,18 +296,17 @@ function agentVoicePrompt(details: AgentEventDetails): string {
337
296
  ];
338
297
  if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
339
298
  let instruction: string;
340
- if (details.state === "blocked" || details.state === "question") {
299
+ if (details.state === "blocked" || details.state === "extension-message") {
341
300
  instruction =
342
- details.state === "question"
343
- ? "Briefly tell the user what this worker asks while it continues working."
301
+ details.state === "extension-message"
302
+ ? "Briefly tell the user what this worker reports."
344
303
  : "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
345
304
  if (details.blockedOn?.trim())
346
305
  lines.push(`Reason:\n${details.blockedOn.trim()}`);
347
- if (details.ask) {
306
+ if (details.extensionMessages)
348
307
  lines.push(
349
- `Questions:\n${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
308
+ ...details.extensionMessages.map((message) => message.message),
350
309
  );
351
- }
352
310
  } else {
353
311
  instruction =
354
312
  details.state === "failed"
@@ -423,7 +381,7 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
423
381
  (details["machine"] !== undefined &&
424
382
  typeof details["machine"] !== "string") ||
425
383
  (details["state"] !== "blocked" &&
426
- details["state"] !== "question" &&
384
+ details["state"] !== "extension-message" &&
427
385
  details["state"] !== "failed" &&
428
386
  details["state"] !== "finished")
429
387
  ) {
@@ -433,13 +391,15 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
433
391
  typeof details[field] === "string"
434
392
  ? { [field]: details[field] as string }
435
393
  : {};
436
- const ask = eventAsk(details["ask"]);
394
+ const extensionMessages = eventExtensionMessages(
395
+ details["extensionMessages"],
396
+ );
437
397
  return {
438
398
  machine:
439
399
  typeof details["machine"] === "string" ? details["machine"] : "local",
440
400
  paneId: details["paneId"],
441
401
  state: details["state"],
442
- ...(ask ? { ask } : {}),
402
+ ...(extensionMessages ? { extensionMessages } : {}),
443
403
  ...optional("blockedOn"),
444
404
  ...optional("cwd"),
445
405
  ...optional("machineLabel"),
@@ -458,7 +418,8 @@ function agentEvent(options: AgentEventOptions): {
458
418
  const {
459
419
  agent,
460
420
  agentToolName,
461
- ask,
421
+ codeMode,
422
+ extensionMessages,
462
423
  blockedMessage,
463
424
  labels,
464
425
  machine,
@@ -470,11 +431,11 @@ function agentEvent(options: AgentEventOptions): {
470
431
  } = options;
471
432
  const task = activityTask(record.activity);
472
433
  const blocked = status === "blocked";
473
- const question = status === "question";
434
+ const notification = status === "extension-message";
474
435
  const failed = !blocked && reply?.stopReason === "error";
475
436
  const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
476
- const tag = question
477
- ? "herdr_agent_question"
437
+ const tag = notification
438
+ ? "herdr_agent_extension_message"
478
439
  : blocked
479
440
  ? "herdr_agent_blocked"
480
441
  : failed
@@ -488,23 +449,32 @@ function agentEvent(options: AgentEventOptions): {
488
449
  directory: cwd,
489
450
  });
490
451
  const lines = [`<${tag} ${attributes}>`];
491
- if (task) lines.push(`<task>${xml(task)}</task>`);
452
+ if (task && !notification) lines.push(`<task>${xml(task)}</task>`);
492
453
  if (blockedMessage) {
493
454
  lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
494
455
  }
495
- if ((blocked || question) && ask) {
496
- lines.push(`<ask>${xml(JSON.stringify(modelAsk(ask)))}</ask>`);
456
+ for (const message of extensionMessages ?? []) {
457
+ lines.push(message.message);
458
+ if (message.reply !== undefined) {
459
+ const request = {
460
+ action: "reply",
461
+ machine,
462
+ target: agent.pane_id,
463
+ extension: message.extension,
464
+ id: message.id,
465
+ message: message.reply,
466
+ };
467
+ const call = codeMode
468
+ ? `await tools.${agentToolName}(${JSON.stringify(request)})`
469
+ : `${agentToolName} ${JSON.stringify(request)}`;
470
+ lines.push(`Reply: ${call}`);
471
+ }
497
472
  }
498
473
  if (blocked) {
499
474
  lines.push(
500
475
  `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
501
476
  );
502
477
  }
503
- if (question && ask) {
504
- lines.push(
505
- `<operator_hint>${xml(`Worker continues. Answer via ${agentToolName} action=answer machine=${JSON.stringify(machine)} target=${JSON.stringify(agent.pane_id)} ask_id=${JSON.stringify(ask.toolCallId)} answers=[...]`)}</operator_hint>`,
506
- );
507
- }
508
478
  if (failed) {
509
479
  lines.push(
510
480
  `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
@@ -519,19 +489,19 @@ function agentEvent(options: AgentEventOptions): {
519
489
  machine,
520
490
  machineLabel,
521
491
  paneId: agent.pane_id,
522
- state: question
523
- ? "question"
492
+ state: notification
493
+ ? "extension-message"
524
494
  : blocked
525
495
  ? "blocked"
526
496
  : failed
527
497
  ? "failed"
528
498
  : "finished",
529
- ...((blocked || question) && ask ? { ask } : {}),
499
+ ...(extensionMessages ? { extensionMessages } : {}),
530
500
  ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
531
501
  ...(cwd ? { cwd } : {}),
532
502
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
533
503
  ...(labels.tab ? { tab: labels.tab } : {}),
534
- ...(task ? { task } : {}),
504
+ ...(task && !notification ? { task } : {}),
535
505
  ...(blockedMessage ? { blockedOn: blockedMessage } : {}),
536
506
  ...(reply ? { response: reply.text } : {}),
537
507
  },
@@ -543,7 +513,14 @@ export function injectAgentEvent(
543
513
  ctx: ExtensionContext,
544
514
  options: AgentEventOptions,
545
515
  ): void {
546
- const message = agentEvent(options);
516
+ const tools = pi.getActiveTools();
517
+ const message = agentEvent({
518
+ ...options,
519
+ codeMode:
520
+ tools.includes("exec") ||
521
+ tools.includes("code") ||
522
+ tools.includes("notebook"),
523
+ });
547
524
  const idle = ctx.isIdle();
548
525
  const delivery = idle
549
526
  ? { triggerTurn: false, deliverAs: "nextTurn" as const }
@@ -588,14 +565,14 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
588
565
  }
589
566
  const blocked = details?.state === "blocked";
590
567
  const failed = details?.state === "failed";
591
- const question = details.state === "question";
568
+ const notification = details.state === "extension-message";
592
569
  const agentIdentity = details?.name
593
570
  ? `${details.name} (${details.paneId})`
594
571
  : (details?.paneId ?? "unknown");
595
572
  const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
596
573
  const title = theme.fg(
597
574
  blocked || failed ? "error" : "success",
598
- `Herdr agent ${identity} · ${question ? "question pending, worker continues" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
575
+ `Herdr agent ${identity} · ${notification ? "extension message pending" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
599
576
  );
600
577
  const location = [details?.workspace, details?.tab]
601
578
  .filter(Boolean)
@@ -606,51 +583,27 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
606
583
  );
607
584
  box.addChild(new Text(title, 0, 0));
608
585
  if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
609
- if (blocked || question) {
586
+ if (blocked || notification) {
610
587
  box.addChild(new Spacer(1));
611
588
  box.addChild(
612
589
  new Text(
613
590
  theme.fg(
614
591
  "warning",
615
592
  details?.blockedOn ??
616
- (question
617
- ? "Question pending"
593
+ (notification
594
+ ? "Extension message pending"
618
595
  : "Agent needs input or approval"),
619
596
  ),
620
597
  0,
621
598
  0,
622
599
  ),
623
600
  );
624
- if (details.ask) {
625
- box.addChild(
626
- new Text(
627
- theme.fg(
628
- "muted",
629
- `Questions: ${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
630
- ),
631
- 0,
632
- 0,
633
- ),
634
- );
635
- if (expanded) {
636
- for (const prompt of details.ask.prompts) {
637
- box.addChild(new Spacer(1));
638
- box.addChild(new Text(theme.fg("muted", prompt.title), 0, 0));
639
- if (prompt.body) {
640
- box.addChild(
641
- new Markdown(prompt.body, 0, 0, getMarkdownTheme()),
642
- );
643
- }
644
- if (prompt.choices.length > 0) {
645
- box.addChild(
646
- new Text(
647
- `Choices: ${prompt.choices.map((choice) => choice.label).join(", ")}`,
648
- 0,
649
- 0,
650
- ),
651
- );
652
- }
653
- }
601
+ if (details.extensionMessages && expanded) {
602
+ for (const message of details.extensionMessages) {
603
+ box.addChild(new Spacer(1));
604
+ box.addChild(
605
+ new Markdown(message.message, 0, 0, getMarkdownTheme()),
606
+ );
654
607
  }
655
608
  }
656
609
  }
@@ -1,19 +1,13 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { sameAgentIdentity } from "./ask-answer.js";
2
+ import { sameAgentIdentity } from "./agent-identity.js";
3
3
  import { getAgent, sessionPath } from "./herdr.js";
4
4
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
5
5
  import type { MonitorState } from "./monitor-state.js";
6
+ import { extensionMessageKey } from "./remote/shepherdr-session.mjs";
6
7
  import type { AssistantReader } from "./session-reader.js";
7
- import type {
8
- AskResult,
9
- MonitoredAgent,
10
- PaneInfo,
11
- PendingAsk,
12
- } from "./types.js";
8
+ import type { ExtensionMessage, MonitoredAgent, PaneInfo } from "./types.js";
13
9
 
14
- const ASK_RESULT_TIMEOUT_MS = 10_000;
15
-
16
- interface MonitorQuestionsOptions {
10
+ interface MonitorExtensionMessagesOptions {
17
11
  client: HerdrConnection;
18
12
  reader: AssistantReader;
19
13
  state: MonitorState;
@@ -21,13 +15,13 @@ interface MonitorQuestionsOptions {
21
15
  ctx: ExtensionContext,
22
16
  record: MonitoredAgent,
23
17
  panel: PaneInfo,
24
- ask: PendingAsk,
18
+ message: ExtensionMessage,
25
19
  ) => void;
26
20
  persist: () => void;
27
21
  }
28
22
 
29
- // Questions are attention events, not settlements of delegated work.
30
- export class MonitorQuestions {
23
+ // Extension messages are attention events, not settlements of delegated work.
24
+ export class MonitorExtensionMessages {
31
25
  private context: ExtensionContext | undefined;
32
26
  private generation = 0;
33
27
  private panels: PaneInfo[] = [];
@@ -36,11 +30,11 @@ export class MonitorQuestions {
36
30
  private unsubscribe: (() => void) | undefined;
37
31
  private refreshTail = Promise.resolve();
38
32
  private readonly checks = new Map<string, { dirty: boolean }>();
39
- private readonly answers = new Set<AbortController>();
33
+
40
34
  private warned = false;
41
- private readonly options: MonitorQuestionsOptions;
35
+ private readonly options: MonitorExtensionMessagesOptions;
42
36
 
43
- constructor(options: MonitorQuestionsOptions) {
37
+ constructor(options: MonitorExtensionMessagesOptions) {
44
38
  this.options = options;
45
39
  }
46
40
 
@@ -51,7 +45,6 @@ export class MonitorQuestions {
51
45
 
52
46
  stop(): void {
53
47
  this.generation++;
54
- for (const controller of this.answers) controller.abort();
55
48
  this.context = undefined;
56
49
  this.panels = [];
57
50
  this.key = "";
@@ -64,86 +57,6 @@ export class MonitorQuestions {
64
57
  this.refreshTail = Promise.resolve();
65
58
  }
66
59
 
67
- submitAnswer(
68
- panel: PaneInfo,
69
- askId: string,
70
- submit: (signal: AbortSignal) => Promise<void>,
71
- signal: AbortSignal,
72
- ): Promise<AskResult | undefined> {
73
- signal.throwIfAborted();
74
- const path = sessionPath(panel);
75
- if (!path) return Promise.resolve(undefined);
76
- const controller = new AbortController();
77
- this.answers.add(controller);
78
- return new Promise((resolve, reject) => {
79
- let closed = false;
80
- let unsubscribe: (() => void) | undefined;
81
- let submitted = false;
82
- let checking = false;
83
- let dirty = false;
84
- const finish = (result?: AskResult, error?: unknown) => {
85
- if (closed) return;
86
- closed = true;
87
- clearTimeout(timer);
88
- signal.removeEventListener("abort", cancel);
89
- controller.signal.removeEventListener("abort", stopped);
90
- controller.abort();
91
- unsubscribe?.();
92
- this.answers.delete(controller);
93
- if (error !== undefined) reject(error);
94
- else resolve(result);
95
- };
96
- const cancel = () => finish(undefined, signal.reason);
97
- const stopped = () => finish(undefined, controller.signal.reason);
98
- const timer = setTimeout(() => finish(), ASK_RESULT_TIMEOUT_MS);
99
- signal.addEventListener("abort", cancel, { once: true });
100
- controller.signal.addEventListener("abort", stopped, { once: true });
101
- const check = () => {
102
- dirty = true;
103
- if (closed || !submitted || checking) return;
104
- checking = true;
105
- void (async () => {
106
- while (dirty && !closed) {
107
- dirty = false;
108
- const current = await getAgent(this.options.client, panel.pane_id);
109
- if (closed) return;
110
- if (!sameAgentIdentity(panel, current)) return finish();
111
- const view = await this.options.reader.view(path);
112
- if (closed) return;
113
- // Identity may change while the session read is in flight.
114
- const after = await getAgent(this.options.client, panel.pane_id);
115
- if (closed) return;
116
- if (!sameAgentIdentity(panel, after)) return finish();
117
- // Ask can leave the UI before its close record is persisted.
118
- const result = view.askResults?.[askId];
119
- if (result) return finish(result);
120
- }
121
- })()
122
- .catch((error) => finish(undefined, error))
123
- .finally(() => {
124
- checking = false;
125
- if (dirty && !closed) check();
126
- });
127
- };
128
- void (async () => {
129
- // The reader belongs to this machine. Cover persistence before Enter.
130
- const close = await this.options.reader.watch(
131
- [path],
132
- check,
133
- (error) => finish(undefined, error),
134
- controller.signal,
135
- );
136
- if (closed) return close();
137
- unsubscribe = close;
138
- await submit(controller.signal);
139
- if (closed) return;
140
- submitted = true;
141
- // Read after subscription and submit ACK even if no event was observed.
142
- check();
143
- })().catch((error) => finish(undefined, error));
144
- });
145
- }
146
-
147
60
  refresh(panels: PaneInfo[] = this.panels): Promise<void> {
148
61
  this.panels = panels.filter(
149
62
  (panel) =>
@@ -222,20 +135,33 @@ export class MonitorQuestions {
222
135
  if (!sameAgentIdentity(panel, current)) continue;
223
136
  const view = await this.options.reader.view(path);
224
137
  if (generation !== this.generation || !this.context) return;
138
+ const after = await getAgent(
139
+ this.options.client,
140
+ panel.pane_id,
141
+ ).catch((error: unknown) => {
142
+ if (isHerdrErrorCode(error, "agent_not_found")) return undefined;
143
+ throw error;
144
+ });
145
+ if (generation !== this.generation || !this.context) return;
146
+ if (!after || !sameAgentIdentity(panel, after)) continue;
225
147
  const record = this.options.state.byTerminal(current.terminal_id);
226
- const ask = view.ask;
227
- if (
228
- !record ||
229
- record.paneId !== current.pane_id ||
230
- ask?.delivery !== "steer" ||
231
- record.lastQuestionId === ask.toolCallId
232
- )
233
- continue;
234
- this.options.notify(this.context, record, current, ask);
235
- if (
236
- this.options.state.markQuestion(record.terminalId, ask.toolCallId)
237
- )
238
- this.options.persist();
148
+ if (!record || record.paneId !== current.pane_id) continue;
149
+ const messages = view.extensionMessages ?? [];
150
+ let changed = this.options.state.retainExtensionNotifications(
151
+ record.terminalId,
152
+ messages.map(extensionMessageKey),
153
+ );
154
+ for (const message of messages) {
155
+ // Blocking messages arrive with the worker's settlement.
156
+ if (message.blocking) continue;
157
+ const key = extensionMessageKey(message);
158
+ if (record.notifiedExtensionMessages?.includes(key)) continue;
159
+ this.options.notify(this.context, record, current, message);
160
+ changed =
161
+ this.options.state.markExtensionMessage(record.terminalId, key) ||
162
+ changed;
163
+ }
164
+ if (changed) this.options.persist();
239
165
  }
240
166
  }
241
167
  })()
@@ -251,7 +177,7 @@ export class MonitorQuestions {
251
177
  if (this.warned) return;
252
178
  this.warned = true;
253
179
  this.context?.ui.notify(
254
- `Async question monitoring unavailable: ${error instanceof Error ? error.message : String(error)}. Use agents read to inspect workers; reconnect through /herdr`,
180
+ `Worker extension notifications unavailable: ${error instanceof Error ? error.message : String(error)}. Use agents read to inspect workers; reconnect through /herdr`,
255
181
  "warning",
256
182
  );
257
183
  }