@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
@@ -0,0 +1,195 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { activityTask } from "../activity.js";
6
+ import { sendPolicyMessage } from "../delivery.js";
7
+ import type {
8
+ ExtensionMessage,
9
+ LatestAssistant,
10
+ MonitoredAgent,
11
+ PaneInfo,
12
+ SettledAgentStatus,
13
+ } from "../types.js";
14
+ import {
15
+ type AgentEventLabels,
16
+ agentSource,
17
+ sourceAttributes,
18
+ xml,
19
+ } from "./attribution.js";
20
+ import {
21
+ AGENT_EVENT_MESSAGE_TYPE,
22
+ type AgentEventDetails,
23
+ } from "./event-details.js";
24
+ import { agentVoicePrompt, announceAgentEvent } from "./voice-announcements.js";
25
+
26
+ interface AgentEventOptions {
27
+ agent: PaneInfo;
28
+ agentToolName: string;
29
+ codeMode?: boolean;
30
+ extensionMessages?: ExtensionMessage[];
31
+ blockedMessage?: string;
32
+ labels: AgentEventLabels;
33
+ machine: string;
34
+ machineLabel: string;
35
+ operatorPrefix: string;
36
+ record: MonitoredAgent;
37
+ reply?: LatestAssistant;
38
+ status: SettledAgentStatus | "extension-message";
39
+ }
40
+
41
+ function operatorCommand(operatorPrefix: string, command: string): string {
42
+ return `\`${operatorPrefix} ${command}\``;
43
+ }
44
+
45
+ function blockedOperatorHint(
46
+ agentToolName: string,
47
+ machine: string,
48
+ operatorPrefix: string,
49
+ paneId: string,
50
+ core: boolean,
51
+ ): string {
52
+ return `Inspect first with ${operatorCommand(operatorPrefix, core ? `read ${paneId}` : `agent read ${paneId} --source visible`)}; respond through ${agentToolName} with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, core ? `keys ${paneId} <keys>` : `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
53
+ }
54
+
55
+ function failedOperatorHint(
56
+ agentToolName: string,
57
+ machine: string,
58
+ operatorPrefix: string,
59
+ paneId: string,
60
+ core: boolean,
61
+ ): string {
62
+ return `Inspect with ${operatorCommand(operatorPrefix, core ? `read ${paneId} --lines 80` : `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.`;
63
+ }
64
+
65
+ function agentEvent(options: AgentEventOptions): {
66
+ content: string;
67
+ details: AgentEventDetails;
68
+ } {
69
+ const {
70
+ agent,
71
+ agentToolName,
72
+ codeMode,
73
+ extensionMessages,
74
+ blockedMessage,
75
+ labels,
76
+ machine,
77
+ machineLabel,
78
+ operatorPrefix,
79
+ record,
80
+ reply,
81
+ status,
82
+ } = options;
83
+ const task = activityTask(record.activity);
84
+ const blocked = status === "blocked";
85
+ const notification = status === "extension-message";
86
+ const failed = !blocked && reply?.stopReason === "error";
87
+ const operatorTarget =
88
+ agent.backend === "core" && machine !== "local"
89
+ ? `${machineLabel}/${agent.pane_id}`
90
+ : agent.pane_id;
91
+ const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
92
+ const tag = notification
93
+ ? "herdr_agent_extension_message"
94
+ : blocked
95
+ ? "herdr_agent_blocked"
96
+ : failed
97
+ ? "herdr_agent_failed"
98
+ : "herdr_agent_result";
99
+ const attributes = sourceAttributes({
100
+ machine,
101
+ machine_name: machineLabel !== machine ? machineLabel : undefined,
102
+ ...agentSource(agent, labels),
103
+ name: agent.name ?? record.name,
104
+ directory: cwd,
105
+ });
106
+ const lines = [`<${tag} ${attributes}>`];
107
+ if (task && !notification) lines.push(`<task>${xml(task)}</task>`);
108
+ if (blockedMessage) {
109
+ lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
110
+ }
111
+ for (const message of extensionMessages ?? []) {
112
+ lines.push(message.message);
113
+ if (message.reply !== undefined) {
114
+ const request = {
115
+ action: "reply",
116
+ machine,
117
+ target: agent.pane_id,
118
+ extension: message.extension,
119
+ id: message.id,
120
+ message: message.reply,
121
+ };
122
+ const call = codeMode
123
+ ? `await tools.${agentToolName}(${JSON.stringify(request)})`
124
+ : `${agentToolName} ${JSON.stringify(request)}`;
125
+ lines.push(`Reply: ${call}`);
126
+ }
127
+ }
128
+ if (blocked) {
129
+ lines.push(
130
+ `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, operatorTarget, agent.backend === "core"))}</operator_hint>`,
131
+ );
132
+ }
133
+ if (failed) {
134
+ lines.push(
135
+ `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, operatorTarget, agent.backend === "core"))}</operator_hint>`,
136
+ );
137
+ }
138
+ if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
139
+ lines.push(`</${tag}>`);
140
+
141
+ return {
142
+ content: lines.join("\n"),
143
+ details: {
144
+ machine,
145
+ machineLabel,
146
+ paneId: agent.pane_id,
147
+ state: notification
148
+ ? "extension-message"
149
+ : blocked
150
+ ? "blocked"
151
+ : failed
152
+ ? "failed"
153
+ : "finished",
154
+ ...(extensionMessages ? { extensionMessages } : {}),
155
+ ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
156
+ ...(cwd ? { cwd } : {}),
157
+ ...(labels.workspace ? { workspace: labels.workspace } : {}),
158
+ ...(labels.tab ? { tab: labels.tab } : {}),
159
+ ...(task && !notification ? { task } : {}),
160
+ ...(blockedMessage ? { blockedOn: blockedMessage } : {}),
161
+ ...(reply ? { response: reply.text } : {}),
162
+ },
163
+ };
164
+ }
165
+
166
+ export function injectAgentEvent(
167
+ pi: ExtensionAPI,
168
+ _ctx: ExtensionContext,
169
+ options: AgentEventOptions,
170
+ ): void {
171
+ const tools = pi.getActiveTools();
172
+ const message = agentEvent({
173
+ ...options,
174
+ codeMode:
175
+ tools.includes("exec") ||
176
+ tools.includes("code") ||
177
+ tools.includes("notebook"),
178
+ });
179
+ const delivery = { triggerTurn: true, deliverAs: "steer" as const };
180
+ sendPolicyMessage(
181
+ pi,
182
+ {
183
+ customType: AGENT_EVENT_MESSAGE_TYPE,
184
+ content: message.content,
185
+ details: message.details,
186
+ display: true,
187
+ },
188
+ delivery,
189
+ );
190
+ announceAgentEvent(
191
+ pi,
192
+ `pi-shepherdr:${message.details.machine}:${message.details.paneId}`,
193
+ agentVoicePrompt(message.details),
194
+ );
195
+ }
@@ -0,0 +1,47 @@
1
+ import type { FocusRequest } from "../types.js";
2
+
3
+ function focusOrigin({ source }: FocusRequest) {
4
+ return {
5
+ host: source.host,
6
+ session: source.session,
7
+ ...(source.backend === "core"
8
+ ? { terminal: source.terminal }
9
+ : { pane: source.pane }),
10
+ };
11
+ }
12
+
13
+ export function focusArrivalContent(
14
+ request: FocusRequest,
15
+ machine: string,
16
+ codeMode: boolean,
17
+ ) {
18
+ const returnFocus = {
19
+ action: "focus",
20
+ target:
21
+ request.source.backend === "core"
22
+ ? request.source.terminal
23
+ : request.source.pane!,
24
+ machine,
25
+ voice: request.voice === true,
26
+ };
27
+ const args = JSON.stringify(returnFocus);
28
+ const callable = codeMode ? `await tools.agents(${args})` : `agents ${args}`;
29
+ return {
30
+ returnFocus,
31
+ 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}` : ""}`,
32
+ };
33
+ }
34
+
35
+ export function voiceFocusContinuity(request: FocusRequest): string {
36
+ return `User transferring voice from ${JSON.stringify(focusOrigin(request))}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`;
37
+ }
38
+
39
+ export function voiceFocusReport(
40
+ side: "source" | "destination",
41
+ target: string,
42
+ error?: unknown,
43
+ ): string {
44
+ return error === undefined
45
+ ? `Voice transfer complete (${side}, ${target}); replacement call active`
46
+ : `Voice transfer failed (${side}, ${target}): ${error instanceof Error ? error.message : String(error)}. Voice availability is not confirmed; inspect the session before retrying`;
47
+ }
@@ -0,0 +1,83 @@
1
+ import { activityTask } from "../activity.js";
2
+ import type { MachineStatus, ScopedMonitoredAgent } from "../types.js";
3
+
4
+ export function orchestrationGuidance(enabled: boolean, general: boolean) {
5
+ const ownership = "Own a scope or delegate it; don't do both.";
6
+ if (!enabled)
7
+ return `Work normally. Delegate only when useful or requested. ${ownership}`;
8
+ const guidance = general
9
+ ? "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."
10
+ : "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.";
11
+ return `${guidance} ${ownership}`;
12
+ }
13
+ export function activeAgentsBriefing(
14
+ agents: ScopedMonitoredAgent[],
15
+ machines: MachineStatus[],
16
+ ): string | undefined {
17
+ if (!agents.length) return;
18
+ return [
19
+ "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.",
20
+ JSON.stringify(
21
+ agents.map((agent) => ({
22
+ machine: agent.machine,
23
+ target: agent.paneId,
24
+ ...(agent.name ? { name: agent.name } : {}),
25
+ status:
26
+ agent.activity.phase === "settled"
27
+ ? agent.activity.status
28
+ : agent.activity.phase,
29
+ connection:
30
+ machines.find((machine) => machine.id === agent.machine)?.status ??
31
+ "unavailable",
32
+ ...(agent.cwd ? { cwd: agent.cwd } : {}),
33
+ ...((agent.instructions ?? activityTask(agent.activity))
34
+ ? { instructions: agent.instructions ?? activityTask(agent.activity) }
35
+ : {}),
36
+ })),
37
+ ),
38
+ ].join("\n");
39
+ }
40
+ export function boardMigrationWarning() {
41
+ 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.";
42
+ }
43
+
44
+ export function boardBriefing(
45
+ member: boolean,
46
+ population: "empty" | "populated" | "unavailable",
47
+ gpt = false,
48
+ ) {
49
+ const state =
50
+ population === "populated"
51
+ ? "Read relevant board threads."
52
+ : population === "empty"
53
+ ? gpt
54
+ ? "Shared board available; posts=none."
55
+ : "Shared board available; no posts yet."
56
+ : gpt
57
+ ? "Shared board status unavailable; board help→retry read when available."
58
+ : "Shared board status unavailable. Check board help and retry reading when available.";
59
+ const setup = member
60
+ ? gpt
61
+ ? "Root owns setup; follow assigned task."
62
+ : "The root agent owns setup; follow your assigned task."
63
+ : "";
64
+ if (gpt)
65
+ return [
66
+ state,
67
+ setup,
68
+ "Posts=work-changing ownership/decisions/findings/blockers only. Existing thread replies; link≠repeat. Personal checkpoints→notes. No ack/status spam/duplicate completion reports. Assignments/urgent messages→agents.",
69
+ "Channels=workstreams; threads=topics. Reuse relevant channels≠catchalls. New channel requires distinct coordination purpose; never task/result announcement only.",
70
+ ]
71
+ .filter(Boolean)
72
+ .join(" ");
73
+ return (
74
+ [
75
+ state,
76
+ setup,
77
+ "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.",
78
+ ]
79
+ .filter(Boolean)
80
+ .join(" ") +
81
+ "\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."
82
+ );
83
+ }
@@ -0,0 +1,89 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ getMarkdownTheme,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
6
+ import {
7
+ AGENT_EVENT_MESSAGE_TYPE,
8
+ type AgentEventDetails,
9
+ eventDetails,
10
+ } from "./event-details.js";
11
+
12
+ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
13
+ pi.registerMessageRenderer<AgentEventDetails>(
14
+ AGENT_EVENT_MESSAGE_TYPE,
15
+ (message, { expanded, outputPad }, theme) => {
16
+ const details = eventDetails(message.details);
17
+ if (!details) {
18
+ const box = new Box(outputPad, 1, (value) =>
19
+ theme.bg("customMessageBg", value),
20
+ );
21
+ box.addChild(
22
+ new Text(
23
+ typeof message.content === "string"
24
+ ? message.content
25
+ : "Herdr agent event unavailable",
26
+ 0,
27
+ 0,
28
+ ),
29
+ );
30
+ return box;
31
+ }
32
+ const blocked = details?.state === "blocked";
33
+ const failed = details?.state === "failed";
34
+ const notification = details.state === "extension-message";
35
+ const agentIdentity = details?.name
36
+ ? `${details.name} (${details.paneId})`
37
+ : (details?.paneId ?? "unknown");
38
+ const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
39
+ const title = theme.fg(
40
+ blocked || failed ? "error" : "success",
41
+ `Herdr agent ${identity} · ${notification ? "extension message pending" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
42
+ );
43
+ const location = [details?.workspace, details?.tab]
44
+ .filter(Boolean)
45
+ .join(" / ");
46
+ const metadata = [location, details?.cwd].filter(Boolean).join(" · ");
47
+ const box = new Box(outputPad, 1, (value) =>
48
+ theme.bg("customMessageBg", value),
49
+ );
50
+ box.addChild(new Text(title, 0, 0));
51
+ if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
52
+ if (blocked || notification) {
53
+ box.addChild(new Spacer(1));
54
+ box.addChild(
55
+ new Text(
56
+ theme.fg(
57
+ "warning",
58
+ details?.blockedOn ??
59
+ (notification
60
+ ? "Extension message pending"
61
+ : "Agent needs input or approval"),
62
+ ),
63
+ 0,
64
+ 0,
65
+ ),
66
+ );
67
+ if (details.extensionMessages && expanded) {
68
+ for (const message of details.extensionMessages) {
69
+ box.addChild(new Spacer(1));
70
+ box.addChild(
71
+ new Markdown(message.message, 0, 0, getMarkdownTheme()),
72
+ );
73
+ }
74
+ }
75
+ }
76
+ if (expanded && details?.task) {
77
+ box.addChild(new Spacer(1));
78
+ box.addChild(new Text(theme.fg("muted", "Task"), 0, 0));
79
+ box.addChild(new Markdown(details.task, 0, 0, getMarkdownTheme()));
80
+ }
81
+ if (details?.response) {
82
+ box.addChild(new Spacer(1));
83
+ box.addChild(new Text(theme.fg("muted", "Response"), 0, 0));
84
+ box.addChild(new Markdown(details.response, 0, 0, getMarkdownTheme()));
85
+ }
86
+ return box;
87
+ },
88
+ );
89
+ }
@@ -0,0 +1,79 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { PeerMessage } from "../types.js";
3
+ import type { AgentEventDetails } from "./event-details.js";
4
+
5
+ const REALTIME_VOICE_PROMPT_CHANNEL =
6
+ "@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
7
+ const MAX_REALTIME_VOICE_PROMPT_BYTES = 8 * 1_024;
8
+
9
+ function boundedVoicePrompt(prompt: string): string {
10
+ const bytes = new TextEncoder().encode(prompt);
11
+ if (bytes.byteLength <= MAX_REALTIME_VOICE_PROMPT_BYTES) return prompt;
12
+ return new TextDecoder()
13
+ .decode(bytes.subarray(0, MAX_REALTIME_VOICE_PROMPT_BYTES), {
14
+ stream: true,
15
+ })
16
+ .trimEnd();
17
+ }
18
+
19
+ export function agentVoicePrompt(details: AgentEventDetails): string {
20
+ const lines = [
21
+ `Worker: ${details.machineLabel ?? details.machine} / ${details.name?.trim() || "unnamed"}`,
22
+ `State: ${details.state}`,
23
+ ];
24
+ if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
25
+ let instruction: string;
26
+ if (details.state === "blocked" || details.state === "extension-message") {
27
+ instruction =
28
+ details.state === "extension-message"
29
+ ? "Briefly tell the user what this worker reports."
30
+ : "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
31
+ if (details.blockedOn?.trim())
32
+ lines.push(`Reason:\n${details.blockedOn.trim()}`);
33
+ if (details.extensionMessages)
34
+ lines.push(
35
+ ...details.extensionMessages.map((message) => message.message),
36
+ );
37
+ } else {
38
+ instruction =
39
+ details.state === "failed"
40
+ ? "Briefly tell the user that this monitored worker failed and include useful detail from its report."
41
+ : "Briefly tell the user what this monitored worker found or completed; do not merely announce that it finished.";
42
+ if (details.response?.trim())
43
+ lines.push(`Report:\n${details.response.trim()}`);
44
+ }
45
+ return boundedVoicePrompt(`${instruction}\n\n${lines.join("\n\n")}`);
46
+ }
47
+
48
+ export function announceAgentEvent(
49
+ pi: ExtensionAPI,
50
+ candidateId: string,
51
+ prompt: string,
52
+ ): void {
53
+ const id =
54
+ new TextEncoder().encode(candidateId).byteLength <= 160
55
+ ? candidateId
56
+ : "pi-shepherdr:worker";
57
+ pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: true, prompt });
58
+ pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
59
+ }
60
+
61
+ export function announcePeerMessage(
62
+ pi: ExtensionAPI,
63
+ message: PeerMessage,
64
+ ): void {
65
+ const source = Object.fromEntries(
66
+ Array.from(
67
+ message.sender.matchAll(/ ([a-z_]+)="([^"]*)"/g),
68
+ ([, key, value]) => [key, value],
69
+ ),
70
+ );
71
+ if (source["kind"] !== "message" || message.text.startsWith("/")) return;
72
+ announceAgentEvent(
73
+ pi,
74
+ `pi-shepherdr:${source["host"] ?? "local"}:${source["pane"] ?? "peer"}`,
75
+ boundedVoicePrompt(
76
+ `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()}`,
77
+ ),
78
+ );
79
+ }
@@ -97,8 +97,9 @@ export function parseMonitoredAgent(
97
97
  (record["scope"] !== "task" && record["scope"] !== "persistent") ||
98
98
  typeof record["paneId"] !== "string" ||
99
99
  typeof record["terminalId"] !== "string" ||
100
- typeof record["workspaceId"] !== "string" ||
101
- typeof record["tabId"] !== "string"
100
+ (record["workspaceId"] !== undefined &&
101
+ typeof record["workspaceId"] !== "string") ||
102
+ (record["tabId"] !== undefined && typeof record["tabId"] !== "string")
102
103
  ) {
103
104
  return undefined;
104
105
  }
