@howaboua/pi-shepherdr 0.2.23 → 0.2.25

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.
Files changed (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
package/src/messages.ts DELETED
@@ -1,637 +0,0 @@
1
- import { hostname } from "node:os";
2
- import {
3
- type ExtensionAPI,
4
- type ExtensionContext,
5
- getMarkdownTheme,
6
- } from "@earendil-works/pi-coding-agent";
7
- import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
8
- import type { BoardBinding } from "@howaboua/pi-agent-board/integration";
9
- import { activityTask } from "./activity.js";
10
- import { sendPolicyMessage } from "./delivery.js";
11
- import { getCurrentPane, getSnapshot } from "./herdr.js";
12
- import type { HerdrConnection } from "./herdr-client.js";
13
- import { readExtensionMessage } from "./remote/shepherdr-session.mjs";
14
- import type {
15
- ExtensionMessage,
16
- FocusRequest,
17
- LatestAssistant,
18
- MachineStatus,
19
- MonitoredAgent,
20
- PaneInfo,
21
- PeerMessage,
22
- ScopedMonitoredAgent,
23
- SettledAgentStatus,
24
- } from "./types.js";
25
-
26
- const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
27
- const REALTIME_VOICE_PROMPT_CHANNEL =
28
- "@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
29
- const MAX_REALTIME_VOICE_PROMPT_BYTES = 8 * 1_024;
30
- const DELEGATED_WORKER_GUIDANCE =
31
- "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.";
32
-
33
- function focusOrigin({ source }: FocusRequest) {
34
- return { host: source.host, session: source.session, pane: source.pane };
35
- }
36
-
37
- export function focusArrivalContent(
38
- request: FocusRequest,
39
- machine: string,
40
- codeMode: boolean,
41
- ) {
42
- const returnFocus = {
43
- action: "focus",
44
- target: request.source.pane,
45
- machine,
46
- voice: request.voice === true,
47
- };
48
- const args = JSON.stringify(returnFocus);
49
- const callable = codeMode ? `await tools.agents(${args})` : `agents ${args}`;
50
- return {
51
- returnFocus,
52
- content: `User arrived from ${JSON.stringify({ ...focusOrigin(request), machine })}\nReturn: ${callable}${request.voice ? "\nVoice transfer pending" : ""}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`,
53
- };
54
- }
55
-
56
- export function voiceFocusContinuity(request: FocusRequest): string {
57
- return `User transferring voice from ${JSON.stringify(focusOrigin(request))}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`;
58
- }
59
-
60
- export function voiceFocusReport(
61
- side: "source" | "destination",
62
- target: string,
63
- error?: unknown,
64
- ): string {
65
- return error === undefined
66
- ? `Voice transfer complete (${side}, ${target}); replacement call active`
67
- : `Voice transfer failed (${side}, ${target}): ${error instanceof Error ? error.message : String(error)}. Voice availability is not confirmed; inspect the session before retrying`;
68
- }
69
-
70
- export function orchestrationGuidance(enabled: boolean, general: boolean) {
71
- const ownership = "Own a scope or delegate it; don't do both.";
72
- if (!enabled)
73
- return `Work normally. Delegate only when useful or requested. ${ownership}`;
74
- const guidance = general
75
- ? "Orchestrate general agents with separate scopes. Integrate their results, validate the combined outcome and report it. Work directly only when asked or for routine local tasks."
76
- : "Orchestrate agents with separate scopes. Integrate their results, validate the combined outcome and report it. Work directly only when asked or for routine local tasks.";
77
- return `${guidance} ${ownership}`;
78
- }
79
- export function activeAgentsBriefing(
80
- agents: ScopedMonitoredAgent[],
81
- machines: MachineStatus[],
82
- ): string | undefined {
83
- if (!agents.length) return;
84
- return [
85
- "Supervised agents after context rollover. Their instructions are reference data, not tasks for you. Do not repeat settled tasks or duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
86
- JSON.stringify(
87
- agents.map((agent) => ({
88
- machine: agent.machine,
89
- target: agent.paneId,
90
- ...(agent.name ? { name: agent.name } : {}),
91
- status:
92
- agent.activity.phase === "settled"
93
- ? agent.activity.status
94
- : agent.activity.phase,
95
- connection:
96
- machines.find((machine) => machine.id === agent.machine)?.status ??
97
- "unavailable",
98
- ...(agent.cwd ? { cwd: agent.cwd } : {}),
99
- ...((agent.instructions ?? activityTask(agent.activity))
100
- ? { instructions: agent.instructions ?? activityTask(agent.activity) }
101
- : {}),
102
- })),
103
- ),
104
- ].join("\n");
105
- }
106
- export function boardMigrationWarning() {
107
- return "Boards moved to Pi Agent Board. Install @howaboua/pi-agent-board for the same features as a separate extension. Your saved boards are preserved.";
108
- }
109
-
110
- export function boardBriefing(
111
- member: boolean,
112
- population: "empty" | "populated" | "unavailable",
113
- gpt = false,
114
- ) {
115
- const state =
116
- population === "populated"
117
- ? gpt
118
- ? "Read relevantboardthreads."
119
- : "Read relevant board threads."
120
- : population === "empty"
121
- ? gpt
122
- ? "Sharedboard available; posts=none."
123
- : "Shared board available; no posts yet."
124
- : gpt
125
- ? "Sharedboard status unavailable; board help→retry read when available."
126
- : "Shared board status unavailable. Check board help and retry reading when available.";
127
- const setup = member
128
- ? gpt
129
- ? "Root owns setup; follow assignedtask."
130
- : "The root agent owns setup; follow your assigned task."
131
- : "";
132
- if (gpt)
133
- return [
134
- state,
135
- setup,
136
- "Posts=work-changing ownership/decisions/findings/blockers only. Existingthread replies; link≠repeat. Personalcheckpoints→notes. No ack/statusspam/duplicate completionreports. Assignments/urgentmessages→agents.",
137
- "Channels=workstreams; threads=topics. Reuse relevantchannels≠catchalls. Newchannel requires distinctcoordinationpurpose; never task/result announcement only.",
138
- ]
139
- .filter(Boolean)
140
- .join(" ");
141
- return (
142
- [
143
- state,
144
- setup,
145
- "Post only new information that changes another agent's work: ownership, decisions, findings or blockers. Reply in existing threads; link rather than repeat. Keep personal checkpoints in notes. Skip acknowledgements, routine status and duplicated completion reports. Use agents for assignments and urgent messages.",
146
- ]
147
- .filter(Boolean)
148
- .join(" ") +
149
- "\n\nChannels group shared workstreams; threads group topics. Reuse a relevant channel, not a catch-all. Create a channel only for a distinct coordination need, never just to announce a task or result."
150
- );
151
- }
152
-
153
- export function attachmentMessage(
154
- controllerContextAgent?: string,
155
- boardAgent?: string,
156
- ) {
157
- return {
158
- customType: "herdr-agent-attachment",
159
- content: [
160
- ...(controllerContextAgent
161
- ? [
162
- `Controller notes/history: ${controllerContextAgent}; own context unchanged`,
163
- ]
164
- : []),
165
- ...(boardAgent ? [`Shared board: ${boardAgent}`] : []),
166
- ].join("\n"),
167
- display: true,
168
- };
169
- }
170
-
171
- export function detachmentMessage(
172
- controllerContextAgent?: string,
173
- board?: BoardBinding,
174
- ) {
175
- return {
176
- customType: "herdr-agent-detachment",
177
- content: [
178
- ...(controllerContextAgent
179
- ? [
180
- `Detached controller: ${controllerContextAgent}; checkpoints read-only, history unavailable; own context unchanged`,
181
- ]
182
- : []),
183
- ...(board
184
- ? [`Board restored: ${board.boardId} as ${board.agentName}`]
185
- : []),
186
- ].join("\n"),
187
- display: true,
188
- };
189
- }
190
-
191
- function xml(value: string): string {
192
- return value
193
- .replaceAll("&", "&")
194
- .replaceAll("<", "&lt;")
195
- .replaceAll(">", "&gt;")
196
- .replaceAll('"', "&quot;")
197
- .replaceAll("'", "&apos;");
198
- }
199
-
200
- interface AgentEventLabels {
201
- tab?: string;
202
- workspace?: string;
203
- }
204
-
205
- export function agentSource(agent: PaneInfo, labels: AgentEventLabels) {
206
- const paneName = agent.label || agent.title;
207
- return {
208
- pane: agent.pane_id,
209
- workspace: agent.workspace_id,
210
- tab: agent.tab_id,
211
- ...(agent.name ? { name: agent.name } : {}),
212
- ...(paneName ? { pane_name: paneName } : {}),
213
- ...(labels.workspace ? { workspace_name: labels.workspace } : {}),
214
- ...(labels.tab ? { tab_name: labels.tab } : {}),
215
- };
216
- }
217
-
218
- function sourceAttributes(source: Record<string, string | undefined>): string {
219
- return Object.entries(source)
220
- .filter((entry): entry is [string, string] => entry[1] !== undefined)
221
- .map(
222
- ([key, value]) =>
223
- `${key}="${xml(value).replaceAll("\n", "&#10;").replaceAll("\r", "&#13;")}"`,
224
- )
225
- .join(" ");
226
- }
227
-
228
- export async function attributeAgentPrompt(
229
- client: HerdrConnection,
230
- message: string,
231
- kind: "message" | "task",
232
- ): Promise<PeerMessage> {
233
- const [pane, snapshot] = await Promise.all([
234
- getCurrentPane(client),
235
- getSnapshot(client),
236
- ]);
237
- const workspace = snapshot.workspaces.find(
238
- (workspace) => workspace.workspace_id === pane.workspace_id,
239
- )?.label;
240
- const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
241
- const source = {
242
- kind,
243
- host: hostname(),
244
- session: process.env["HERDR_SESSION"] || "default",
245
- ...agentSource(pane, {
246
- ...(workspace ? { workspace } : {}),
247
- ...(tab ? { tab } : {}),
248
- }),
249
- };
250
- return {
251
- sender: `<herdr_sender ${sourceAttributes(source)} />`,
252
- text: message,
253
- ...(kind === "task" ? { context: DELEGATED_WORKER_GUIDANCE } : {}),
254
- };
255
- }
256
-
257
- interface AgentEventOptions {
258
- agent: PaneInfo;
259
- agentToolName: string;
260
- codeMode?: boolean;
261
- extensionMessages?: ExtensionMessage[];
262
- blockedMessage?: string;
263
- labels: AgentEventLabels;
264
- machine: string;
265
- machineLabel: string;
266
- operatorPrefix: string;
267
- record: MonitoredAgent;
268
- reply?: LatestAssistant;
269
- status: SettledAgentStatus | "extension-message";
270
- }
271
-
272
- interface AgentEventDetails {
273
- extensionMessages?: ExtensionMessage[];
274
- blockedOn?: string;
275
- cwd?: string;
276
- machine: string;
277
- machineLabel?: string;
278
- name?: string;
279
- paneId: string;
280
- response?: string;
281
- state: "blocked" | "failed" | "finished" | "extension-message";
282
- tab?: string;
283
- task?: string;
284
- workspace?: string;
285
- }
286
-
287
- function eventExtensionMessages(
288
- value: unknown,
289
- ): ExtensionMessage[] | undefined {
290
- if (!Array.isArray(value)) return undefined;
291
- const messages = value.map((message) => {
292
- if (typeof message !== "object" || message === null) return undefined;
293
- return readExtensionMessage({ ...message, version: 1, state: "pending" });
294
- });
295
- return messages.every((message) => message !== undefined)
296
- ? messages
297
- : undefined;
298
- }
299
-
300
- function boundedVoicePrompt(prompt: string): string {
301
- const bytes = new TextEncoder().encode(prompt);
302
- if (bytes.byteLength <= MAX_REALTIME_VOICE_PROMPT_BYTES) return prompt;
303
- return new TextDecoder()
304
- .decode(bytes.subarray(0, MAX_REALTIME_VOICE_PROMPT_BYTES), {
305
- stream: true,
306
- })
307
- .trimEnd();
308
- }
309
-
310
- function agentVoicePrompt(details: AgentEventDetails): string {
311
- const lines = [
312
- `Worker: ${details.machineLabel ?? details.machine} / ${details.name?.trim() || "unnamed"}`,
313
- `State: ${details.state}`,
314
- ];
315
- if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
316
- let instruction: string;
317
- if (details.state === "blocked" || details.state === "extension-message") {
318
- instruction =
319
- details.state === "extension-message"
320
- ? "Briefly tell the user what this worker reports."
321
- : "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
322
- if (details.blockedOn?.trim())
323
- lines.push(`Reason:\n${details.blockedOn.trim()}`);
324
- if (details.extensionMessages)
325
- lines.push(
326
- ...details.extensionMessages.map((message) => message.message),
327
- );
328
- } else {
329
- instruction =
330
- details.state === "failed"
331
- ? "Briefly tell the user that this monitored worker failed and include useful detail from its report."
332
- : "Briefly tell the user what this monitored worker found or completed; do not merely announce that it finished.";
333
- if (details.response?.trim())
334
- lines.push(`Report:\n${details.response.trim()}`);
335
- }
336
- return boundedVoicePrompt(`${instruction}\n\n${lines.join("\n\n")}`);
337
- }
338
-
339
- function announceAgentEvent(
340
- pi: ExtensionAPI,
341
- candidateId: string,
342
- prompt: string,
343
- ): void {
344
- const id =
345
- new TextEncoder().encode(candidateId).byteLength <= 160
346
- ? candidateId
347
- : "pi-shepherdr:worker";
348
- pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: true, prompt });
349
- pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
350
- }
351
-
352
- export function announcePeerMessage(
353
- pi: ExtensionAPI,
354
- message: PeerMessage,
355
- ): void {
356
- const source = Object.fromEntries(
357
- Array.from(
358
- message.sender.matchAll(/ ([a-z_]+)="([^"]*)"/g),
359
- ([, key, value]) => [key, value],
360
- ),
361
- );
362
- if (source["kind"] !== "message" || message.text.startsWith("/")) return;
363
- announceAgentEvent(
364
- pi,
365
- `pi-shepherdr:${source["host"] ?? "local"}:${source["pane"] ?? "peer"}`,
366
- boundedVoicePrompt(
367
- `Briefly tell the user the useful update from this peer.\n\nPeer: ${source["host"] ?? "local"} / ${source["name"] || source["pane"] || "unnamed"}\n\nUpdate:\n${message.text.trim()}`,
368
- ),
369
- );
370
- }
371
-
372
- function operatorCommand(operatorPrefix: string, command: string): string {
373
- return `\`${operatorPrefix} ${command}\``;
374
- }
375
-
376
- function blockedOperatorHint(
377
- agentToolName: string,
378
- machine: string,
379
- operatorPrefix: string,
380
- paneId: string,
381
- ): string {
382
- 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.`;
383
- }
384
-
385
- function failedOperatorHint(
386
- agentToolName: string,
387
- machine: string,
388
- operatorPrefix: string,
389
- paneId: string,
390
- ): string {
391
- 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.`;
392
- }
393
-
394
- function eventDetails(value: unknown): AgentEventDetails | undefined {
395
- if (typeof value !== "object" || value === null) return undefined;
396
- const details = value as Record<string, unknown>;
397
- if (
398
- typeof details["paneId"] !== "string" ||
399
- (details["machine"] !== undefined &&
400
- typeof details["machine"] !== "string") ||
401
- (details["state"] !== "blocked" &&
402
- details["state"] !== "extension-message" &&
403
- details["state"] !== "failed" &&
404
- details["state"] !== "finished")
405
- ) {
406
- return undefined;
407
- }
408
- const optional = (field: keyof AgentEventDetails) =>
409
- typeof details[field] === "string"
410
- ? { [field]: details[field] as string }
411
- : {};
412
- const extensionMessages = eventExtensionMessages(
413
- details["extensionMessages"],
414
- );
415
- return {
416
- machine:
417
- typeof details["machine"] === "string" ? details["machine"] : "local",
418
- paneId: details["paneId"],
419
- state: details["state"],
420
- ...(extensionMessages ? { extensionMessages } : {}),
421
- ...optional("blockedOn"),
422
- ...optional("cwd"),
423
- ...optional("machineLabel"),
424
- ...optional("name"),
425
- ...optional("response"),
426
- ...optional("tab"),
427
- ...optional("task"),
428
- ...optional("workspace"),
429
- };
430
- }
431
-
432
- function agentEvent(options: AgentEventOptions): {
433
- content: string;
434
- details: AgentEventDetails;
435
- } {
436
- const {
437
- agent,
438
- agentToolName,
439
- codeMode,
440
- extensionMessages,
441
- blockedMessage,
442
- labels,
443
- machine,
444
- machineLabel,
445
- operatorPrefix,
446
- record,
447
- reply,
448
- status,
449
- } = options;
450
- const task = activityTask(record.activity);
451
- const blocked = status === "blocked";
452
- const notification = status === "extension-message";
453
- const failed = !blocked && reply?.stopReason === "error";
454
- const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
455
- const tag = notification
456
- ? "herdr_agent_extension_message"
457
- : blocked
458
- ? "herdr_agent_blocked"
459
- : failed
460
- ? "herdr_agent_failed"
461
- : "herdr_agent_result";
462
- const attributes = sourceAttributes({
463
- machine,
464
- machine_name: machineLabel !== machine ? machineLabel : undefined,
465
- ...agentSource(agent, labels),
466
- name: agent.name ?? record.name,
467
- directory: cwd,
468
- });
469
- const lines = [`<${tag} ${attributes}>`];
470
- if (task && !notification) lines.push(`<task>${xml(task)}</task>`);
471
- if (blockedMessage) {
472
- lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
473
- }
474
- for (const message of extensionMessages ?? []) {
475
- lines.push(message.message);
476
- if (message.reply !== undefined) {
477
- const request = {
478
- action: "reply",
479
- machine,
480
- target: agent.pane_id,
481
- extension: message.extension,
482
- id: message.id,
483
- message: message.reply,
484
- };
485
- const call = codeMode
486
- ? `await tools.${agentToolName}(${JSON.stringify(request)})`
487
- : `${agentToolName} ${JSON.stringify(request)}`;
488
- lines.push(`Reply: ${call}`);
489
- }
490
- }
491
- if (blocked) {
492
- lines.push(
493
- `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
494
- );
495
- }
496
- if (failed) {
497
- lines.push(
498
- `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
499
- );
500
- }
501
- if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
502
- lines.push(`</${tag}>`);
503
-
504
- return {
505
- content: lines.join("\n"),
506
- details: {
507
- machine,
508
- machineLabel,
509
- paneId: agent.pane_id,
510
- state: notification
511
- ? "extension-message"
512
- : blocked
513
- ? "blocked"
514
- : failed
515
- ? "failed"
516
- : "finished",
517
- ...(extensionMessages ? { extensionMessages } : {}),
518
- ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
519
- ...(cwd ? { cwd } : {}),
520
- ...(labels.workspace ? { workspace: labels.workspace } : {}),
521
- ...(labels.tab ? { tab: labels.tab } : {}),
522
- ...(task && !notification ? { task } : {}),
523
- ...(blockedMessage ? { blockedOn: blockedMessage } : {}),
524
- ...(reply ? { response: reply.text } : {}),
525
- },
526
- };
527
- }
528
-
529
- export function injectAgentEvent(
530
- pi: ExtensionAPI,
531
- _ctx: ExtensionContext,
532
- options: AgentEventOptions,
533
- ): void {
534
- const tools = pi.getActiveTools();
535
- const message = agentEvent({
536
- ...options,
537
- codeMode:
538
- tools.includes("exec") ||
539
- tools.includes("code") ||
540
- tools.includes("notebook"),
541
- });
542
- const delivery = { triggerTurn: true, deliverAs: "steer" as const };
543
- sendPolicyMessage(
544
- pi,
545
- {
546
- customType: AGENT_EVENT_MESSAGE_TYPE,
547
- content: message.content,
548
- details: message.details,
549
- display: true,
550
- },
551
- delivery,
552
- );
553
- announceAgentEvent(
554
- pi,
555
- `pi-shepherdr:${message.details.machine}:${message.details.paneId}`,
556
- agentVoicePrompt(message.details),
557
- );
558
- }
559
-
560
- export function registerAgentEventRenderer(pi: ExtensionAPI): void {
561
- pi.registerMessageRenderer<AgentEventDetails>(
562
- AGENT_EVENT_MESSAGE_TYPE,
563
- (message, { expanded, outputPad }, theme) => {
564
- const details = eventDetails(message.details);
565
- if (!details) {
566
- const box = new Box(outputPad, 1, (value) =>
567
- theme.bg("customMessageBg", value),
568
- );
569
- box.addChild(
570
- new Text(
571
- typeof message.content === "string"
572
- ? message.content
573
- : "Herdr agent event unavailable",
574
- 0,
575
- 0,
576
- ),
577
- );
578
- return box;
579
- }
580
- const blocked = details?.state === "blocked";
581
- const failed = details?.state === "failed";
582
- const notification = details.state === "extension-message";
583
- const agentIdentity = details?.name
584
- ? `${details.name} (${details.paneId})`
585
- : (details?.paneId ?? "unknown");
586
- const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
587
- const title = theme.fg(
588
- blocked || failed ? "error" : "success",
589
- `Herdr agent ${identity} · ${notification ? "extension message pending" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
590
- );
591
- const location = [details?.workspace, details?.tab]
592
- .filter(Boolean)
593
- .join(" / ");
594
- const metadata = [location, details?.cwd].filter(Boolean).join(" · ");
595
- const box = new Box(outputPad, 1, (value) =>
596
- theme.bg("customMessageBg", value),
597
- );
598
- box.addChild(new Text(title, 0, 0));
599
- if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
600
- if (blocked || notification) {
601
- box.addChild(new Spacer(1));
602
- box.addChild(
603
- new Text(
604
- theme.fg(
605
- "warning",
606
- details?.blockedOn ??
607
- (notification
608
- ? "Extension message pending"
609
- : "Agent needs input or approval"),
610
- ),
611
- 0,
612
- 0,
613
- ),
614
- );
615
- if (details.extensionMessages && expanded) {
616
- for (const message of details.extensionMessages) {
617
- box.addChild(new Spacer(1));
618
- box.addChild(
619
- new Markdown(message.message, 0, 0, getMarkdownTheme()),
620
- );
621
- }
622
- }
623
- }
624
- if (expanded && details?.task) {
625
- box.addChild(new Spacer(1));
626
- box.addChild(new Text(theme.fg("muted", "Task"), 0, 0));
627
- box.addChild(new Markdown(details.task, 0, 0, getMarkdownTheme()));
628
- }
629
- if (details?.response) {
630
- box.addChild(new Spacer(1));
631
- box.addChild(new Text(theme.fg("muted", "Response"), 0, 0));
632
- box.addChild(new Markdown(details.response, 0, 0, getMarkdownTheme()));
633
- }
634
- return box;
635
- },
636
- );
637
- }