@howaboua/pi-shepherdr 0.1.0 → 0.1.2

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
@@ -13,6 +13,9 @@ import type {
13
13
  } from "./types.js";
14
14
 
15
15
  const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
16
+ const REALTIME_VOICE_PROMPT_CHANNEL =
17
+ "@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
18
+ const MAX_REALTIME_VOICE_PROMPT_BYTES = 4 * 1_024;
16
19
 
17
20
  function xml(value: string): string {
18
21
  return value
@@ -32,6 +35,8 @@ interface AgentEventOptions {
32
35
  agent: PaneInfo;
33
36
  blockedMessage?: string;
34
37
  labels: AgentEventLabels;
38
+ machine: string;
39
+ operatorPrefix: string;
35
40
  record: MonitoredAgent;
36
41
  reply?: LatestAssistant;
37
42
  status: SettledAgentStatus;
@@ -40,6 +45,7 @@ interface AgentEventOptions {
40
45
  interface AgentEventDetails {
41
46
  blockedOn?: string;
42
47
  cwd?: string;
48
+ machine: string;
43
49
  name?: string;
44
50
  paneId: string;
45
51
  response?: string;
@@ -49,8 +55,87 @@ interface AgentEventDetails {
49
55
  workspace?: string;
50
56
  }
51
57
 
52
- function operatorHint(paneId: string): string {
53
- 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.`;
58
+ function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
59
+ const encoder = new TextEncoder();
60
+ const bytes = encoder.encode(prompt);
61
+ if (bytes.byteLength <= MAX_REALTIME_VOICE_PROMPT_BYTES) return prompt;
62
+
63
+ const suffix = `…\n\n${truncationNotice}`;
64
+ const decoder = new TextDecoder("utf-8", { fatal: true });
65
+ let end = MAX_REALTIME_VOICE_PROMPT_BYTES - encoder.encode(suffix).byteLength;
66
+ while (end > 0) {
67
+ try {
68
+ return `${decoder.decode(bytes.subarray(0, end)).trimEnd()}${suffix}`;
69
+ } catch {
70
+ end -= 1;
71
+ }
72
+ }
73
+ return truncationNotice;
74
+ }
75
+
76
+ function agentVoicePrompt(details: AgentEventDetails): string {
77
+ const lines = [
78
+ `Worker: ${details.machine} / ${details.name?.trim() || "unnamed"}`,
79
+ `State: ${details.state}`,
80
+ ];
81
+ if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
82
+ let instruction: string;
83
+ let truncationNotice: string;
84
+ if (details.state === "blocked") {
85
+ instruction =
86
+ "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
87
+ truncationNotice =
88
+ "The blocked worker details above were truncated. Tell the user and ask whether they would like the rest.";
89
+ if (details.blockedOn?.trim())
90
+ lines.push(`Reason:\n${details.blockedOn.trim()}`);
91
+ } else {
92
+ instruction =
93
+ details.state === "failed"
94
+ ? "Briefly tell the user that this monitored worker failed and include useful detail from its report."
95
+ : "Briefly tell the user what this monitored worker found or completed; do not merely announce that it finished.";
96
+ truncationNotice =
97
+ "The worker report above was truncated. Tell the user and ask whether they would like the rest.";
98
+ if (details.response?.trim())
99
+ lines.push(`Report:\n${details.response.trim()}`);
100
+ }
101
+ return boundedVoicePrompt(
102
+ `${instruction}\n\n${lines.join("\n\n")}`,
103
+ truncationNotice,
104
+ );
105
+ }
106
+
107
+ function announceAgentEvent(
108
+ pi: ExtensionAPI,
109
+ details: AgentEventDetails,
110
+ ): void {
111
+ const candidateId = `pi-shepherdr:${details.machine}:${details.paneId}`;
112
+ const id =
113
+ new TextEncoder().encode(candidateId).byteLength <= 160
114
+ ? candidateId
115
+ : "pi-shepherdr:worker";
116
+ const prompt = agentVoicePrompt(details);
117
+ pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: true, prompt });
118
+ pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
119
+ }
120
+
121
+ function operatorCommand(operatorPrefix: string, command: string): string {
122
+ return `\`${operatorPrefix} ${command}\``;
123
+ }
124
+
125
+ function blockedOperatorHint(
126
+ machine: string,
127
+ operatorPrefix: string,
128
+ paneId: string,
129
+ ): string {
130
+ return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through herdr_agents with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
131
+ }
132
+
133
+ function failedOperatorHint(
134
+ machine: string,
135
+ operatorPrefix: string,
136
+ paneId: string,
137
+ ): string {
138
+ 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 herdr_agents with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
54
139
  }
55
140
 
56
141
  function eventDetails(value: unknown): AgentEventDetails | undefined {
@@ -58,6 +143,8 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
58
143
  const details = value as Record<string, unknown>;
59
144
  if (
60
145
  typeof details["paneId"] !== "string" ||
146
+ (details["machine"] !== undefined &&
147
+ typeof details["machine"] !== "string") ||
61
148
  (details["state"] !== "blocked" &&
62
149
  details["state"] !== "failed" &&
63
150
  details["state"] !== "finished")
@@ -69,6 +156,8 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
69
156
  ? { [field]: details[field] as string }
70
157
  : {};
71
158
  return {
159
+ machine:
160
+ typeof details["machine"] === "string" ? details["machine"] : "local",
72
161
  paneId: details["paneId"],
73
162
  state: details["state"],
74
163
  ...optional("blockedOn"),
@@ -85,7 +174,16 @@ function agentEvent(options: AgentEventOptions): {
85
174
  content: string;
86
175
  details: AgentEventDetails;
87
176
  } {
88
- const { agent, blockedMessage, labels, record, reply, status } = options;
177
+ const {
178
+ agent,
179
+ blockedMessage,
180
+ labels,
181
+ machine,
182
+ operatorPrefix,
183
+ record,
184
+ reply,
185
+ status,
186
+ } = options;
89
187
  const task = activityTask(record.activity);
90
188
  const blocked = status === "blocked";
91
189
  const failed = !blocked && reply?.stopReason === "error";
@@ -96,6 +194,7 @@ function agentEvent(options: AgentEventOptions): {
96
194
  ? "herdr_agent_failed"
97
195
  : "herdr_agent_result";
98
196
  const attributes = [
197
+ `machine="${xml(machine)}"`,
99
198
  `pane="${xml(agent.pane_id)}"`,
100
199
  record.name ? `name="${xml(record.name)}"` : undefined,
101
200
  cwd ? `directory="${xml(cwd)}"` : undefined,
@@ -109,7 +208,12 @@ function agentEvent(options: AgentEventOptions): {
109
208
  }
110
209
  if (blocked) {
111
210
  lines.push(
112
- `<operator_hint>${xml(operatorHint(agent.pane_id))}</operator_hint>`,
211
+ `<operator_hint>${xml(blockedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
212
+ );
213
+ }
214
+ if (failed) {
215
+ lines.push(
216
+ `<operator_hint>${xml(failedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
113
217
  );
114
218
  }
115
219
  if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
@@ -118,6 +222,7 @@ function agentEvent(options: AgentEventOptions): {
118
222
  return {
119
223
  content: lines.join("\n"),
120
224
  details: {
225
+ machine,
121
226
  paneId: agent.pane_id,
122
227
  state: blocked ? "blocked" : failed ? "failed" : "finished",
123
228
  ...(record.name ? { name: record.name } : {}),
@@ -149,6 +254,7 @@ export function injectAgentEvent(
149
254
  },
150
255
  delivery,
151
256
  );
257
+ announceAgentEvent(pi, message.details);
152
258
  }
153
259
 
154
260
  export function registerAgentEventRenderer(pi: ExtensionAPI): void {
@@ -173,9 +279,10 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
173
279
  }
174
280
  const blocked = details?.state === "blocked";
175
281
  const failed = details?.state === "failed";
176
- const identity = details?.name
282
+ const agentIdentity = details?.name
177
283
  ? `${details.name} (${details.paneId})`
178
284
  : (details?.paneId ?? "unknown");
285
+ const identity = `${details.machine} / ${agentIdentity}`;
179
286
  const title = theme.fg(
180
287
  blocked || failed ? "error" : "success",
181
288
  `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
@@ -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
  }
package/src/monitor.ts CHANGED
@@ -4,51 +4,81 @@ import type {
4
4
  } from "@earendil-works/pi-coding-agent";
5
5
  import { isSettledStatus } from "./activity.js";
6
6
  import { getSnapshot } from "./herdr.js";
7
- import { HerdrClient, isHerdrResponseError } from "./herdr-client.js";
7
+ import { type HerdrConnection, isHerdrResponseError } from "./herdr-client.js";
8
8
  import { parseMonitorEvent } from "./monitor-event.js";
9
9
  import { MonitorEvents } from "./monitor-events.js";
10
10
  import { MonitorState, type WorkAttempt } from "./monitor-state.js";
11
+ import type { AssistantReader } from "./session-reader.js";
11
12
  import { SettlementReporter, type SettlementRequest } from "./settlement.js";
12
13
  import type { HerdrEvent, MonitoredAgent, PaneInfo } from "./types.js";
13
- import { renderAgentWidget } from "./widget.js";
14
14
 
15
- const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
16
-
17
- interface MonitorStateEntry {
18
- agents: MonitoredAgent[];
15
+ interface AgentMonitorOptions {
16
+ client: HerdrConnection;
17
+ machine: string;
18
+ onChange: () => void;
19
+ onRefresh: () => void;
20
+ operatorPrefix: string;
21
+ onWarning: (message: string) => void;
22
+ reader?: AssistantReader;
23
+ reconnect: boolean;
24
+ selfPaneId?: string;
19
25
  }
20
26
 
21
27
  export class AgentMonitor {
22
- readonly client: HerdrClient;
23
- private readonly pi: ExtensionAPI;
28
+ readonly client: HerdrConnection;
29
+ readonly machine: string;
30
+ private readonly onChange: () => void;
31
+ private readonly onRefresh: () => void;
32
+ private readonly selfPaneId: string | undefined;
33
+ private readonly onWarning: (message: string) => void;
24
34
  private readonly state = new MonitorState();
25
35
  private readonly events: MonitorEvents;
26
36
  private readonly settlements: SettlementReporter;
27
37
  private context: ExtensionContext | undefined;
28
38
  private activationGeneration = 0;
29
39
 
30
- constructor(pi: ExtensionAPI, client = new HerdrClient()) {
31
- this.pi = pi;
32
- this.client = client;
33
- this.settlements = new SettlementReporter(pi, client, this.state, () =>
34
- this.persist(),
40
+ constructor(pi: ExtensionAPI, options: AgentMonitorOptions) {
41
+ this.client = options.client;
42
+ this.machine = options.machine;
43
+ this.onChange = options.onChange;
44
+ this.onRefresh = options.onRefresh;
45
+ this.selfPaneId = options.selfPaneId;
46
+ this.onWarning = options.onWarning;
47
+ this.settlements = new SettlementReporter(
48
+ pi,
49
+ this.client,
50
+ this.state,
51
+ () => this.persist(),
52
+ options.reader,
53
+ this.machine,
54
+ options.operatorPrefix,
35
55
  );
36
56
  this.events = new MonitorEvents({
37
- client,
57
+ client: this.client,
58
+ reconnect: options.reconnect,
38
59
  onEvent: (event) => this.handleEvent(event),
39
60
  onReconnect: () => this.reconcileNow(),
40
- onWarning: (message) => this.context?.ui.notify(message, "warning"),
61
+ onWarning: (message) => this.onWarning(message),
41
62
  targets: () => this.list().map((record) => record.paneId),
42
63
  });
43
64
  }
44
65
 
45
- async activate(ctx: ExtensionContext): Promise<void> {
66
+ async activate(
67
+ ctx: ExtensionContext,
68
+ restored: unknown[] = [],
69
+ ): Promise<void> {
46
70
  this.deactivate();
47
71
  const generation = this.activationGeneration;
48
72
  this.context = ctx;
49
- this.restore(ctx);
50
- renderAgentWidget(this.context, this.list());
51
- await this.reconcile(generation, ctx);
73
+ const dropped = this.state.restore(restored, this.selfPaneId);
74
+ if (dropped > 0) {
75
+ ctx.ui.notify(
76
+ `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"} for ${this.machine}`,
77
+ "warning",
78
+ );
79
+ }
80
+ this.onRefresh();
81
+ await this.reconcile(generation, ctx, dropped > 0);
52
82
  if (generation !== this.activationGeneration || ctx !== this.context)
53
83
  return;
54
84
  await this.events.start();
@@ -56,7 +86,6 @@ export class AgentMonitor {
56
86
 
57
87
  deactivate(): void {
58
88
  this.activationGeneration += 1;
59
- renderAgentWidget(this.context, []);
60
89
  this.context = undefined;
61
90
  this.events.stop();
62
91
  this.settlements.stop();
@@ -71,7 +100,7 @@ export class AgentMonitor {
71
100
  }
72
101
 
73
102
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
74
- if (panel.pane_id === process.env["HERDR_PANE_ID"]) {
103
+ if (panel.pane_id === this.selfPaneId) {
75
104
  throw new Error("refusing to monitor the controlling Pi session");
76
105
  }
77
106
  const reply = await this.settlements.latest(panel);
@@ -129,54 +158,36 @@ export class AgentMonitor {
129
158
  await this.reconcile(this.activationGeneration, this.context);
130
159
  }
131
160
 
132
- private restore(ctx: ExtensionContext): void {
133
- let latest: MonitorStateEntry | undefined;
134
- for (const entry of ctx.sessionManager.getBranch()) {
135
- if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
136
- continue;
137
- const data = entry.data as Partial<MonitorStateEntry>;
138
- if (Array.isArray(data?.agents)) {
139
- latest = { agents: data.agents };
140
- }
141
- }
142
- const dropped = this.state.restore(
143
- latest?.agents ?? [],
144
- process.env["HERDR_PANE_ID"],
145
- );
146
- if (dropped > 0) {
147
- ctx.ui.notify(
148
- `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"}`,
149
- "warning",
150
- );
151
- }
152
- }
153
-
154
161
  private persist(): void {
155
- this.pi.appendEntry(MONITOR_STATE_TYPE, { agents: this.list() });
156
- renderAgentWidget(this.context, this.list());
162
+ this.onChange();
157
163
  }
158
164
 
159
165
  private async reconcile(
160
166
  generation: number,
161
167
  context: ExtensionContext | undefined,
168
+ persistRestoration = false,
162
169
  ): Promise<void> {
163
170
  if (
164
171
  !context ||
165
172
  generation !== this.activationGeneration ||
166
- context !== this.context ||
167
- this.list().length === 0
173
+ context !== this.context
168
174
  ) {
169
175
  return;
170
176
  }
177
+ if (this.list().length === 0) {
178
+ if (persistRestoration) this.persist();
179
+ else this.onRefresh();
180
+ return;
181
+ }
171
182
  const snapshot = await getSnapshot(this.client);
172
183
  if (generation !== this.activationGeneration || context !== this.context)
173
184
  return;
174
185
  const { changed, completions } = this.state.reconcile(
175
186
  snapshot,
176
- process.env["HERDR_PANE_ID"],
187
+ this.selfPaneId,
177
188
  );
178
- if (changed) this.persist();
179
- else renderAgentWidget(this.context, this.list());
189
+ if (changed || persistRestoration) this.persist();
190
+ else this.onRefresh();
180
191
  for (const completion of completions) {
181
192
  void this.report(completion);
182
193
  }