@howaboua/pi-shepherdr 0.1.1 → 0.1.3

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
@@ -9,6 +9,7 @@ import type {
9
9
  LatestAssistant,
10
10
  MonitoredAgent,
11
11
  PaneInfo,
12
+ PendingAsk,
12
13
  SettledAgentStatus,
13
14
  } from "./types.js";
14
15
 
@@ -33,16 +34,22 @@ interface AgentEventLabels {
33
34
 
34
35
  interface AgentEventOptions {
35
36
  agent: PaneInfo;
37
+ agentToolName: string;
38
+ ask?: PendingAsk;
36
39
  blockedMessage?: string;
37
40
  labels: AgentEventLabels;
41
+ machine: string;
42
+ operatorPrefix: string;
38
43
  record: MonitoredAgent;
39
44
  reply?: LatestAssistant;
40
45
  status: SettledAgentStatus;
41
46
  }
42
47
 
43
48
  interface AgentEventDetails {
49
+ ask?: PendingAsk;
44
50
  blockedOn?: string;
45
51
  cwd?: string;
52
+ machine: string;
46
53
  name?: string;
47
54
  paneId: string;
48
55
  response?: string;
@@ -52,6 +59,54 @@ interface AgentEventDetails {
52
59
  workspace?: string;
53
60
  }
54
61
 
62
+ function eventAsk(value: unknown): PendingAsk | undefined {
63
+ if (typeof value !== "object" || value === null) return undefined;
64
+ const record = value as Record<string, unknown>;
65
+ if (
66
+ typeof record["toolCallId"] !== "string" ||
67
+ typeof record["handoff"] !== "boolean" ||
68
+ !Array.isArray(record["prompts"])
69
+ ) {
70
+ return undefined;
71
+ }
72
+ const prompts: PendingAsk["prompts"] = [];
73
+ for (const value of record["prompts"]) {
74
+ if (typeof value !== "object" || value === null) return undefined;
75
+ const prompt = value as Record<string, unknown>;
76
+ if (
77
+ typeof prompt["title"] !== "string" ||
78
+ typeof prompt["multiple"] !== "boolean" ||
79
+ !Array.isArray(prompt["choices"])
80
+ ) {
81
+ return undefined;
82
+ }
83
+ const choices: PendingAsk["prompts"][number]["choices"] = [];
84
+ for (const value of prompt["choices"]) {
85
+ if (typeof value !== "object" || value === null) return undefined;
86
+ const choice = value as Record<string, unknown>;
87
+ if (typeof choice["label"] !== "string") return undefined;
88
+ choices.push({
89
+ label: choice["label"],
90
+ ...(typeof choice["description"] === "string"
91
+ ? { description: choice["description"] }
92
+ : {}),
93
+ });
94
+ }
95
+ prompts.push({
96
+ title: prompt["title"],
97
+ multiple: prompt["multiple"],
98
+ choices,
99
+ ...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
100
+ });
101
+ }
102
+ if (prompts.length === 0) return undefined;
103
+ return {
104
+ toolCallId: record["toolCallId"],
105
+ handoff: record["handoff"],
106
+ prompts,
107
+ };
108
+ }
109
+
55
110
  function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
56
111
  const encoder = new TextEncoder();
57
112
  const bytes = encoder.encode(prompt);
@@ -72,7 +127,7 @@ function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
72
127
 
73
128
  function agentVoicePrompt(details: AgentEventDetails): string {
74
129
  const lines = [
75
- `Worker: ${details.name?.trim() || "unnamed"}`,
130
+ `Worker: ${details.machine} / ${details.name?.trim() || "unnamed"}`,
76
131
  `State: ${details.state}`,
77
132
  ];
78
133
  if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
@@ -85,6 +140,11 @@ function agentVoicePrompt(details: AgentEventDetails): string {
85
140
  "The blocked worker details above were truncated. Tell the user and ask whether they would like the rest.";
86
141
  if (details.blockedOn?.trim())
87
142
  lines.push(`Reason:\n${details.blockedOn.trim()}`);
143
+ if (details.ask) {
144
+ lines.push(
145
+ `Questions:\n${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
146
+ );
147
+ }
88
148
  } else {
89
149
  instruction =
90
150
  details.state === "failed"
@@ -105,7 +165,7 @@ function announceAgentEvent(
105
165
  pi: ExtensionAPI,
106
166
  details: AgentEventDetails,
107
167
  ): void {
108
- const candidateId = `pi-shepherdr:${details.paneId}`;
168
+ const candidateId = `pi-shepherdr:${details.machine}:${details.paneId}`;
109
169
  const id =
110
170
  new TextEncoder().encode(candidateId).byteLength <= 160
111
171
  ? candidateId
@@ -115,12 +175,26 @@ function announceAgentEvent(
115
175
  pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
116
176
  }
117
177
 
118
- function blockedOperatorHint(paneId: string): string {
119
- return `Inspect first with \`herdr agent read ${paneId} --source visible\`; respond with \`herdr agent prompt ${paneId} "<text>"\` or use \`herdr agent send-keys ${paneId} <keys>\` for interactive controls.`;
178
+ function operatorCommand(operatorPrefix: string, command: string): string {
179
+ return `\`${operatorPrefix} ${command}\``;
180
+ }
181
+
182
+ function blockedOperatorHint(
183
+ agentToolName: string,
184
+ machine: string,
185
+ operatorPrefix: string,
186
+ paneId: string,
187
+ ): string {
188
+ return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through ${agentToolName} with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
120
189
  }
121
190
 
122
- function failedOperatorHint(paneId: string): string {
123
- return `Inspect with \`herdr agent read ${paneId} --source recent-unwrapped --lines 80\` and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once with \`herdr agent prompt ${paneId} "<text>"\`. If it fails again or the setup looks broken, stop retrying and tell the user.`;
191
+ function failedOperatorHint(
192
+ agentToolName: string,
193
+ machine: string,
194
+ operatorPrefix: string,
195
+ paneId: string,
196
+ ): string {
197
+ return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through ${agentToolName} with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
124
198
  }
125
199
 
126
200
  function eventDetails(value: unknown): AgentEventDetails | undefined {
@@ -128,6 +202,8 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
128
202
  const details = value as Record<string, unknown>;
129
203
  if (
130
204
  typeof details["paneId"] !== "string" ||
205
+ (details["machine"] !== undefined &&
206
+ typeof details["machine"] !== "string") ||
131
207
  (details["state"] !== "blocked" &&
132
208
  details["state"] !== "failed" &&
133
209
  details["state"] !== "finished")
@@ -138,9 +214,13 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
138
214
  typeof details[field] === "string"
139
215
  ? { [field]: details[field] as string }
140
216
  : {};
217
+ const ask = eventAsk(details["ask"]);
141
218
  return {
219
+ machine:
220
+ typeof details["machine"] === "string" ? details["machine"] : "local",
142
221
  paneId: details["paneId"],
143
222
  state: details["state"],
223
+ ...(ask ? { ask } : {}),
144
224
  ...optional("blockedOn"),
145
225
  ...optional("cwd"),
146
226
  ...optional("name"),
@@ -155,7 +235,18 @@ function agentEvent(options: AgentEventOptions): {
155
235
  content: string;
156
236
  details: AgentEventDetails;
157
237
  } {
158
- const { agent, blockedMessage, labels, record, reply, status } = options;
238
+ const {
239
+ agent,
240
+ agentToolName,
241
+ ask,
242
+ blockedMessage,
243
+ labels,
244
+ machine,
245
+ operatorPrefix,
246
+ record,
247
+ reply,
248
+ status,
249
+ } = options;
159
250
  const task = activityTask(record.activity);
160
251
  const blocked = status === "blocked";
161
252
  const failed = !blocked && reply?.stopReason === "error";
@@ -166,6 +257,7 @@ function agentEvent(options: AgentEventOptions): {
166
257
  ? "herdr_agent_failed"
167
258
  : "herdr_agent_result";
168
259
  const attributes = [
260
+ `machine="${xml(machine)}"`,
169
261
  `pane="${xml(agent.pane_id)}"`,
170
262
  record.name ? `name="${xml(record.name)}"` : undefined,
171
263
  cwd ? `directory="${xml(cwd)}"` : undefined,
@@ -177,14 +269,19 @@ function agentEvent(options: AgentEventOptions): {
177
269
  if (blockedMessage) {
178
270
  lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
179
271
  }
272
+ if (blocked && ask) {
273
+ lines.push(
274
+ `<ask>${xml(JSON.stringify({ handoff: ask.handoff, prompts: ask.prompts }))}</ask>`,
275
+ );
276
+ }
180
277
  if (blocked) {
181
278
  lines.push(
182
- `<operator_hint>${xml(blockedOperatorHint(agent.pane_id))}</operator_hint>`,
279
+ `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
183
280
  );
184
281
  }
185
282
  if (failed) {
186
283
  lines.push(
187
- `<operator_hint>${xml(failedOperatorHint(agent.pane_id))}</operator_hint>`,
284
+ `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
188
285
  );
189
286
  }
190
287
  if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
@@ -193,8 +290,10 @@ function agentEvent(options: AgentEventOptions): {
193
290
  return {
194
291
  content: lines.join("\n"),
195
292
  details: {
293
+ machine,
196
294
  paneId: agent.pane_id,
197
295
  state: blocked ? "blocked" : failed ? "failed" : "finished",
296
+ ...(blocked && ask ? { ask } : {}),
198
297
  ...(record.name ? { name: record.name } : {}),
199
298
  ...(cwd ? { cwd } : {}),
200
299
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
@@ -249,9 +348,10 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
249
348
  }
250
349
  const blocked = details?.state === "blocked";
251
350
  const failed = details?.state === "failed";
252
- const identity = details?.name
351
+ const agentIdentity = details?.name
253
352
  ? `${details.name} (${details.paneId})`
254
353
  : (details?.paneId ?? "unknown");
354
+ const identity = `${details.machine} / ${agentIdentity}`;
255
355
  const title = theme.fg(
256
356
  blocked || failed ? "error" : "success",
257
357
  `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
@@ -277,6 +377,38 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
277
377
  0,
278
378
  ),
279
379
  );
380
+ if (details.ask) {
381
+ box.addChild(
382
+ new Text(
383
+ theme.fg(
384
+ "muted",
385
+ `Questions: ${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
386
+ ),
387
+ 0,
388
+ 0,
389
+ ),
390
+ );
391
+ if (expanded) {
392
+ for (const prompt of details.ask.prompts) {
393
+ box.addChild(new Spacer(1));
394
+ box.addChild(new Text(theme.fg("muted", prompt.title), 0, 0));
395
+ if (prompt.body) {
396
+ box.addChild(
397
+ new Markdown(prompt.body, 0, 0, getMarkdownTheme()),
398
+ );
399
+ }
400
+ if (prompt.choices.length > 0) {
401
+ box.addChild(
402
+ new Text(
403
+ `Choices: ${prompt.choices.map((choice) => choice.label).join(", ")}`,
404
+ 0,
405
+ 0,
406
+ ),
407
+ );
408
+ }
409
+ }
410
+ }
411
+ }
280
412
  }
281
413
  if (expanded && details?.task) {
282
414
  box.addChild(new Spacer(1));
@@ -1,4 +1,4 @@
1
- import type { HerdrClient } from "./herdr-client.js";
1
+ import type { HerdrConnection } from "./herdr-client.js";
2
2
  import type { HerdrEvent } from "./types.js";
3
3
 
4
4
  interface Subscription {
@@ -7,7 +7,8 @@ interface Subscription {
7
7
  }
8
8
 
9
9
  interface MonitorEventsOptions {
10
- client: HerdrClient;
10
+ client: HerdrConnection;
11
+ reconnect?: boolean;
11
12
  onEvent: (event: HerdrEvent) => void;
12
13
  onReconnect: () => Promise<void>;
13
14
  onWarning: (message: string) => void;
@@ -94,9 +95,9 @@ export class MonitorEvents {
94
95
  } catch (error) {
95
96
  this.live.delete(generation);
96
97
  if (!this.active || generation !== this.generation) return;
97
- this.warn(
98
- `Herdr monitoring unavailable: ${error instanceof Error ? error.message : String(error)}`,
99
- );
98
+ const failure = error instanceof Error ? error : new Error(String(error));
99
+ this.warn(`Herdr monitoring unavailable: ${failure.message}`);
100
+ if (this.options.reconnect === false) throw failure;
100
101
  this.scheduleReconnect(generation, false);
101
102
  }
102
103
  }
@@ -115,6 +116,7 @@ export class MonitorEvents {
115
116
 
116
117
  private scheduleReconnect(generation: number, disconnected: boolean): void {
117
118
  if (!this.active || generation !== this.generation) return;
119
+ if (this.options.reconnect === false) return;
118
120
  if (disconnected && this.subscription?.generation === generation) {
119
121
  this.subscription = undefined;
120
122
  }
@@ -16,6 +16,18 @@ function optionalString(
16
16
  : false;
17
17
  }
18
18
 
19
+ function optionalNullableString(
20
+ value: Record<string, unknown>,
21
+ field: string,
22
+ ): string | null | undefined | false {
23
+ const candidate = value[field];
24
+ return candidate === undefined ||
25
+ candidate === null ||
26
+ typeof candidate === "string"
27
+ ? candidate
28
+ : false;
29
+ }
30
+
19
31
  function stableActivity(value: unknown): StableAgentActivity | undefined {
20
32
  if (typeof value !== "object" || value === null) return undefined;
21
33
  const activity = value as Record<string, unknown>;
@@ -28,9 +40,24 @@ function stableActivity(value: unknown): StableAgentActivity | undefined {
28
40
  }
29
41
  if (activity["phase"] !== "working") return undefined;
30
42
  const task = optionalString(activity, "task");
43
+ const attemptId = optionalString(activity, "attemptId");
44
+ const expectedUserAfter = optionalNullableString(
45
+ activity,
46
+ "expectedUserAfter",
47
+ );
31
48
  return task === false
32
49
  ? undefined
33
- : { phase: "working", ...(task ? { task } : {}) };
50
+ : attemptId === false
51
+ ? undefined
52
+ : expectedUserAfter === false ||
53
+ (expectedUserAfter !== undefined && !task)
54
+ ? undefined
55
+ : {
56
+ phase: "working",
57
+ ...(attemptId ? { attemptId } : {}),
58
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
59
+ ...(task ? { task } : {}),
60
+ };
34
61
  }
35
62
 
36
63
  function parsedActivity(value: unknown): AgentActivity | undefined {
@@ -39,10 +66,15 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
39
66
  if (typeof value !== "object" || value === null) return undefined;
40
67
  const activity = value as Record<string, unknown>;
41
68
  const previous = stableActivity(activity["previous"]);
69
+ const expectedUserAfter = optionalNullableString(
70
+ activity,
71
+ "expectedUserAfter",
72
+ );
42
73
  if (
43
74
  activity["phase"] !== "submitting" ||
44
75
  typeof activity["attemptId"] !== "string" ||
45
76
  typeof activity["task"] !== "string" ||
77
+ expectedUserAfter === false ||
46
78
  !previous
47
79
  ) {
48
80
  return undefined;
@@ -52,6 +84,7 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
52
84
  phase: "submitting",
53
85
  previous,
54
86
  task: activity["task"],
87
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
55
88
  };
56
89
  }
57
90
 
@@ -34,6 +34,7 @@ interface CompletionCandidate {
34
34
  interface ReconcileResult {
35
35
  changed: boolean;
36
36
  completions: CompletionCandidate[];
37
+ removed: MonitoredAgent[];
37
38
  }
38
39
 
39
40
  interface StatusResult {
@@ -85,10 +86,12 @@ export class MonitorState {
85
86
  watch(
86
87
  panel: PaneInfo,
87
88
  lastAssistantId?: string,
89
+ reportSettled = true,
88
90
  ): { record: MonitoredAgent; reportCurrent: boolean } {
89
91
  const existing =
90
92
  this.byTerminal(panel.terminal_id) ?? this.byPane(panel.pane_id);
91
93
  const reportCurrent =
94
+ reportSettled &&
92
95
  !existing &&
93
96
  (panel.agent_status === "done" || panel.agent_status === "blocked");
94
97
  const activity = reportCurrent
@@ -114,7 +117,11 @@ export class MonitorState {
114
117
  return record;
115
118
  }
116
119
 
117
- beginWork(paneId: string, task: string): WorkAttempt | undefined {
120
+ beginWork(
121
+ paneId: string,
122
+ task: string,
123
+ expectedUserAfter?: string | null,
124
+ ): WorkAttempt | undefined {
118
125
  const record = this.byPane(paneId);
119
126
  if (!record) return undefined;
120
127
  if (record.activity.phase === "submitting") {
@@ -133,6 +140,7 @@ export class MonitorState {
133
140
  phase: "submitting",
134
141
  previous: record.activity,
135
142
  task,
143
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
136
144
  },
137
145
  });
138
146
  return attempt;
@@ -149,7 +157,14 @@ export class MonitorState {
149
157
  }
150
158
  this.agents.set(record.terminalId, {
151
159
  ...record,
152
- activity: { phase: "working", task: record.activity.task },
160
+ activity: {
161
+ attemptId: record.activity.attemptId,
162
+ ...(record.activity.expectedUserAfter !== undefined
163
+ ? { expectedUserAfter: record.activity.expectedUserAfter }
164
+ : {}),
165
+ phase: "working",
166
+ task: record.activity.task,
167
+ },
153
168
  });
154
169
  return true;
155
170
  }
@@ -175,8 +190,18 @@ export class MonitorState {
175
190
  if (!record) return { changed: false };
176
191
  if (status === "working") {
177
192
  const task = activityTask(record.activity);
193
+ const attemptId =
194
+ record.activity.phase === "settled"
195
+ ? undefined
196
+ : record.activity.attemptId;
197
+ const expectedUserAfter =
198
+ record.activity.phase === "settled"
199
+ ? undefined
200
+ : record.activity.expectedUserAfter;
178
201
  const next: AgentActivity = {
179
202
  phase: "working",
203
+ ...(attemptId ? { attemptId } : {}),
204
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
180
205
  ...(task ? { task } : {}),
181
206
  };
182
207
  const changed = !sameAgentActivity(record.activity, next);
@@ -210,6 +235,7 @@ export class MonitorState {
210
235
  ): ReconcileResult {
211
236
  let changed = false;
212
237
  const completions: CompletionCandidate[] = [];
238
+ const removed: MonitoredAgent[] = [];
213
239
  for (const record of this.list()) {
214
240
  const panel =
215
241
  snapshot.agents.find(
@@ -226,6 +252,7 @@ export class MonitorState {
226
252
  );
227
253
  if (!paneStillExists) {
228
254
  this.agents.delete(record.terminalId);
255
+ removed.push(record);
229
256
  changed = true;
230
257
  }
231
258
  continue;
@@ -236,7 +263,16 @@ export class MonitorState {
236
263
  let completion: Omit<CompletionCandidate, "record"> | undefined;
237
264
  if (panel.agent_status === "working") {
238
265
  const task = activityTask(activity);
239
- activity = { phase: "working", ...(task ? { task } : {}) };
266
+ const attemptId =
267
+ activity.phase === "settled" ? undefined : activity.attemptId;
268
+ const expectedUserAfter =
269
+ activity.phase === "settled" ? undefined : activity.expectedUserAfter;
270
+ activity = {
271
+ phase: "working",
272
+ ...(attemptId ? { attemptId } : {}),
273
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
274
+ ...(task ? { task } : {}),
275
+ };
240
276
  } else if (
241
277
  isSettledStatus(panel.agent_status) &&
242
278
  activity.phase !== "settled"
@@ -259,7 +295,7 @@ export class MonitorState {
259
295
  this.agents.set(updated.terminalId, updated);
260
296
  if (completion) completions.push({ ...completion, record: updated });
261
297
  }
262
- return { changed, completions };
298
+ return { changed, completions, removed };
263
299
  }
264
300
 
265
301
  movePane(