@howaboua/pi-shepherdr 0.1.6 → 0.2.1

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
@@ -1,3 +1,4 @@
1
+ import { hostname } from "node:os";
1
2
  import {
2
3
  type ExtensionAPI,
3
4
  type ExtensionContext,
@@ -5,11 +6,14 @@ import {
5
6
  } from "@earendil-works/pi-coding-agent";
6
7
  import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
7
8
  import { activityTask } from "./activity.js";
8
- import { sendPolicyMessage } from "./delivery.js";
9
+ import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
10
+ import { getCurrentPane, getSnapshot } from "./herdr.js";
11
+ import type { HerdrConnection } from "./herdr-client.js";
9
12
  import type {
10
13
  LatestAssistant,
11
14
  MonitoredAgent,
12
15
  PaneInfo,
16
+ PeerMessage,
13
17
  PendingAsk,
14
18
  SettledAgentStatus,
15
19
  } from "./types.js";
@@ -33,6 +37,57 @@ interface AgentEventLabels {
33
37
  workspace?: string;
34
38
  }
35
39
 
40
+ export function agentSource(agent: PaneInfo, labels: AgentEventLabels) {
41
+ const paneName = agent.label || agent.title;
42
+ return {
43
+ pane: agent.pane_id,
44
+ workspace: agent.workspace_id,
45
+ tab: agent.tab_id,
46
+ ...(agent.name ? { name: agent.name } : {}),
47
+ ...(paneName ? { pane_name: paneName } : {}),
48
+ ...(labels.workspace ? { workspace_name: labels.workspace } : {}),
49
+ ...(labels.tab ? { tab_name: labels.tab } : {}),
50
+ };
51
+ }
52
+
53
+ function sourceAttributes(source: Record<string, string | undefined>): string {
54
+ return Object.entries(source)
55
+ .filter((entry): entry is [string, string] => entry[1] !== undefined)
56
+ .map(
57
+ ([key, value]) =>
58
+ `${key}="${xml(value).replaceAll("\n", "&#10;").replaceAll("\r", "&#13;")}"`,
59
+ )
60
+ .join(" ");
61
+ }
62
+
63
+ export async function attributeAgentPrompt(
64
+ client: HerdrConnection,
65
+ message: string,
66
+ kind: "message" | "task",
67
+ ): Promise<PeerMessage> {
68
+ const [pane, snapshot] = await Promise.all([
69
+ getCurrentPane(client),
70
+ getSnapshot(client),
71
+ ]);
72
+ const workspace = snapshot.workspaces.find(
73
+ (workspace) => workspace.workspace_id === pane.workspace_id,
74
+ )?.label;
75
+ const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
76
+ const source = {
77
+ kind,
78
+ host: hostname(),
79
+ session: process.env["HERDR_SESSION"] || "default",
80
+ ...agentSource(pane, {
81
+ ...(workspace ? { workspace } : {}),
82
+ ...(tab ? { tab } : {}),
83
+ }),
84
+ };
85
+ return {
86
+ sender: `<herdr_sender ${sourceAttributes(source)} />`,
87
+ text: message,
88
+ };
89
+ }
90
+
36
91
  interface AgentEventOptions {
37
92
  agent: PaneInfo;
38
93
  agentToolName: string;
@@ -40,6 +95,7 @@ interface AgentEventOptions {
40
95
  blockedMessage?: string;
41
96
  labels: AgentEventLabels;
42
97
  machine: string;
98
+ machineLabel: string;
43
99
  operatorPrefix: string;
44
100
  record: MonitoredAgent;
45
101
  reply?: LatestAssistant;
@@ -51,6 +107,7 @@ interface AgentEventDetails {
51
107
  blockedOn?: string;
52
108
  cwd?: string;
53
109
  machine: string;
110
+ machineLabel?: string;
54
111
  name?: string;
55
112
  paneId: string;
56
113
  response?: string;
@@ -128,7 +185,7 @@ function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
128
185
 
129
186
  function agentVoicePrompt(details: AgentEventDetails): string {
130
187
  const lines = [
131
- `Worker: ${details.machine} / ${details.name?.trim() || "unnamed"}`,
188
+ `Worker: ${details.machineLabel ?? details.machine} / ${details.name?.trim() || "unnamed"}`,
132
189
  `State: ${details.state}`,
133
190
  ];
134
191
  if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
@@ -224,6 +281,7 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
224
281
  ...(ask ? { ask } : {}),
225
282
  ...optional("blockedOn"),
226
283
  ...optional("cwd"),
284
+ ...optional("machineLabel"),
227
285
  ...optional("name"),
228
286
  ...optional("response"),
229
287
  ...optional("tab"),
@@ -243,6 +301,7 @@ function agentEvent(options: AgentEventOptions): {
243
301
  blockedMessage,
244
302
  labels,
245
303
  machine,
304
+ machineLabel,
246
305
  operatorPrefix,
247
306
  record,
248
307
  reply,
@@ -257,14 +316,13 @@ function agentEvent(options: AgentEventOptions): {
257
316
  : failed
258
317
  ? "herdr_agent_failed"
259
318
  : "herdr_agent_result";
260
- const attributes = [
261
- `machine="${xml(machine)}"`,
262
- `pane="${xml(agent.pane_id)}"`,
263
- record.name ? `name="${xml(record.name)}"` : undefined,
264
- cwd ? `directory="${xml(cwd)}"` : undefined,
265
- ]
266
- .filter(Boolean)
267
- .join(" ");
319
+ const attributes = sourceAttributes({
320
+ machine,
321
+ machine_name: machineLabel !== machine ? machineLabel : undefined,
322
+ ...agentSource(agent, labels),
323
+ name: agent.name ?? record.name,
324
+ directory: cwd,
325
+ });
268
326
  const lines = [`<${tag} ${attributes}>`];
269
327
  if (task) lines.push(`<task>${xml(task)}</task>`);
270
328
  if (blockedMessage) {
@@ -292,10 +350,11 @@ function agentEvent(options: AgentEventOptions): {
292
350
  content: lines.join("\n"),
293
351
  details: {
294
352
  machine,
353
+ machineLabel,
295
354
  paneId: agent.pane_id,
296
355
  state: blocked ? "blocked" : failed ? "failed" : "finished",
297
356
  ...(blocked && ask ? { ask } : {}),
298
- ...(record.name ? { name: record.name } : {}),
357
+ ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
299
358
  ...(cwd ? { cwd } : {}),
300
359
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
301
360
  ...(labels.tab ? { tab: labels.tab } : {}),
@@ -312,8 +371,9 @@ export function injectAgentEvent(
312
371
  options: AgentEventOptions,
313
372
  ): void {
314
373
  const message = agentEvent(options);
315
- const delivery = ctx.isIdle()
316
- ? { triggerTurn: true, deliverAs: "steer" as const }
374
+ const idle = ctx.isIdle();
375
+ const delivery = idle
376
+ ? { triggerTurn: false, deliverAs: "steer" as const }
317
377
  : { deliverAs: "steer" as const };
318
378
  sendPolicyMessage(
319
379
  pi,
@@ -325,6 +385,7 @@ export function injectAgentEvent(
325
385
  },
326
386
  delivery,
327
387
  );
388
+ if (idle) startPreparedIdleTurn(pi, ctx);
328
389
  announceAgentEvent(pi, message.details);
329
390
  }
330
391
 
@@ -353,7 +414,7 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
353
414
  const agentIdentity = details?.name
354
415
  ? `${details.name} (${details.paneId})`
355
416
  : (details?.paneId ?? "unknown");
356
- const identity = `${details.machine} / ${agentIdentity}`;
417
+ const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
357
418
  const title = theme.fg(
358
419
  blocked || failed ? "error" : "success",
359
420
  `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
@@ -88,30 +88,13 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
88
88
  };
89
89
  }
90
90
 
91
- function legacyActivity(
92
- record: Record<string, unknown>,
93
- ): AgentActivity | undefined {
94
- if (!isAgentStatus(record["lastStatus"])) return undefined;
95
- const task = optionalString(record, "task");
96
- if (task === false) return undefined;
97
- if (record["lastStatus"] === "working") {
98
- return { phase: "working", ...(task ? { task } : {}) };
99
- }
100
- if (!task) return { phase: "settled", status: record["lastStatus"] };
101
- return {
102
- attemptId: `restored:${String(record["terminalId"])}`,
103
- phase: "submitting",
104
- previous: { phase: "settled", status: record["lastStatus"] },
105
- task,
106
- };
107
- }
108
-
109
91
  export function parseMonitoredAgent(
110
92
  value: unknown,
111
93
  ): MonitoredAgent | undefined {
112
94
  if (typeof value !== "object" || value === null) return undefined;
113
95
  const record = value as Record<string, unknown>;
114
96
  if (
97
+ (record["scope"] !== "task" && record["scope"] !== "persistent") ||
115
98
  typeof record["paneId"] !== "string" ||
116
99
  typeof record["terminalId"] !== "string" ||
117
100
  typeof record["workspaceId"] !== "string" ||
@@ -122,7 +105,7 @@ export function parseMonitoredAgent(
122
105
  const cwd = optionalString(record, "cwd");
123
106
  const lastAssistantId = optionalString(record, "lastAssistantId");
124
107
  const name = optionalString(record, "name");
125
- const activity = parsedActivity(record["activity"]) ?? legacyActivity(record);
108
+ const activity = parsedActivity(record["activity"]);
126
109
  if (
127
110
  cwd === false ||
128
111
  lastAssistantId === false ||
@@ -132,6 +115,7 @@ export function parseMonitoredAgent(
132
115
  return undefined;
133
116
  }
134
117
  return {
118
+ scope: record["scope"],
135
119
  activity,
136
120
  paneId: record["paneId"],
137
121
  terminalId: record["terminalId"],
@@ -146,10 +130,12 @@ export function parseMonitoredAgent(
146
130
  export function recordForPanel(
147
131
  panel: PaneInfo,
148
132
  activity: AgentActivity,
133
+ scope: MonitoredAgent["scope"],
149
134
  lastAssistantId?: string,
150
135
  ): MonitoredAgent {
151
136
  const cwd = panel.foreground_cwd ?? panel.cwd;
152
137
  return {
138
+ scope,
153
139
  activity,
154
140
  paneId: panel.pane_id,
155
141
  terminalId: panel.terminal_id,
@@ -166,6 +152,7 @@ export function sameMonitorRecord(
166
152
  right: MonitoredAgent,
167
153
  ): boolean {
168
154
  return (
155
+ left.scope === right.scope &&
169
156
  left.paneId === right.paneId &&
170
157
  left.terminalId === right.terminalId &&
171
158
  left.workspaceId === right.workspaceId &&
@@ -44,9 +44,11 @@ interface StatusResult {
44
44
 
45
45
  export class MonitorState {
46
46
  private readonly agents = new Map<string, MonitoredAgent>();
47
+ private readonly pendingSubmissions = new Set<string>();
47
48
 
48
49
  restore(values: unknown[], controllingPaneId?: string): number {
49
50
  this.agents.clear();
51
+ this.pendingSubmissions.clear();
50
52
  let dropped = 0;
51
53
  for (const value of values) {
52
54
  const record = parseMonitoredAgent(value);
@@ -79,10 +81,6 @@ export class MonitorState {
79
81
  return this.agents.get(terminalId);
80
82
  }
81
83
 
82
- isMonitored(paneId: string): boolean {
83
- return this.byPane(paneId) !== undefined;
84
- }
85
-
86
84
  watch(
87
85
  panel: PaneInfo,
88
86
  lastAssistantId?: string,
@@ -100,6 +98,7 @@ export class MonitorState {
100
98
  const record = recordForPanel(
101
99
  panel,
102
100
  activity,
101
+ reportSettled ? "persistent" : (existing?.scope ?? "task"),
103
102
  reportCurrent
104
103
  ? undefined
105
104
  : (existing?.lastAssistantId ?? lastAssistantId),
@@ -129,10 +128,14 @@ export class MonitorState {
129
128
  `prompt submission to ${record.name ?? paneId} is still unresolved`,
130
129
  );
131
130
  }
131
+ if (record.activity.phase === "working" && record.activity.task) {
132
+ throw new Error("Agent already has delegated work; use send for updates");
133
+ }
132
134
  const attempt = {
133
135
  attemptId: randomUUID(),
134
136
  terminalId: record.terminalId,
135
137
  };
138
+ this.pendingSubmissions.add(attempt.attemptId);
136
139
  this.agents.set(record.terminalId, {
137
140
  ...record,
138
141
  activity: {
@@ -146,7 +149,12 @@ export class MonitorState {
146
149
  return attempt;
147
150
  }
148
151
 
152
+ endSubmission(attempt: WorkAttempt | undefined): void {
153
+ if (attempt) this.pendingSubmissions.delete(attempt.attemptId);
154
+ }
155
+
149
156
  acceptWork(attempt: WorkAttempt | undefined): boolean {
157
+ this.endSubmission(attempt);
150
158
  const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
151
159
  if (
152
160
  !record ||
@@ -170,6 +178,7 @@ export class MonitorState {
170
178
  }
171
179
 
172
180
  rejectWork(attempt: WorkAttempt | undefined): boolean {
181
+ this.endSubmission(attempt);
173
182
  const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
174
183
  if (
175
184
  !record ||
@@ -188,6 +197,13 @@ export class MonitorState {
188
197
  applyStatus(paneId: string, status: AgentStatus): StatusResult {
189
198
  const record = this.byPane(paneId);
190
199
  if (!record) return { changed: false };
200
+ // Submission owns the transaction until its receipt decides whether this
201
+ // is delegated work at all. The caller reconciles after accepting it.
202
+ if (
203
+ record.activity.phase === "submitting" &&
204
+ this.pendingSubmissions.has(record.activity.attemptId)
205
+ )
206
+ return { changed: false };
191
207
  if (status === "working") {
192
208
  const task = activityTask(record.activity);
193
209
  const attemptId =
@@ -283,7 +299,12 @@ export class MonitorState {
283
299
 
284
300
  let activity = record.activity;
285
301
  let completion: Omit<CompletionCandidate, "record"> | undefined;
286
- if (panel.agent_status === "working") {
302
+ if (
303
+ activity.phase === "submitting" &&
304
+ this.pendingSubmissions.has(activity.attemptId)
305
+ ) {
306
+ // Keep the rollback state until submission is acknowledged.
307
+ } else if (panel.agent_status === "working") {
287
308
  const task = activityTask(activity);
288
309
  const attemptId =
289
310
  activity.phase === "settled" ? undefined : activity.attemptId;
@@ -322,7 +343,12 @@ export class MonitorState {
322
343
  activity = { phase: "settled", status: panel.agent_status };
323
344
  }
324
345
 
325
- const updated = recordForPanel(panel, activity, record.lastAssistantId);
346
+ const updated = recordForPanel(
347
+ panel,
348
+ activity,
349
+ record.scope,
350
+ record.lastAssistantId,
351
+ );
326
352
  if (!sameMonitorRecord(record, updated)) changed = true;
327
353
  if (record.terminalId !== updated.terminalId) {
328
354
  this.agents.delete(record.terminalId);
@@ -356,6 +382,10 @@ export class MonitorState {
356
382
  ): boolean {
357
383
  const record = this.byTerminal(terminalId);
358
384
  if (!record || activityTask(record.activity) !== task) return false;
385
+ if (record.scope === "task" && status !== "blocked") {
386
+ this.agents.delete(terminalId);
387
+ return true;
388
+ }
359
389
  this.agents.set(terminalId, {
360
390
  ...record,
361
391
  activity: { phase: "settled", status },
package/src/monitor.ts CHANGED
@@ -4,7 +4,7 @@ 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 { type HerdrConnection, isHerdrResponseError } from "./herdr-client.js";
7
+ import { type HerdrConnection, isDispatchRejected } 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";
@@ -25,6 +25,7 @@ import type {
25
25
  interface AgentMonitorOptions {
26
26
  client: HerdrConnection;
27
27
  machine: string;
28
+ machineLabel: () => string;
28
29
  onChange: () => void;
29
30
  onRefresh: () => void;
30
31
  operatorPrefix: string;
@@ -57,10 +58,16 @@ export class AgentMonitor {
57
58
  pi,
58
59
  this.client,
59
60
  this.state,
60
- () => this.persist(),
61
+ () => {
62
+ this.persist();
63
+ this.refreshAfterEvent();
64
+ },
61
65
  options.reader,
62
- this.machine,
63
- options.operatorPrefix,
66
+ {
67
+ machine: this.machine,
68
+ label: options.machineLabel,
69
+ operatorPrefix: options.operatorPrefix,
70
+ },
64
71
  );
65
72
  this.events = new MonitorEvents({
66
73
  client: this.client,
@@ -105,10 +112,6 @@ export class AgentMonitor {
105
112
  return this.state.list();
106
113
  }
107
114
 
108
- isMonitored(paneId: string): boolean {
109
- return this.state.isMonitored(paneId);
110
- }
111
-
112
115
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
113
116
  return this.watchPanel(panel, true);
114
117
  }
@@ -187,10 +190,12 @@ export class AgentMonitor {
187
190
  attempt: WorkAttempt | undefined,
188
191
  error: unknown,
189
192
  ): Promise<void> {
190
- if (isHerdrResponseError(error)) {
193
+ if (isDispatchRejected(error)) {
191
194
  this.rejectWork(attempt);
192
195
  return;
193
196
  }
197
+ // An unknown acknowledgement must not leave status processing suspended.
198
+ this.state.endSubmission(attempt);
194
199
  try {
195
200
  await this.reconcileNow();
196
201
  } catch (reconcileError) {
@@ -0,0 +1,237 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { createServer, type Socket } from "node:net";
4
+ import type {
5
+ ExtensionAPI,
6
+ ExtensionContext,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
9
+ import { getCurrentPane } from "./herdr.js";
10
+ import { HerdrClient } from "./herdr-client.js";
11
+ import {
12
+ MAX_PEER_FRAME_BYTES,
13
+ peerInboxPath,
14
+ } from "./remote/shepherdr-peer.mjs";
15
+
16
+ export function registerPeerInbox(pi: ExtensionAPI): void {
17
+ let close: (() => Promise<void>) | undefined;
18
+ let running = false;
19
+ pi.on("agent_start", () => {
20
+ running = true;
21
+ });
22
+ pi.on("agent_settled", () => {
23
+ running = false;
24
+ });
25
+ pi.on("session_start", async (_event, ctx) => {
26
+ await close?.();
27
+ close = undefined;
28
+ running = false;
29
+ if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
30
+ return;
31
+ close = await openInbox(pi, ctx, () => running);
32
+ });
33
+ pi.on("session_shutdown", async () => {
34
+ await close?.();
35
+ close = undefined;
36
+ running = false;
37
+ });
38
+ }
39
+
40
+ async function openInbox(
41
+ pi: ExtensionAPI,
42
+ ctx: ExtensionContext,
43
+ isRunning: () => boolean,
44
+ ): Promise<() => Promise<void>> {
45
+ const sessionFile = ctx.sessionManager.getSessionFile();
46
+ if (!sessionFile)
47
+ throw new Error("Shepherdr peer delivery requires a saved Pi session");
48
+ const pane = await getCurrentPane(new HerdrClient());
49
+ const token = randomBytes(32).toString("hex");
50
+ const path = peerInboxPath(sessionFile, pane.terminal_id);
51
+ const temporary = `${path}.${token}.tmp`;
52
+ const sockets = new Set<Socket>();
53
+ let active = true;
54
+ const server = createServer((socket) => {
55
+ sockets.add(socket);
56
+ socket.setEncoding("utf8");
57
+ socket.setTimeout(10_000, () => socket.destroy());
58
+ socket.on("error", () => socket.destroy());
59
+ socket.on("close", () => sockets.delete(socket));
60
+ let buffer = "";
61
+ let received = false;
62
+ socket.on("data", (chunk: string) => {
63
+ if (received) return;
64
+ buffer += chunk;
65
+ if (Buffer.byteLength(buffer) > MAX_PEER_FRAME_BYTES) {
66
+ socket.destroy();
67
+ return;
68
+ }
69
+ const newline = buffer.indexOf("\n");
70
+ if (newline < 0) return;
71
+ received = true;
72
+ let request: Record<string, unknown>;
73
+ try {
74
+ const value: unknown = JSON.parse(buffer.slice(0, newline));
75
+ if (!value || typeof value !== "object" || Array.isArray(value))
76
+ throw new Error("Invalid request");
77
+ request = value as Record<string, unknown>;
78
+ } catch {
79
+ socket.destroy();
80
+ return;
81
+ }
82
+ const reply = (value: object) =>
83
+ socket.end(
84
+ `${JSON.stringify({ protocol: 1, id: request["id"], ...value })}\n`,
85
+ );
86
+ if (
87
+ !active ||
88
+ request["protocol"] !== 1 ||
89
+ request["token"] !== token ||
90
+ request["sessionFile"] !== sessionFile ||
91
+ request["terminalId"] !== pane.terminal_id ||
92
+ ctx.sessionManager.getSessionFile() !== sessionFile ||
93
+ typeof request["id"] !== "string" ||
94
+ typeof request["text"] !== "string" ||
95
+ !request["text"].trim() ||
96
+ typeof request["sender"] !== "string" ||
97
+ !/^<herdr_sender [^\n]+ \/>$/.test(request["sender"]) ||
98
+ (request["context"] !== undefined &&
99
+ typeof request["context"] !== "string")
100
+ ) {
101
+ reply({
102
+ ok: false,
103
+ rejected: true,
104
+ error: "Peer delivery rejected: stale session or invalid request",
105
+ });
106
+ return;
107
+ }
108
+ let submitted = false;
109
+ try {
110
+ const idle = ctx.isIdle();
111
+ // Manual compaction/tree navigation can be busy without an agent
112
+ // loop to consume steering. Do not acknowledge a stranded message.
113
+ if (!idle && !isRunning()) {
114
+ reply({
115
+ ok: false,
116
+ rejected: true,
117
+ error: "Target is changing context; retry after it settles",
118
+ });
119
+ return;
120
+ }
121
+ const text = request["text"];
122
+ const sender = request["context"]
123
+ ? `${request["sender"]}\n${request["context"]}`
124
+ : request["sender"];
125
+ if (text.startsWith("/")) {
126
+ // Match only Pi's extension-command boundary, not its argument or
127
+ // skill/template parsers. Extension commands may never start a turn.
128
+ const space = text.indexOf(" ");
129
+ const name = text.slice(1, space < 0 ? undefined : space);
130
+ const command = pi
131
+ .getCommands()
132
+ .some(
133
+ (entry) => entry.source === "extension" && entry.name === name,
134
+ );
135
+ const submit = () => {
136
+ submitted = true;
137
+ sendPolicyMessage(
138
+ pi,
139
+ {
140
+ customType: "herdr-agent-source",
141
+ content: sender,
142
+ display: true,
143
+ },
144
+ { triggerTurn: false, deliverAs: "steer" },
145
+ );
146
+ pi.sendUserMessage(text, {
147
+ expandPromptTemplates: true,
148
+ deliverAs: "steer",
149
+ });
150
+ };
151
+ if (idle && !command) startPreparedIdleTurn(pi, ctx, submit);
152
+ else submit();
153
+ reply({ ok: true, command });
154
+ return;
155
+ }
156
+ submitted = true;
157
+ sendPolicyMessage(
158
+ pi,
159
+ {
160
+ customType: "herdr-agent-message",
161
+ content: `${sender}\n${text}`,
162
+ display: true,
163
+ },
164
+ idle
165
+ ? { triggerTurn: false, deliverAs: "steer" }
166
+ : { deliverAs: "steer" },
167
+ );
168
+ // Appending then claiming the shared kickoff also coalesces arrivals
169
+ // during async preparation, when Pi still reports itself idle.
170
+ if (idle) startPreparedIdleTurn(pi, ctx);
171
+ reply({ ok: true, command: false });
172
+ } catch (error) {
173
+ reply({
174
+ ok: false,
175
+ rejected: !submitted,
176
+ error: `${submitted ? "Peer delivery failed; inspect the target before retrying" : "Peer delivery rejected"}: ${error instanceof Error ? error.message : String(error)}`,
177
+ });
178
+ }
179
+ });
180
+ });
181
+ server.maxConnections = 16;
182
+ const stop = async () => {
183
+ if (!active) return;
184
+ active = false;
185
+ for (const socket of sockets) socket.destroy();
186
+ await new Promise<void>((resolve) => server.close(() => resolve()));
187
+ try {
188
+ const current: unknown = JSON.parse(await readFile(path, "utf8"));
189
+ if (
190
+ current &&
191
+ typeof current === "object" &&
192
+ "token" in current &&
193
+ current.token === token
194
+ )
195
+ await unlink(path);
196
+ } catch (error) {
197
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
198
+ }
199
+ };
200
+ try {
201
+ await new Promise<void>((resolve, reject) => {
202
+ server.once("error", reject);
203
+ server.listen(0, "127.0.0.1", () => {
204
+ server.removeListener("error", reject);
205
+ resolve();
206
+ });
207
+ });
208
+ server.on("error", (error) => {
209
+ ctx.ui.notify(
210
+ `Shepherdr peer receiver failed: ${error.message}`,
211
+ "error",
212
+ );
213
+ void stop().catch((failure: unknown) =>
214
+ ctx.ui.notify(String(failure), "error"),
215
+ );
216
+ });
217
+ const address = server.address();
218
+ if (!address || typeof address === "string")
219
+ throw new Error("Shepherdr peer receiver has no address");
220
+ await writeFile(
221
+ temporary,
222
+ JSON.stringify({ protocol: 1, port: address.port, token }),
223
+ { mode: 0o600, flag: "wx" },
224
+ );
225
+ await rename(temporary, path);
226
+ } catch (error) {
227
+ try {
228
+ await unlink(temporary).catch((failure: NodeJS.ErrnoException) => {
229
+ if (failure.code !== "ENOENT") throw failure;
230
+ });
231
+ } finally {
232
+ await stop();
233
+ }
234
+ throw error;
235
+ }
236
+ return stop;
237
+ }