@howaboua/pi-shepherdr 0.2.13 → 0.2.15

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/messages.ts CHANGED
@@ -12,19 +12,103 @@ import { getCurrentPane, getSnapshot } from "./herdr.js";
12
12
  import type { HerdrConnection } from "./herdr-client.js";
13
13
  import type {
14
14
  LatestAssistant,
15
+ MachineStatus,
15
16
  MonitoredAgent,
16
17
  PaneInfo,
17
18
  PeerMessage,
18
19
  PendingAsk,
20
+ ScopedMonitoredAgent,
19
21
  SettledAgentStatus,
20
22
  } from "./types.js";
21
23
 
22
24
  const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
25
+ const BOARD_POST_MARKER = "shepherdr-board-post-marker";
26
+
27
+ export function recordBoardPostMarker(
28
+ pi: ExtensionAPI,
29
+ ctx: ExtensionContext,
30
+ value: unknown,
31
+ ): void {
32
+ if (
33
+ !value ||
34
+ typeof value !== "object" ||
35
+ !("message_id" in value) ||
36
+ typeof value.message_id !== "string" ||
37
+ !("channel_name" in value) ||
38
+ typeof value.channel_name !== "string"
39
+ )
40
+ return;
41
+ if (
42
+ ctx.sessionManager
43
+ .getBranch()
44
+ .some(
45
+ (entry) =>
46
+ entry.type === "custom" &&
47
+ entry.customType === BOARD_POST_MARKER &&
48
+ entry.data &&
49
+ typeof entry.data === "object" &&
50
+ "messageId" in entry.data &&
51
+ entry.data.messageId === value.message_id,
52
+ )
53
+ )
54
+ return;
55
+ // Owner acknowledgements reach the sender here, never the subscription inbox.
56
+ pi.appendEntry(BOARD_POST_MARKER, {
57
+ messageId: value.message_id,
58
+ channelName: value.channel_name,
59
+ });
60
+ }
23
61
  const REALTIME_VOICE_PROMPT_CHANNEL =
24
62
  "@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
25
63
  const MAX_REALTIME_VOICE_PROMPT_BYTES = 8 * 1_024;
26
64
  const DELEGATED_WORKER_GUIDANCE =
27
65
  "If blocked mid-run, use a question-asking tool, not peer messages. Without one, end with the blocker. Finish with an assistant reply, not a separate send report; never watch your parent.";
66
+ export function orchestrationGuidance(enabled: boolean, general: boolean) {
67
+ if (!enabled) return "Work normally. Delegate only when useful or requested.";
68
+ return general
69
+ ? "Your main goal from now on is to orchestrate agents. Fan out suitable work to general agents, synthesize their results, and report the outcome. Work directly only when asked or for routine local tasks."
70
+ : "Your main goal from now on is to orchestrate agents. Fan out suitable work, synthesize agent results, and report the outcome. Work directly only when asked or for routine local tasks.";
71
+ }
72
+ export function activeAgentsBriefing(
73
+ agents: ScopedMonitoredAgent[],
74
+ machines: MachineStatus[],
75
+ ): string | undefined {
76
+ const active = agents.filter((agent) => agent.activity.phase !== "settled");
77
+ if (!active.length) return;
78
+ return [
79
+ "Existing agents after context rollover. Do not duplicate their work. Status is last observed; use these machine/target values for updates.",
80
+ JSON.stringify(
81
+ active.map((agent) => ({
82
+ machine: agent.machine,
83
+ target: agent.paneId,
84
+ ...(agent.name ? { name: agent.name } : {}),
85
+ status: agent.activity.phase,
86
+ connection:
87
+ machines.find((machine) => machine.id === agent.machine)?.status ??
88
+ "unavailable",
89
+ ...(agent.cwd ? { cwd: agent.cwd } : {}),
90
+ ...(activityTask(agent.activity)
91
+ ? { task: activityTask(agent.activity) }
92
+ : {}),
93
+ })),
94
+ ),
95
+ ].join("\n");
96
+ }
97
+ export function boardBriefing(
98
+ member: boolean,
99
+ population: "empty" | "populated" | "unavailable",
100
+ ) {
101
+ const state =
102
+ population === "populated"
103
+ ? "Your shared board has posts. Read relevant threads and contribute useful plans, decisions and findings."
104
+ : population === "empty"
105
+ ? "Shared board available; no posts yet."
106
+ : "Shared board status unavailable. Check board help and retry reading when available.";
107
+ const setup = member
108
+ ? "The root agent owns setup; follow your assigned task."
109
+ : "You own setup. Before delegating, consider posting shared context if useful.";
110
+ return `${state} ${setup} Use agents for assignments and urgent messages.`;
111
+ }
28
112
 
