@howaboua/pi-shepherdr 0.1.6 → 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/fleet.ts CHANGED
@@ -6,10 +6,9 @@ import { getSnapshot } from "./herdr.js";
6
6
  import { HerdrClient, type HerdrConnection } from "./herdr-client.js";
7
7
  import {
8
8
  LOCAL_MACHINE,
9
- type MachinesConfig,
10
- type RemoteMachineConfig,
11
- readMachinesConfig,
12
- } from "./machines-config.js";
9
+ readMachineCatalog,
10
+ type SshMachine,
11
+ } from "./machine-catalog.js";
13
12
  import { AgentMonitor } from "./monitor.js";
14
13
  import { parseMonitoredAgent } from "./monitor-record.js";
15
14
  import { RemoteHerdrClient } from "./remote-client.js";
@@ -27,7 +26,7 @@ const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
27
26
  interface Runtime {
28
27
  attempting?: boolean;
29
28
  client?: HerdrConnection;
30
- config?: RemoteMachineConfig;
29
+ config?: SshMachine;
31
30
  local: boolean;
32
31
  monitor?: AgentMonitor;
33
32
  monitoringIssue?: MonitoringIssue;
@@ -63,41 +62,28 @@ function shellQuote(value: string): string {
63
62
  return `'${value.replaceAll("'", `'"'"'`)}'`;
64
63
  }
65
64
 
66
- function operatorPrefix(config: RemoteMachineConfig): string {
67
- const socket = config.socket?.startsWith("~/")
68
- ? `HERDR_SOCKET_PATH="$HOME"/${shellQuote(config.socket.slice(2))}`
69
- : config.socket === "~"
70
- ? 'HERDR_SOCKET_PATH="$HOME"'
71
- : config.socket
72
- ? `HERDR_SOCKET_PATH=${shellQuote(config.socket)}`
73
- : undefined;
74
- const remote = socket
75
- ? ["env", socket, config.herdr]
76
- : [config.herdr, ...(config.session ? ["--session", config.session] : [])];
77
- return [...config.command, ...remote].map(shellQuote).join(" ");
78
- }
79
-
80
- function sameMachineConfig(
81
- left: RemoteMachineConfig,
82
- right: RemoteMachineConfig,
83
- ): boolean {
84
- return (
85
- left.herdr === right.herdr &&
86
- left.node === right.node &&
87
- left.session === right.session &&
88
- left.socket === right.socket &&
89
- left.command.length === right.command.length &&
90
- left.command.every((part, index) => part === right.command[index])
91
- );
65
+ function operatorPrefix(config: SshMachine): string {
66
+ return `ssh -T -o BatchMode=yes -- ${shellQuote(config.target)} herdr --session ${shellQuote(config.session)}`;
92
67
  }
93
68
 
94
69
  function savedAgents(ctx: ExtensionContext): unknown[] {
95
70
  let latest: unknown[] = [];
71
+ let version: unknown;
96
72
  for (const entry of ctx.sessionManager.getBranch()) {
97
73
  if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
98
74
  continue;
99
- const data = entry.data as { agents?: unknown };
100
- if (Array.isArray(data?.agents)) latest = data.agents;
75
+ const data = entry.data as { version?: unknown; agents?: unknown };
76
+ if (Array.isArray(data?.agents)) {
77
+ latest = data.agents;
78
+ version = data.version;
79
+ }
80
+ }
81
+ if (latest.length > 0 && version !== 2) {
82
+ ctx.ui.notify(
83
+ "Cleared legacy Shepherdr watches; use watch to subscribe explicitly. Remote agents are unchanged.",
84
+ "warning",
85
+ );
86
+ return [];
101
87
  }
102
88
  return latest;
103
89
  }
@@ -120,7 +106,6 @@ function groupSaved(values: unknown[]): Map<string, unknown[]> {
120
106
  }
121
107
 
122
108
  export class AgentFleet {
123
- private config: MachinesConfig = { machines: {} };
124
109
  private context: ExtensionContext | undefined;
125
110
  private generation = 0;
126
111
  private readonly pi: ExtensionAPI;
@@ -134,14 +119,13 @@ export class AgentFleet {
134
119
  this.deactivate();
135
120
  const generation = this.generation;
136
121
  this.context = ctx;
137
- const config = await readMachinesConfig();
122
+ const catalog = await readMachineCatalog();
138
123
  if (!this.isCurrent(generation, ctx)) return;
139
- this.config = config;
124
+ const machines = Object.entries(catalog).filter(
125
+ ([, machine]) => machine.enabled,
126
+ );
140
127
  const grouped = groupSaved(savedAgents(ctx));
141
- const known = new Set([
142
- LOCAL_MACHINE,
143
- ...Object.keys(this.config.machines),
144
- ]);
128
+ const known = new Set([LOCAL_MACHINE, ...machines.map(([id]) => id)]);
145
129
  const orphaned = [...grouped.entries()]
146
130
  .filter(([machine]) => !known.has(machine))
147
131
  .reduce((count, [, records]) => count + records.length, 0);
@@ -158,7 +142,7 @@ export class AgentFleet {
158
142
  status: "connecting",
159
143
  };
160
144
  this.runtimes.set(LOCAL_MACHINE, localRuntime);
161
- for (const [name, config] of Object.entries(this.config.machines)) {
145
+ for (const [name, config] of machines) {
162
146
  this.runtimes.set(name, {
163
147
  config,
164
148
  local: false,
@@ -189,9 +173,9 @@ export class AgentFleet {
189
173
  }
190
174
  localRuntime.pending = [];
191
175
  localRuntime.status = "connected";
192
- this.refresh();
176
+ this.changed();
193
177
 
194
- for (const name of Object.keys(this.config.machines)) {
178
+ for (const [name] of machines) {
195
179
  void this.connectMachine(name, generation, true);
196
180
  }
197
181
  }
@@ -215,19 +199,25 @@ export class AgentFleet {
215
199
  const ctx = this.context;
216
200
  if (!ctx) return;
217
201
  const generation = this.generation;
218
- const config = await readMachinesConfig();
202
+ const catalog = await readMachineCatalog();
219
203
  if (!this.isCurrent(generation, ctx)) return;
220
204
  const reconnect: string[] = [];
221
205
 
222
206
  for (const [name, runtime] of this.runtimes) {
223
- if (runtime.local || Object.hasOwn(config.machines, name)) continue;
207
+ if (runtime.local || catalog[name]?.enabled) continue;
224
208
  runtime.monitor?.deactivate();
225
209
  if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
226
210
  this.runtimes.delete(name);
227
211
  }
228
- for (const [name, machineConfig] of Object.entries(config.machines)) {
212
+ for (const [name, machineConfig] of Object.entries(catalog)) {
213
+ if (!machineConfig.enabled) continue;
229
214
  const runtime = this.runtimes.get(name);
230
- if (runtime?.config && sameMachineConfig(runtime.config, machineConfig)) {
215
+ if (
216
+ runtime?.config &&
217
+ runtime.config.target === machineConfig.target &&
218
+ runtime.config.session === machineConfig.session
219
+ ) {
220
+ runtime.config = machineConfig;
231
221
  continue;
232
222
  }
233
223
  const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
@@ -241,7 +231,6 @@ export class AgentFleet {
241
231
  });
242
232
  reconnect.push(name);
243
233
  }
244
- this.config = config;
245
234
  this.changed();
246
235
  for (const name of reconnect) {
247
236
  void this.connectMachine(name, generation, true);
@@ -302,7 +291,7 @@ export class AgentFleet {
302
291
  : this.statuses();
303
292
  return Promise.all(
304
293
  selected.map(async (status) => {
305
- const runtime = this.runtimes.get(status.name);
294
+ const runtime = this.runtimes.get(status.id);
306
295
  if (
307
296
  status.status !== "connected" ||
308
297
  !runtime?.client ||
@@ -317,10 +306,10 @@ export class AgentFleet {
317
306
  runtime.status !== "connected" ||
318
307
  runtime.client !== client ||
319
308
  runtime.monitor !== monitor ||
320
- this.runtimes.get(status.name) !== runtime
309
+ this.runtimes.get(status.id) !== runtime
321
310
  ) {
322
- return this.runtimes.has(status.name)
323
- ? this.statusFor(status.name)
311
+ return this.runtimes.has(status.id)
312
+ ? this.statusFor(status.id)
324
313
  : status;
325
314
  }
326
315
  return {
@@ -335,10 +324,10 @@ export class AgentFleet {
335
324
  runtime.status !== "connected" ||
336
325
  runtime.client !== client ||
337
326
  runtime.monitor !== monitor ||
338
- this.runtimes.get(status.name) !== runtime
327
+ this.runtimes.get(status.id) !== runtime
339
328
  ) {
340
- return this.runtimes.has(status.name)
341
- ? this.statusFor(status.name)
329
+ return this.runtimes.has(status.id)
330
+ ? this.statusFor(status.id)
342
331
  : status;
343
332
  }
344
333
  return { ...status, snapshotError: errorMessage(error) };
@@ -420,8 +409,15 @@ export class AgentFleet {
420
409
  if (!runtime)
421
410
  throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
422
411
  return {
423
- name,
412
+ id: name,
424
413
  local: runtime.local,
414
+ ...(runtime.config
415
+ ? {
416
+ label: runtime.config.label,
417
+ target: runtime.config.target,
418
+ session: runtime.config.session,
419
+ }
420
+ : {}),
425
421
  status: runtime.status,
426
422
  ...(runtime.monitoringIssue
427
423
  ? { monitoringIssue: runtime.monitoringIssue }
@@ -438,6 +434,7 @@ export class AgentFleet {
438
434
  return new AgentMonitor(this.pi, {
439
435
  client,
440
436
  machine,
437
+ machineLabel: () => runtime.config?.label ?? LOCAL_MACHINE,
441
438
  onChange: () => this.changed(),
442
439
  onRefresh: () => this.refresh(),
443
440
  operatorPrefix: runtime.local ? "herdr" : operatorPrefix(runtime.config!),
@@ -544,11 +541,12 @@ export class AgentFleet {
544
541
  client.close();
545
542
  return;
546
543
  }
544
+ const pending = runtime.monitor?.list() ?? runtime.pending;
547
545
  const monitor = this.createMonitor(name, runtime, client);
548
546
  runtime.client = client;
549
547
  runtime.monitor = monitor;
550
548
  attached = true;
551
- await monitor.activate(ctx, runtime.pending);
549
+ await monitor.activate(ctx, pending);
552
550
  if (
553
551
  !this.isCurrent(generation, ctx) ||
554
552
  this.runtimes.get(name) !== runtime ||
@@ -593,12 +591,10 @@ export class AgentFleet {
593
591
  private disconnected(name: string, runtime: Runtime, reason: string): void {
594
592
  reason = errorMessage(reason);
595
593
  if (runtime.status === "unavailable" && runtime.reason === reason) return;
596
- if (runtime.monitor) {
597
- runtime.pending = runtime.monitor.list();
598
- runtime.monitor.deactivate();
599
- }
594
+ // Keep the stopped owner until reconnect so in-flight dispatch cleanup
595
+ // updates the state we persist, rather than a detached snapshot.
596
+ runtime.monitor?.deactivate();
600
597
  if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
601
- delete runtime.monitor;
602
598
  delete runtime.client;
603
599
  delete runtime.monitoringIssue;
604
600
  runtime.status = "unavailable";
@@ -614,7 +610,7 @@ export class AgentFleet {
614
610
  private changed(): void {
615
611
  if (!this.context) return;
616
612
  const agents = this.persistedAgents();
617
- this.pi.appendEntry(MONITOR_STATE_TYPE, { agents });
613
+ this.pi.appendEntry(MONITOR_STATE_TYPE, { version: 2, agents });
618
614
  this.refresh();
619
615
  }
620
616
 
package/src/herdr.ts CHANGED
@@ -46,6 +46,21 @@ export async function getPane(
46
46
  return parsePaneInfo(result["pane"], "pane.get result.pane");
47
47
  }
48
48
 
49
+ export async function getCurrentPane(
50
+ client: HerdrConnection,
51
+ ): Promise<PaneInfo> {
52
+ const callerPaneId = process.env["HERDR_PANE_ID"];
53
+ if (!callerPaneId)
54
+ throw new Error("HERDR_PANE_ID is required to identify the sender");
55
+ const result = record(
56
+ await client.request<unknown>("pane.current", {
57
+ caller_pane_id: callerPaneId,
58
+ }),
59
+ "pane.current result",
60
+ );
61
+ return parsePaneInfo(result["pane"], "pane.current result.pane");
62
+ }
63
+
49
64
  export async function resolvePiAgent(
50
65
  client: HerdrConnection,
51
66
  target: string,
@@ -101,6 +116,7 @@ export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
101
116
  ...optionalNullableString(pane, "foreground_cwd", path),
102
117
  ...optionalNullableString(pane, "label", path),
103
118
  ...optionalNullableString(pane, "name", path),
119
+ ...optionalNullableString(pane, "title", path),
104
120
  ...optionalBoolean(pane, "interactive_ready", path),
105
121
  ...optionalBoolean(pane, "launch_pending", path),
106
122
  ...parseAgentSession(pane["agent_session"], path),
@@ -182,7 +198,7 @@ function parseAgentSession(
182
198
  }
183
199
 
184
200
  function optionalNullableString<
185
- K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name",
201
+ K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name" | "title",
186
202
  >(
187
203
  value: Record<string, unknown>,
188
204
  key: K,
package/src/launch.ts CHANGED
@@ -8,7 +8,6 @@ import {
8
8
  resolveWorkspace,
9
9
  } from "./herdr.js";
10
10
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
11
- import type { AgentMonitor } from "./monitor.js";
12
11
  import type { PaneInfo } from "./types.js";
13
12
 
14
13
  export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
@@ -20,7 +19,6 @@ export interface StartAgentParams {
20
19
  name?: string;
21
20
  pane?: string;
22
21
  placement?: (typeof START_PLACEMENTS)[number];
23
- prompt?: string;
24
22
  workspace?: string;
25
23
  }
26
24
 
@@ -200,7 +198,6 @@ function nestedId(value: unknown, key: string, path: string): string {
200
198
 
201
199
  export async function startAgent(
202
200
  client: HerdrConnection,
203
- monitor: AgentMonitor,
204
201
  params: StartAgentParams,
205
202
  fallbackCwd: string,
206
203
  resolveDirectory: DirectoryResolver = directory,
@@ -234,25 +231,6 @@ export async function startAgent(
234
231
  } catch (error) {
235
232
  return rollbackCreatedLocation(client, created.cleanup, error);
236
233
  }
237
- try {
238
- await monitor.watch(agent);
239
- } catch (error) {
240
- return rollbackCreatedLocation(client, created.cleanup, error);
241
- }
242
- if (params.prompt?.trim()) {
243
- const prompt = params.prompt.trim();
244
- const attempt = monitor.beginWork(agent.pane_id, prompt);
245
- try {
246
- await client.request("agent.prompt", {
247
- target: agent.pane_id,
248
- text: prompt,
249
- });
250
- monitor.acceptWork(attempt);
251
- } catch (error) {
252
- await monitor.handleWorkFailure(attempt, error);
253
- throw error;
254
- }
255
- }
256
234
  return {
257
235
  agent,
258
236
  ...(created.cleanup ? { cleanup: created.cleanup } : {}),
@@ -262,12 +240,9 @@ export async function startAgent(
262
240
 
263
241
  export async function rollbackStartedAgent(
264
242
  client: HerdrConnection,
265
- monitor: AgentMonitor,
266
243
  started: StartedAgent,
267
244
  cause: unknown,
268
245
  ): Promise<never> {
269
- if (!started.cleanup) throw cause;
270
- await monitor.unwatch(started.id).catch(() => undefined);
271
246
  return rollbackCreatedLocation(client, started.cleanup, cause);
272
247
  }
273
248
 
@@ -0,0 +1,60 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { type Static, Type } from "typebox";
4
+ import { Check } from "typebox/value";
5
+
6
+ export const LOCAL_MACHINE = "local";
7
+
8
+ const Machine = Type.Object({
9
+ id: Type.String({ pattern: "^[a-f0-9]{32}$" }),
10
+ label: Type.String({ minLength: 1, pattern: "^[^\\x00-\\x1f\\x7f]+$" }),
11
+ target: Type.String({
12
+ minLength: 1,
13
+ pattern: "^[^-\\x00-\\x1f\\x7f][^\\x00-\\x1f\\x7f]*$",
14
+ }),
15
+ session: Type.String({
16
+ minLength: 1,
17
+ maxLength: 64,
18
+ pattern: "^[a-zA-Z0-9_.-]+$",
19
+ }),
20
+ enabled: Type.Boolean(),
21
+ });
22
+ const Catalog = Type.Array(Machine);
23
+ export type SshMachine = Static<typeof Machine>;
24
+
25
+ export async function readMachineCatalog(): Promise<
26
+ Record<string, SshMachine>
27
+ > {
28
+ let stdout: string;
29
+ try {
30
+ ({ stdout } = await promisify(execFile)(
31
+ process.env["HERDR_BIN_PATH"]?.trim() || "herdr",
32
+ ["machine", "list", "--json"],
33
+ {
34
+ timeout: 10_000,
35
+ maxBuffer: 1024 * 1024,
36
+ encoding: "utf8",
37
+ },
38
+ ));
39
+ } catch (error) {
40
+ throw new Error(
41
+ `Could not read Herdr machines; requires Herdr 0.9 or newer: ${error instanceof Error ? error.message : String(error)}`,
42
+ );
43
+ }
44
+ let value: unknown;
45
+ try {
46
+ value = JSON.parse(stdout);
47
+ } catch {
48
+ throw new Error("Herdr machine list returned invalid JSON");
49
+ }
50
+ if (
51
+ !Check(Catalog, value) ||
52
+ value.some((machine) => machine.session === "." || machine.session === "..")
53
+ ) {
54
+ throw new Error("Herdr machine list returned an invalid catalog");
55
+ }
56
+ if (new Set(value.map((machine) => machine.id)).size !== value.length) {
57
+ throw new Error("Herdr machine list returned duplicate profile IDs");
58
+ }
59
+ return Object.fromEntries(value.map((machine) => [machine.id, machine]));
60
+ }
package/src/messages.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { hostname } from "node:os";
1
2
  import {
2
3
  type ExtensionAPI,
3
4
  type ExtensionContext,
@@ -6,6 +7,8 @@ import {
6
7
  import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
7
8
  import { activityTask } from "./activity.js";
8
9
  import { sendPolicyMessage } from "./delivery.js";
10
+ import { getCurrentPane, getSnapshot } from "./herdr.js";
11
+ import type { HerdrConnection } from "./herdr-client.js";
9
12
  import type {
10
13
  LatestAssistant,
11
14
  MonitoredAgent,
@@ -33,6 +36,54 @@ interface AgentEventLabels {
33
36
  workspace?: string;
34
37
  }
35
38
 
39
+ export function agentSource(agent: PaneInfo, labels: AgentEventLabels) {
40
+ const paneName = agent.label || agent.title;
41
+ return {
42
+ pane: agent.pane_id,
43
+ workspace: agent.workspace_id,
44
+ tab: agent.tab_id,
45
+ ...(agent.name ? { name: agent.name } : {}),
46
+ ...(paneName ? { pane_name: paneName } : {}),
47
+ ...(labels.workspace ? { workspace_name: labels.workspace } : {}),
48
+ ...(labels.tab ? { tab_name: labels.tab } : {}),
49
+ };
50
+ }
51
+
52
+ function sourceAttributes(source: Record<string, string | undefined>): string {
53
+ return Object.entries(source)
54
+ .filter((entry): entry is [string, string] => entry[1] !== undefined)
55
+ .map(
56
+ ([key, value]) =>
57
+ `${key}="${xml(value).replaceAll("\n", "&#10;").replaceAll("\r", "&#13;")}"`,
58
+ )
59
+ .join(" ");
60
+ }
61
+
62
+ export async function attributeAgentPrompt(
63
+ client: HerdrConnection,
64
+ message: string,
65
+ kind: "message" | "task",
66
+ ): Promise<string> {
67
+ const [pane, snapshot] = await Promise.all([
68
+ getCurrentPane(client),
69
+ getSnapshot(client),
70
+ ]);
71
+ const workspace = snapshot.workspaces.find(
72
+ (workspace) => workspace.workspace_id === pane.workspace_id,
73
+ )?.label;
74
+ const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
75
+ const source = {
76
+ kind,
77
+ host: hostname(),
78
+ session: process.env["HERDR_SESSION"] || "default",
79
+ ...agentSource(pane, {
80
+ ...(workspace ? { workspace } : {}),
81
+ ...(tab ? { tab } : {}),
82
+ }),
83
+ };
84
+ return `<herdr_sender ${sourceAttributes(source)} />\n${message}`;
85
+ }
86
+
36
87
  interface AgentEventOptions {
37
88
  agent: PaneInfo;
38
89
  agentToolName: string;
@@ -40,6 +91,7 @@ interface AgentEventOptions {
40
91
  blockedMessage?: string;
41
92
  labels: AgentEventLabels;
42
93
  machine: string;
94
+ machineLabel: string;
43
95
  operatorPrefix: string;
44
96
  record: MonitoredAgent;
45
97
  reply?: LatestAssistant;
@@ -51,6 +103,7 @@ interface AgentEventDetails {
51
103
  blockedOn?: string;
52
104
  cwd?: string;
53
105
  machine: string;
106
+ machineLabel?: string;
54
107
  name?: string;
55
108
  paneId: string;
56
109
  response?: string;
@@ -128,7 +181,7 @@ function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
128
181
 
129
182
  function agentVoicePrompt(details: AgentEventDetails): string {
130
183
  const lines = [
131
- `Worker: ${details.machine} / ${details.name?.trim() || "unnamed"}`,
184
+ `Worker: ${details.machineLabel ?? details.machine} / ${details.name?.trim() || "unnamed"}`,
132
185
  `State: ${details.state}`,
133
186
  ];
134
187
  if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
@@ -224,6 +277,7 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
224
277
  ...(ask ? { ask } : {}),
225
278
  ...optional("blockedOn"),
226
279
  ...optional("cwd"),
280
+ ...optional("machineLabel"),
227
281
  ...optional("name"),
228
282
  ...optional("response"),
229
283
  ...optional("tab"),
@@ -243,6 +297,7 @@ function agentEvent(options: AgentEventOptions): {
243
297
  blockedMessage,
244
298
  labels,
245
299
  machine,
300
+ machineLabel,
246
301
  operatorPrefix,
247
302
  record,
248
303
  reply,
@@ -257,14 +312,13 @@ function agentEvent(options: AgentEventOptions): {
257
312
  : failed
258
313
  ? "herdr_agent_failed"
259
314
  : "herdr_agent_result";
260
- const attributes = [
261
- `machine="${xml(machine)}"`,
262
- `pane="${xml(agent.pane_id)}"`,
263
- record.name ? `name="${xml(record.name)}"` : undefined,
264
- cwd ? `directory="${xml(cwd)}"` : undefined,
265
- ]
266
- .filter(Boolean)
267
- .join(" ");
315
+ const attributes = sourceAttributes({
316
+ machine,
317
+ machine_name: machineLabel !== machine ? machineLabel : undefined,
318
+ ...agentSource(agent, labels),
319
+ name: agent.name ?? record.name,
320
+ directory: cwd,
321
+ });
268
322
  const lines = [`<${tag} ${attributes}>`];
269
323
  if (task) lines.push(`<task>${xml(task)}</task>`);
270
324
  if (blockedMessage) {
@@ -292,10 +346,11 @@ function agentEvent(options: AgentEventOptions): {
292
346
  content: lines.join("\n"),
293
347
  details: {
294
348
  machine,
349
+ machineLabel,
295
350
  paneId: agent.pane_id,
296
351
  state: blocked ? "blocked" : failed ? "failed" : "finished",
297
352
  ...(blocked && ask ? { ask } : {}),
298
- ...(record.name ? { name: record.name } : {}),
353
+ ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
299
354
  ...(cwd ? { cwd } : {}),
300
355
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
301
356
  ...(labels.tab ? { tab: labels.tab } : {}),
@@ -353,7 +408,7 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
353
408
  const agentIdentity = details?.name
354
409
  ? `${details.name} (${details.paneId})`
355
410
  : (details?.paneId ?? "unknown");
356
- const identity = `${details.machine} / ${agentIdentity}`;
411
+ const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
357
412
  const title = theme.fg(
358
413
  blocked || failed ? "error" : "success",
359
414
  `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
@@ -88,30 +88,13 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
88
88
  };
89
89
  }
90
90
 
91
- function legacyActivity(
92
- record: Record<string, unknown>,
93
- ): AgentActivity | undefined {
94
- if (!isAgentStatus(record["lastStatus"])) return undefined;
95
- const task = optionalString(record, "task");
96
- if (task === false) return undefined;
97
- if (record["lastStatus"] === "working") {
98
- return { phase: "working", ...(task ? { task } : {}) };
99
- }
100
- if (!task) return { phase: "settled", status: record["lastStatus"] };
101
- return {
102
- attemptId: `restored:${String(record["terminalId"])}`,
103
- phase: "submitting",
104
- previous: { phase: "settled", status: record["lastStatus"] },
105
- task,
106
- };
107
- }
108
-
109
91
  export function parseMonitoredAgent(
110
92
  value: unknown,
111
93
  ): MonitoredAgent | undefined {
112
94
  if (typeof value !== "object" || value === null) return undefined;
113
95
  const record = value as Record<string, unknown>;
114
96
  if (
97
+ (record["scope"] !== "task" && record["scope"] !== "persistent") ||
115
98
  typeof record["paneId"] !== "string" ||
116
99
  typeof record["terminalId"] !== "string" ||
117
100
  typeof record["workspaceId"] !== "string" ||
@@ -122,7 +105,7 @@ export function parseMonitoredAgent(
122
105
  const cwd = optionalString(record, "cwd");
123
106
  const lastAssistantId = optionalString(record, "lastAssistantId");
124
107
  const name = optionalString(record, "name");
125
- const activity = parsedActivity(record["activity"]) ?? legacyActivity(record);
108
+ const activity = parsedActivity(record["activity"]);
126
109
  if (
127
110
  cwd === false ||
128
111
  lastAssistantId === false ||
@@ -132,6 +115,7 @@ export function parseMonitoredAgent(
132
115
  return undefined;
133
116
  }
134
117
  return {
118
+ scope: record["scope"],
135
119
  activity,
136
120
  paneId: record["paneId"],
137
121
  terminalId: record["terminalId"],
@@ -146,10 +130,12 @@ export function parseMonitoredAgent(
146
130
  export function recordForPanel(
147
131
  panel: PaneInfo,
148
132
  activity: AgentActivity,
133
+ scope: MonitoredAgent["scope"],
149
134
  lastAssistantId?: string,
150
135
  ): MonitoredAgent {
151
136
  const cwd = panel.foreground_cwd ?? panel.cwd;
152
137
  return {
138
+ scope,
153
139
  activity,
154
140
  paneId: panel.pane_id,
155
141
  terminalId: panel.terminal_id,
@@ -166,6 +152,7 @@ export function sameMonitorRecord(
166
152
  right: MonitoredAgent,
167
153
  ): boolean {
168
154
  return (
155
+ left.scope === right.scope &&
169
156
  left.paneId === right.paneId &&
170
157
  left.terminalId === right.terminalId &&
171
158
  left.workspaceId === right.workspaceId &&
@@ -79,10 +79,6 @@ export class MonitorState {
79
79
  return this.agents.get(terminalId);
80
80
  }
81
81
 
82
- isMonitored(paneId: string): boolean {
83
- return this.byPane(paneId) !== undefined;
84
- }
85
-
86
82
  watch(
87
83
  panel: PaneInfo,
88
84
  lastAssistantId?: string,
@@ -100,6 +96,7 @@ export class MonitorState {
100
96
  const record = recordForPanel(
101
97
  panel,
102
98
  activity,
99
+ reportSettled ? "persistent" : (existing?.scope ?? "task"),
103
100
  reportCurrent
104
101
  ? undefined
105
102
  : (existing?.lastAssistantId ?? lastAssistantId),
@@ -129,6 +126,9 @@ export class MonitorState {
129
126
  `prompt submission to ${record.name ?? paneId} is still unresolved`,
130
127
  );
131
128
  }
129
+ if (record.activity.phase === "working" && record.activity.task) {
130
+ throw new Error("Agent already has delegated work; use send for updates");
131
+ }
132
132
  const attempt = {
133
133
  attemptId: randomUUID(),
134
134
  terminalId: record.terminalId,
@@ -322,7 +322,12 @@ export class MonitorState {
322
322
  activity = { phase: "settled", status: panel.agent_status };
323
323
  }
324
324
 
325
- const updated = recordForPanel(panel, activity, record.lastAssistantId);
325
+ const updated = recordForPanel(
326
+ panel,
327
+ activity,
328
+ record.scope,
329
+ record.lastAssistantId,
330
+ );
326
331
  if (!sameMonitorRecord(record, updated)) changed = true;
327
332
  if (record.terminalId !== updated.terminalId) {
328
333
  this.agents.delete(record.terminalId);
@@ -356,6 +361,10 @@ export class MonitorState {
356
361
  ): boolean {
357
362
  const record = this.byTerminal(terminalId);
358
363
  if (!record || activityTask(record.activity) !== task) return false;
364
+ if (record.scope === "task" && status !== "blocked") {
365
+ this.agents.delete(terminalId);
366
+ return true;
367
+ }
359
368
  this.agents.set(terminalId, {
360
369
  ...record,
361
370
  activity: { phase: "settled", status },