@@ -132,8 +133,10 @@ export function parseMonitoredAgent(
132
133
  activity,
133
134
  paneId: record["paneId"],
134
135
  terminalId: record["terminalId"],
135
- workspaceId: record["workspaceId"],
136
- tabId: record["tabId"],
136
+ ...(record["workspaceId"] !== undefined
137
+ ? { workspaceId: record["workspaceId"] }
138
+ : {}),
139
+ ...(record["tabId"] !== undefined ? { tabId: record["tabId"] } : {}),
137
140
  ...(cwd ? { cwd } : {}),
138
141
  ...(lastAssistantId ? { lastAssistantId } : {}),
139
142
  ...(notifiedExtensionMessages ? { notifiedExtensionMessages } : {}),
@@ -154,8 +157,8 @@ export function recordForPanel(
154
157
  activity,
155
158
  paneId: panel.pane_id,
156
159
  terminalId: panel.terminal_id,
157
- workspaceId: panel.workspace_id,
158
- tabId: panel.tab_id,
160
+ ...(panel.workspace_id ? { workspaceId: panel.workspace_id } : {}),
161
+ ...(panel.tab_id ? { tabId: panel.tab_id } : {}),
159
162
  ...(panel.name ? { name: panel.name } : {}),
160
163
  ...(cwd ? { cwd } : {}),
161
164
  ...(lastAssistantId ? { lastAssistantId } : {}),
package/src/monitor.ts CHANGED
@@ -5,7 +5,7 @@ import type {
5
5
  import { isSettledStatus } from "./activity.js";
6
6
  import { getSnapshot } from "./herdr.js";
7
7
  import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
8
- import { injectAgentEvent } from "./messages.js";
8
+ import { injectAgentEvent } from "./messages/events.js";
9
9
  import { parseMonitorEvent } from "./monitor-event.js";
10
10
  import { MonitorEvents } from "./monitor-events.js";
11
11
  import { MonitorExtensionMessages } from "./monitor-extension-messages.js";
@@ -15,7 +15,7 @@ import {
15
15
  type ClaimedSettlement,
16
16
  SettlementReporter,
17
17
  type SettlementRequest,
18
- } from "./settlement.js";
18
+ } from "./settlement/index.js";
19
19
  import type {
20
20
  ExtensionReply,
21
21
  HerdrEvent,
@@ -51,6 +51,8 @@ export class AgentMonitor {
51
51
  private readonly extensionMessages: MonitorExtensionMessages;
52
52
  private context: ExtensionContext | undefined;
53
53
  private activationGeneration = 0;
54
+ private coreReconcile: Promise<void> | undefined;
55
+ private coreDirty = false;
54
56
 
55
57
  constructor(pi: ExtensionAPI, options: AgentMonitorOptions) {
56
58
  this.client = options.client;
@@ -130,6 +132,8 @@ export class AgentMonitor {
130
132
 
131
133
  deactivate(): void {
132
134
  this.activationGeneration += 1;
135
+ this.coreDirty = false;
136
+ this.coreReconcile = undefined;
133
137
  this.context = undefined;
134
138
  this.events.stop();
135
139
  this.extensionMessages.stop();
@@ -292,6 +296,33 @@ export class AgentMonitor {
292
296
  }
293
297
 
294
298
  private handleEvent(event: HerdrEvent): void {
299
+ if (event.event === "core.reconcile") {
300
+ const generation = this.activationGeneration;
301
+ const context = this.context;
302
+ this.coreDirty = true;
303
+ if (this.coreReconcile) return;
304
+ this.coreReconcile = Promise.resolve()
305
+ .then(async () => {
306
+ while (this.coreDirty && generation === this.activationGeneration) {
307
+ this.coreDirty = false;
308
+ await this.reconcile(generation, context);
309
+ }
310
+ })
311
+ .catch((error) => {
312
+ if (generation === this.activationGeneration) {
313
+ this.context?.ui.notify(
314
+ `Core monitoring reconciliation failed: ${String(error)}`,
315
+ "warning",
316
+ );
317
+ void this.events.retry().catch(() => undefined);
318
+ }
319
+ })
320
+ .finally(() => {
321
+ if (generation === this.activationGeneration)
322
+ this.coreReconcile = undefined;
323
+ });
324
+ return;
325
+ }
295
326
  const parsed = parseMonitorEvent(event);
296
327
  if (!parsed) return;
297
328
  if (parsed.type === "closed") {
@@ -51,6 +51,17 @@ export function createPeerCommands(pi: ExtensionAPI) {
51
51
  };
52
52
  return {
53
53
  available,
54
+ closeIdle(
55
+ ctx: ExtensionContext,
56
+ run: (ctx: ExtensionCommandContext) => Promise<void>,
57
+ ): void {
58
+ const token = randomUUID();
59
+ pending.set(token, {
60
+ session: ctx.sessionManager.getSessionFile(),
61
+ run,
62
+ });
63
+ pi.sendUserMessage(`/herdr ${token}`, { expandPromptTemplates: true });
64
+ },
54
65
  async handle(args: string, ctx: ExtensionCommandContext): Promise<boolean> {
55
66
  const intent = pending.get(args);
56
67
  if (!intent) return false;