29
113
  export function attachmentMessage(
30
114
  controllerContextAgent?: string,
@@ -141,12 +225,13 @@ interface AgentEventOptions {
141
225
  operatorPrefix: string;
142
226
  record: MonitoredAgent;
143
227
  reply?: LatestAssistant;
144
- status: SettledAgentStatus;
228
+ status: SettledAgentStatus | "question";
145
229
  }
146
230
 
147
231
  export function modelAsk(ask: PendingAsk) {
148
232
  return {
149
233
  ask_id: ask.toolCallId,
234
+ ...(ask.delivery ? { delivery: ask.delivery } : {}),
150
235
  handoff: ask.handoff,
151
236
  prompts: ask.prompts,
152
237
  };
@@ -161,7 +246,7 @@ interface AgentEventDetails {
161
246
  name?: string;
162
247
  paneId: string;
163
248
  response?: string;
164
- state: "blocked" | "failed" | "finished";
249
+ state: "blocked" | "failed" | "finished" | "question";
165
250
  tab?: string;
166
251
  task?: string;
167
252
  workspace?: string;
@@ -210,6 +295,7 @@ function eventAsk(value: unknown): PendingAsk | undefined {
210
295
  if (prompts.length === 0) return undefined;
211
296
  return {
212
297
  toolCallId: record["toolCallId"],
298
+ ...(record["delivery"] === "steer" ? { delivery: "steer" as const } : {}),
213
299
  handoff: record["handoff"],
214
300
  prompts,
215
301
  };
@@ -232,9 +318,11 @@ function agentVoicePrompt(details: AgentEventDetails): string {
232
318
  ];
233
319
  if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
234
320
  let instruction: string;
235
- if (details.state === "blocked") {
321
+ if (details.state === "blocked" || details.state === "question") {
236
322
  instruction =
237
- "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
323
+ details.state === "question"
324
+ ? "Briefly tell the user what this worker asks while it continues working."
325
+ : "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
238
326
  if (details.blockedOn?.trim())
239
327
  lines.push(`Reason:\n${details.blockedOn.trim()}`);
240
328
  if (details.ask) {
@@ -316,6 +404,7 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
316
404
  (details["machine"] !== undefined &&
317
405
  typeof details["machine"] !== "string") ||
318
406
  (details["state"] !== "blocked" &&
407
+ details["state"] !== "question" &&
319
408
  details["state"] !== "failed" &&
320
409
  details["state"] !== "finished")
321
410
  ) {
@@ -362,13 +451,16 @@ function agentEvent(options: AgentEventOptions): {
362
451
  } = options;
363
452
  const task = activityTask(record.activity);
364
453
  const blocked = status === "blocked";
454
+ const question = status === "question";
365
455
  const failed = !blocked && reply?.stopReason === "error";
366
456
  const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
367
- const tag = blocked
368
- ? "herdr_agent_blocked"
369
- : failed
370
- ? "herdr_agent_failed"
371
- : "herdr_agent_result";
457
+ const tag = question
458
+ ? "herdr_agent_question"
459
+ : blocked
460
+ ? "herdr_agent_blocked"
461
+ : failed
462
+ ? "herdr_agent_failed"
463
+ : "herdr_agent_result";
372
464
  const attributes = sourceAttributes({
373
465
  machine,
374
466
  machine_name: machineLabel !== machine ? machineLabel : undefined,
@@ -381,7 +473,7 @@ function agentEvent(options: AgentEventOptions): {
381
473
  if (blockedMessage) {
382
474
  lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
383
475
  }
384
- if (blocked && ask) {
476
+ if ((blocked || question) && ask) {
385
477
  lines.push(`<ask>${xml(JSON.stringify(modelAsk(ask)))}</ask>`);
386
478
  }
387
479
  if (blocked) {
@@ -389,6 +481,11 @@ function agentEvent(options: AgentEventOptions): {
389
481
  `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
390
482
  );
391
483
  }
484
+ if (question && ask) {
485
+ lines.push(
486
+ `<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>`,
487
+ );
488
+ }
392
489
  if (failed) {
393
490
  lines.push(
394
491
  `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
@@ -403,8 +500,14 @@ function agentEvent(options: AgentEventOptions): {
403
500
  machine,
404
501
  machineLabel,
405
502
  paneId: agent.pane_id,
406
- state: blocked ? "blocked" : failed ? "failed" : "finished",
407
- ...(blocked && ask ? { ask } : {}),
503
+ state: question
504
+ ? "question"
505
+ : blocked
506
+ ? "blocked"
507
+ : failed
508
+ ? "failed"
509
+ : "finished",
510
+ ...((blocked || question) && ask ? { ask } : {}),
408
511
  ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
409
512
  ...(cwd ? { cwd } : {}),
410
513
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
@@ -445,6 +548,25 @@ export function injectAgentEvent(
445
548
  }
446
549
 
447
550
  export function registerAgentEventRenderer(pi: ExtensionAPI): void {
551
+ pi.registerEntryRenderer(BOARD_POST_MARKER, (entry, _options, theme) => {
552
+ const data = entry.data;
553
+ const name =
554
+ data &&
555
+ typeof data === "object" &&
556
+ "channelName" in data &&
557
+ typeof data.channelName === "string" &&
558
+ data.channelName.trim()
559
+ ? data.channelName.replace(/[\r\n\t\x00-\x1f\x7f]/g, " ")
560
+ : "Board";
561
+ return new Text(
562
+ theme.style(`Posted to board · ${name}`, {
563
+ fg: "syntaxString",
564
+ dim: true,
565
+ }),
566
+ 0,
567
+ 0,
568
+ );
569
+ });
448
570
  pi.registerMessageRenderer<AgentEventDetails>(
449
571
  AGENT_EVENT_MESSAGE_TYPE,
450
572
  (message, { expanded, outputPad }, theme) => {
@@ -466,13 +588,14 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
466
588
  }
467
589
  const blocked = details?.state === "blocked";
468
590
  const failed = details?.state === "failed";
591
+ const question = details.state === "question";
469
592
  const agentIdentity = details?.name
470
593
  ? `${details.name} (${details.paneId})`
471
594
  : (details?.paneId ?? "unknown");
472
595
  const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
473
596
  const title = theme.fg(
474
597
  blocked || failed ? "error" : "success",
475
- `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
598
+ `Herdr agent ${identity} · ${question ? "question pending, worker continues" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
476
599
  );
477
600
  const location = [details?.workspace, details?.tab]
478
601
  .filter(Boolean)
@@ -483,13 +606,16 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
483
606
  );
484
607
  box.addChild(new Text(title, 0, 0));
485
608
  if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
486
- if (blocked) {
609
+ if (blocked || question) {
487
610
  box.addChild(new Spacer(1));
488
611
  box.addChild(
489
612
  new Text(
490
613
  theme.fg(
491
614
  "warning",
492
- details?.blockedOn ?? "Agent needs input or approval",
615
+ details?.blockedOn ??
616
+ (question
617
+ ? "Question pending"
618
+ : "Agent needs input or approval"),
493
619
  ),
494
620
  0,
495
621
  0,
@@ -0,0 +1,249 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { sameAgentIdentity } from "./ask-answer.js";
3
+ import { getAgent, sessionPath } from "./herdr.js";
4
+ import type { HerdrConnection } from "./herdr-client.js";
5
+ import type { MonitorState } from "./monitor-state.js";
6
+ import type { AssistantReader } from "./session-reader.js";
7
+ import type {
8
+ AskResult,
9
+ MonitoredAgent,
10
+ PaneInfo,
11
+ PendingAsk,
12
+ } from "./types.js";
13
+
14
+ const ASK_RESULT_TIMEOUT_MS = 10_000;
15
+
16
+ interface MonitorQuestionsOptions {
17
+ client: HerdrConnection;
18
+ reader: AssistantReader;
19
+ state: MonitorState;
20
+ notify: (
21
+ ctx: ExtensionContext,
22
+ record: MonitoredAgent,
23
+ panel: PaneInfo,
24
+ ask: PendingAsk,
25
+ ) => void;
26
+ persist: () => void;
27
+ }
28
+
29
+ // Questions are attention events, not settlements of delegated work.
30
+ export class MonitorQuestions {
31
+ private context: ExtensionContext | undefined;
32
+ private generation = 0;
33
+ private panels: PaneInfo[] = [];
34
+ private key = "";
35
+ private controller: AbortController | undefined;
36
+ private unsubscribe: (() => void) | undefined;
37
+ private refreshTail = Promise.resolve();
38
+ private readonly checks = new Map<string, { dirty: boolean }>();
39
+ private readonly answers = new Set<AbortController>();
40
+ private warned = false;
41
+ private readonly options: MonitorQuestionsOptions;
42
+
43
+ constructor(options: MonitorQuestionsOptions) {
44
+ this.options = options;
45
+ }
46
+
47
+ start(ctx: ExtensionContext): void {
48
+ this.stop();
49
+ this.context = ctx;
50
+ }
51
+
52
+ stop(): void {
53
+ this.generation++;
54
+ for (const controller of this.answers) controller.abort();
55
+ this.context = undefined;
56
+ this.panels = [];
57
+ this.key = "";
58
+ this.controller?.abort();
59
+ this.unsubscribe?.();
60
+ this.unsubscribe = undefined;
61
+ this.controller = undefined;
62
+ this.checks.clear();
63
+ this.warned = false;
64
+ this.refreshTail = Promise.resolve();
65
+ }
66
+
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
+ refresh(panels: PaneInfo[]): Promise<void> {
148
+ this.panels = panels.filter(
149
+ (panel) =>
150
+ this.options.state.byTerminal(panel.terminal_id) && sessionPath(panel),
151
+ );
152
+ const generation = this.generation;
153
+ const update = async () => {
154
+ if (!this.context || generation !== this.generation) return;
155
+ const paths = [
156
+ ...new Set(this.panels.map((panel) => sessionPath(panel)!)),
157
+ ].sort();
158
+ const key = JSON.stringify(paths);
159
+ if (key !== this.key) {
160
+ this.controller?.abort();
161
+ this.unsubscribe?.();
162
+ this.unsubscribe = undefined;
163
+ this.key = "";
164
+ const controller = new AbortController();
165
+ this.controller = controller;
166
+ if (paths.length) {
167
+ const close = await this.options.reader.watch(
168
+ paths,
169
+ (path) => {
170
+ if (!controller.signal.aborted) this.check(path);
171
+ },
172
+ (error) => {
173
+ if (controller.signal.aborted) return;
174
+ controller.abort();
175
+ this.key = "";
176
+ this.warning(error);
177
+ },
178
+ controller.signal,
179
+ );
180
+ if (generation !== this.generation || controller.signal.aborted) {
181
+ close();
182
+ return;
183
+ }
184
+ this.unsubscribe = close;
185
+ }
186
+ this.key = key;
187
+ }
188
+ // Subscribe before reading to cover changes during setup and restoration.
189
+ for (const path of paths) this.check(path);
190
+ };
191
+ this.refreshTail = this.refreshTail.then(update, update).catch((error) => {
192
+ if (generation === this.generation) this.warning(error);
193
+ });
194
+ return this.refreshTail;
195
+ }
196
+
197
+ private check(path: string): void {
198
+ const existing = this.checks.get(path);
199
+ if (existing) {
200
+ existing.dirty = true;
201
+ return;
202
+ }
203
+ const check = { dirty: true };
204
+ this.checks.set(path, check);
205
+ const generation = this.generation;
206
+ void (async () => {
207
+ while (check.dirty && generation === this.generation && this.context) {
208
+ check.dirty = false;
209
+ for (const panel of this.panels.filter(
210
+ (panel) => sessionPath(panel) === path,
211
+ )) {
212
+ const current = await getAgent(this.options.client, panel.pane_id);
213
+ if (!sameAgentIdentity(panel, current)) continue;
214
+ const view = await this.options.reader.view(path);
215
+ if (generation !== this.generation || !this.context) return;
216
+ const record = this.options.state.byTerminal(current.terminal_id);
217
+ const ask = view.ask;
218
+ if (
219
+ !record ||
220
+ record.paneId !== current.pane_id ||
221
+ ask?.delivery !== "steer" ||
222
+ record.lastQuestionId === ask.toolCallId
223
+ )
224
+ continue;
225
+ this.options.notify(this.context, record, current, ask);
226
+ if (
227
+ this.options.state.markQuestion(record.terminalId, ask.toolCallId)
228
+ )
229
+ this.options.persist();
230
+ }
231
+ }
232
+ })()
233
+ .catch((error) => {
234
+ if (generation === this.generation) this.warning(error);
235
+ })
236
+ .finally(() => {
237
+ if (this.checks.get(path) === check) this.checks.delete(path);
238
+ });
239
+ }
240
+
241
+ private warning(error: unknown): void {
242
+ if (this.warned) return;
243
+ this.warned = true;
244
+ this.context?.ui.notify(
245
+ `Async question monitoring unavailable: ${error instanceof Error ? error.message : String(error)}. Use agents read to inspect workers; reconnect through /herdr`,
246
+ "warning",
247
+ );
248
+ }
249
+ }
@@ -104,11 +104,13 @@ export function parseMonitoredAgent(
104
104
  }
105
105
  const cwd = optionalString(record, "cwd");
106
106
  const lastAssistantId = optionalString(record, "lastAssistantId");
107
+ const lastQuestionId = optionalString(record, "lastQuestionId");
107
108
  const name = optionalString(record, "name");
108
109
  const activity = parsedActivity(record["activity"]);
109
110
  if (
110
111
  cwd === false ||
111
112
  lastAssistantId === false ||
113
+ lastQuestionId === false ||
112
114
  name === false ||
113
115
  !activity
114
116
  ) {
@@ -123,6 +125,7 @@ export function parseMonitoredAgent(
123
125
  tabId: record["tabId"],
124
126
  ...(cwd ? { cwd } : {}),
125
127
  ...(lastAssistantId ? { lastAssistantId } : {}),
128
+ ...(lastQuestionId ? { lastQuestionId } : {}),
126
129
  ...(name ? { name } : {}),
127
130
  };
128
131
  }
@@ -132,6 +135,7 @@ export function recordForPanel(
132
135
  activity: AgentActivity,
133
136
  scope: MonitoredAgent["scope"],
134
137
  lastAssistantId?: string,
138
+ lastQuestionId?: string,
135
139
  ): MonitoredAgent {
136
140
  const cwd = panel.foreground_cwd ?? panel.cwd;
137
141
  return {
@@ -144,6 +148,7 @@ export function recordForPanel(
144
148
  ...(panel.name ? { name: panel.name } : {}),
145
149
  ...(cwd ? { cwd } : {}),
146
150
  ...(lastAssistantId ? { lastAssistantId } : {}),
151
+ ...(lastQuestionId ? { lastQuestionId } : {}),
147
152
  };
148
153
  }
149
154
 
@@ -160,6 +165,7 @@ export function sameMonitorRecord(
160
165
  left.cwd === right.cwd &&
161
166
  left.name === right.name &&
162
167
  left.lastAssistantId === right.lastAssistantId &&
168
+ left.lastQuestionId === right.lastQuestionId &&
163
169
  sameAgentActivity(left.activity, right.activity)
164
170
  );
165
171
  }
@@ -81,6 +81,13 @@ export class MonitorState {
81
81
  return this.agents.get(terminalId);
82
82
  }
83
83
 
84
+ markQuestion(terminalId: string, id: string): boolean {
85
+ const record = this.byTerminal(terminalId);
86
+ if (!record || record.lastQuestionId === id) return false;
87
+ this.agents.set(terminalId, { ...record, lastQuestionId: id });
88
+ return true;
89
+ }
90
+
84
91
  watch(
85
92
  panel: PaneInfo,
86
93
  lastAssistantId?: string,
@@ -102,6 +109,7 @@ export class MonitorState {
102
109
  reportCurrent
103
110
  ? undefined
104
111
  : (existing?.lastAssistantId ?? lastAssistantId),
112
+ existing?.lastQuestionId,
105
113
  );
106
114
  if (existing && existing.terminalId !== record.terminalId) {
107
115
  this.agents.delete(existing.terminalId);
@@ -348,6 +356,7 @@ export class MonitorState {
348
356
  activity,
349
357
  record.scope,
350
358
  record.lastAssistantId,
359
+ record.lastQuestionId,
351
360
  );
352
361
  if (!sameMonitorRecord(record, updated)) changed = true;
353
362
  if (record.terminalId !== updated.terminalId) {
@@ -382,12 +391,9 @@ export class MonitorState {
382
391
  ): boolean {
383
392
  const record = this.byTerminal(terminalId);
384
393
  if (!record || activityTask(record.activity) !== task) return false;
385
- if (record.scope === "task" && status !== "blocked") {
386
- this.agents.delete(terminalId);
387
- return true;
388
- }
389
394
  this.agents.set(terminalId, {
390
395
  ...record,
396
+ scope: "persistent",
391
397
  activity: { phase: "settled", status },
392
398
  ...(lastAssistantId ? { lastAssistantId } : {}),
393
399
  });