@howaboua/pi-shepherdr 0.2.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Deliver peer messages directly to Pi without submitting unsent human drafts.
6
+
7
+ - Preserve slash-command arguments and use the target session's skill and prompt-template expansion.
8
+ - Return submission-only acknowledgements for registered extension commands instead of waiting for an assistant reply.
9
+
10
+ Requires Pi 0.84.4 or newer. Update and reload Shepherdr on both controllers and workers, and Pi Codex Conversion where installed.
11
+
12
+ - Fixed idle agent reports and manual checkpoint requests to preserve prompt preparation, coalesce concurrent continuations, and process reports arriving during turn settlement.
13
+
14
+ - Manual Compact reuses notes saved in the last completed turn for Local, Tree, and Remote notes-only windows, avoiding a redundant checkpoint turn. Explicit compaction instructions still request a checkpoint.
15
+ - Compact tool output now offers Off, On, and Minimal. Minimal keeps nested tool results and an expand hint while hiding the trailing Code / Notebook text preview until expanded. Existing Off and On settings keep their behavior.
16
+ - Shepherdr help makes local routing explicit: agent calls default to the host running Pi, while unfiltered discovery searches all machines. Remote calls use profile IDs, not machine labels or hostnames.
17
+ - Fixed Shepherdr startup after a Herdr executable replacement leaves a stale ` (deleted)` path. Recovery silently uses the replacement at the same location. Command failures remain visible and no longer imply that Herdr is outdated.
18
+
3
19
  ## 0.2.0
4
20
 
5
21
  - Shepherdr now reads existing Herdr machine profiles and requires Herdr 0.9 or newer. Manage profiles in Herdr; `shepherdr.json`, old machine aliases and their saved watches are no longer used.
package/README.md CHANGED
@@ -14,7 +14,7 @@ With Pi Codex's compatible custom developer-message API active, asynchronous wor
14
14
  pi install npm:@howaboua/pi-shepherdr
15
15
  ```
16
16
 
17
- Requires Pi 0.84.3 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
17
+ Requires Pi 0.84.4 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
18
18
 
19
19
  ```bash
20
20
  herdr integration install pi
@@ -22,7 +22,7 @@ herdr integration install pi
22
22
 
23
23
  Do not load Pi Codex's example `agents.toml` custom tool alongside Shepherdr; they own the same agent surface.
24
24
 
25
- Pi Codex 3.0.25 or newer is optional. Without it, Shepherdr remains a normal Pi extension.
25
+ Pi Codex is optional. Without it, Shepherdr remains a normal Pi extension.
26
26
 
27
27
  ## Enable orchestration
28
28
 
@@ -36,7 +36,7 @@ The command only records one visible guidance message without triggering a turn.
36
36
 
37
37
  Shepherdr reads Herdr's existing machine profiles and connects enabled profiles at session startup. Manage profiles in Herdr. `/herdr connect [profile-id]` refreshes the catalog and retries failed connections or incomplete monitoring without dropping working connections. A catalog refresh stops watches for disabled or removed profiles without stopping remote agents.
38
38
 
39
- Profiles belong to the host running Pi, not the laptop or desktop displaying its terminal. Each profile targets one remote session. Agent calls use the opaque profile ID returned by `list`; `local` means Pi's current server. Renaming a profile changes its label, not its routing identity.
39
+ Profiles belong to the host running Pi, not the machine displaying its terminal. Omit `machine` for local agent calls. `list` and `find` search all machines unless filtered. Explicit `local` also means the host running Pi. For remote calls, use the opaque profile ID returned by `list`, not its label or hostname. Renaming a profile changes its label, not its routing identity.
40
40
 
41
41
  Remote machines connect over noninteractive SSH. The target needs `node` on its SSH PATH, Herdr 0.9 or newer, the Herdr Pi integration and a running Herdr session. Shepherdr installs one helper at `~/.pi/agent/shepherdr.mjs` on each remote, runs it only for the connection lifetime and leaves no remote daemon behind. Herdr's multi-machine UI does not expose a cross-machine automation socket, so Shepherdr still owns its remote transport and Pi transcript reads.
42
42
 
@@ -75,7 +75,11 @@ Cancelling a blocking call does not kill its worker. The waiter detaches and the
75
75
 
76
76
  Prompts sent through `agents` identify peer messages versus delegated tasks and include the sender's host, session, workspace, tab and pane identity, with current names. Reports include source workspace and tab names too. Raw `herdr agent prompt` calls bypass this attribution. These are runtime locations, not the desktop window showing a pane.
77
77
 
78
- Idle task prompts retain Pi's normal user kickoff and extension preparation. When the receiving agent is already running and Pi Codex developer delivery is active, Shepherdr routes attributed messages into that prepared run as developer steering. Without it, messages remain normal prompts. Install Shepherdr on receiving agents as well as controllers for this delivery.
78
+ Messages sent through `agents` bypass the receiving Pi editor, preserving unsent drafts. Update and reload Shepherdr on receiving agents as well as controllers. If a receiver is unavailable, delivery fails without pasting into its terminal. Raw `herdr agent prompt` still uses terminal input and does not provide this protection.
79
+
80
+ Messages beginning with `/` use the target Pi session's command, skill and prompt-template expansion, with sender attribution kept out of the arguments. Skills and templates retain normal task waiting. Registered extension commands return `commandSubmitted: true` without waiting or adding a task watch, even through `spawn` or `assign`; submission does not confirm command success. TUI-only commands such as `/model` and `/settings` are not available through this route. When Pi Codex Conversion is installed, update and reload it too.
81
+
82
+ Idle messages start a prepared user turn. Messages arriving during a run use steering, promoted to developer messages when Pi Codex developer delivery is active. Otherwise they remain ordinary Pi custom messages.
79
83
 
80
84
  For `answer` inside Code or Notebook Mode, update Pi Ask on workers together with Shepherdr on controllers.
81
85
 
package/index.ts CHANGED
@@ -6,6 +6,7 @@ import { registerAgentController } from "./src/controller.js";
6
6
  import { registerDeveloperDelivery } from "./src/delivery.js";
7
7
  import { AgentFleet } from "./src/fleet.js";
8
8
  import { registerAgentEventRenderer } from "./src/messages.js";
9
+ import { registerPeerInbox } from "./src/peer-inbox.js";
9
10
  import { installAgentProfiles } from "./src/profiles.js";
10
11
 
11
12
  const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
@@ -17,6 +18,7 @@ export default async function shepherdrExtension(
17
18
  registerPackageChangelog(pi);
18
19
  await installAgentProfiles();
19
20
  await registerDeveloperDelivery(pi);
21
+ registerPeerInbox(pi);
20
22
  const fleet = new AgentFleet(pi);
21
23
  const tool = createAgentsTool(fleet);
22
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,9 +43,9 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=3.0.31",
46
+ "@howaboua/pi-codex-conversion": ">=3.0.32",
47
47
  "@earendil-works/pi-ai": ">=0.84.3",
48
- "@earendil-works/pi-coding-agent": ">=0.84.3",
48
+ "@earendil-works/pi-coding-agent": ">=0.84.4",
49
49
  "@earendil-works/pi-tui": ">=0.84.3",
50
50
  "typebox": "*"
51
51
  },
@@ -55,7 +55,7 @@
55
55
  }
56
56
  },
57
57
  "devDependencies": {
58
- "@howaboua/pi-codex-conversion": "3.0.31",
58
+ "@howaboua/pi-codex-conversion": "3.0.32",
59
59
  "@biomejs/biome": "^2.5.10",
60
60
  "@earendil-works/pi-ai": "0.85.1",
61
61
  "@earendil-works/pi-coding-agent": "0.85.1",
@@ -57,9 +57,7 @@ const AskAnswerParameters = Type.Object(
57
57
  const AgentsRequest = Type.Object(
58
58
  {
59
59
  action: StringEnum(ACTIONS),
60
- machine: Type.Optional(
61
- Type.String({ description: "Configured machine; defaults to local" }),
62
- ),
60
+ machine: Type.Optional(Type.String()),
63
61
  target: Type.Optional(
64
62
  Type.String({ description: "Agent name or pane ID" }),
65
63
  ),
@@ -3,17 +3,23 @@ import { activityTask } from "./activity.js";
3
3
  import type { AgentsParams, READ_SOURCES } from "./agents-contract.js";
4
4
  import type { AgentFleet, ConnectedMachine } from "./fleet.js";
5
5
  import { getSnapshot } from "./herdr.js";
6
- import { isHerdrResponseError } from "./herdr-client.js";
6
+ import { isDispatchRejected } from "./herdr-client.js";
7
7
  import { agentSource } from "./messages.js";
8
8
  import type { WorkAttempt } from "./monitor-state.js";
9
9
  import { loadAgentProfiles } from "./profiles.js";
10
10
  import type { ClaimedSettlement } from "./settlement.js";
11
- import type { AgentStatus, PaneInfo, SessionSnapshot } from "./types.js";
11
+ import type {
12
+ AgentStatus,
13
+ PaneInfo,
14
+ PeerDelivery,
15
+ SessionSnapshot,
16
+ } from "./types.js";
12
17
 
13
18
  const MAX_LIST_ITEMS = 30;
14
19
  const MAX_TERMINAL_READ_CHARS = 36_000;
15
20
 
16
- export function toolResult(value: Record<string, unknown>) {
21
+ export function toolResult(value: Record<string, unknown>, warning?: string) {
22
+ if (warning) value = { ...value, next: warning };
17
23
  return {
18
24
  content: [{ type: "text" as const, text: JSON.stringify(value) }],
19
25
  details: value,
@@ -48,7 +54,8 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
48
54
  answer: "target answers machine? blocking?",
49
55
  },
50
56
  rules: {
51
- machine: "Herdr profile ID from list; local = current server",
57
+ machine:
58
+ "Omit for local (host running Pi); list/find omit for all machines. Remote: profile ID from list, not label/hostname",
52
59
  target: "Use spawn/find target exactly",
53
60
  label: "2-3 words; tab/session",
54
61
  answers: "[{selections?:string[],other?:string,comment?:string}]",
@@ -60,6 +67,8 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
60
67
  "Explicit watch persists until unwatch; automatic task watches end on finish/failure, not blockage",
61
68
  prompt:
62
69
  "Only task + inaccessible context; no method/evidence/reporting boilerplate",
70
+ slash:
71
+ "Leading / uses target Pi commands/skills/templates; extension commands are submission-only, even with assign/spawn; TUI-only commands unavailable",
63
72
  reuse:
64
73
  "Reuse only same investigation; reviews independent; new scope = new agent",
65
74
  ...(profiles.has("general")
@@ -274,9 +283,13 @@ export async function dispatchAgentWork(
274
283
  blocking: boolean,
275
284
  signal: AbortSignal,
276
285
  onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
277
- send: () => Promise<void>,
286
+ send: () => Promise<PeerDelivery | void>,
278
287
  options: { expectUserMessage?: boolean } = {},
279
- ): Promise<ClaimedSettlement | undefined> {
288
+ ): Promise<{
289
+ settlement?: ClaimedSettlement;
290
+ command?: true;
291
+ warning?: string;
292
+ }> {
280
293
  signal.throwIfAborted();
281
294
  const addedWatch = !runtime.monitor
282
295
  .list()
@@ -287,6 +300,7 @@ export async function dispatchAgentWork(
287
300
  );
288
301
  let attempt: WorkAttempt | undefined;
289
302
  let settlement: Promise<ClaimedSettlement> | undefined;
303
+ let receipt: PeerDelivery | void;
290
304
  let sendStarted = false;
291
305
  try {
292
306
  await runtime.monitor.track(panel);
@@ -305,13 +319,12 @@ export async function dispatchAgentWork(
305
319
  void settlement?.catch(() => undefined);
306
320
  signal.throwIfAborted();
307
321
  sendStarted = true;
308
- await send();
309
- runtime.monitor.acceptWork(attempt);
322
+ receipt = await send();
310
323
  } catch (error) {
311
324
  runtime.monitor.releaseWorkClaim(attempt, error);
312
325
  if (sendStarted) await runtime.monitor.handleWorkFailure(attempt, error);
313
326
  else runtime.monitor.rejectWork(attempt);
314
- if (addedWatch && (!sendStarted || isHerdrResponseError(error))) {
327
+ if (addedWatch && (!sendStarted || isDispatchRejected(error))) {
315
328
  const record = runtime.monitor
316
329
  .list()
317
330
  .find((record) => record.terminalId === panel.terminal_id);
@@ -328,13 +341,37 @@ export async function dispatchAgentWork(
328
341
  }
329
342
  throw error;
330
343
  }
331
- if (!blocking) return undefined;
344
+ try {
345
+ if (receipt?.command) {
346
+ runtime.monitor.releaseWorkClaim(
347
+ attempt,
348
+ new Error("Command submitted without task waiting"),
349
+ );
350
+ runtime.monitor.rejectWork(attempt);
351
+ if (addedWatch) {
352
+ const record = runtime.monitor
353
+ .list()
354
+ .find((record) => record.terminalId === panel.terminal_id);
355
+ if (record?.scope === "task" && !activityTask(record.activity))
356
+ await runtime.monitor.unwatch(record.paneId);
357
+ }
358
+ } else runtime.monitor.acceptWork(attempt);
359
+ await runtime.monitor.reconcileNow();
360
+ } catch (error) {
361
+ runtime.monitor.releaseWorkClaim(attempt, error);
362
+ return {
363
+ ...(receipt?.command ? { command: true } : {}),
364
+ warning: `Submitted, but monitoring refresh failed: ${error instanceof Error ? error.message : String(error)}. Inspect the target before resubmitting`,
365
+ };
366
+ }
367
+ if (receipt?.command) return { command: true };
368
+ if (!blocking) return {};
332
369
  reportProgress(onUpdate, `Waiting for ${panel.name ?? panel.pane_id}`, {
333
370
  machine: runtime.machine,
334
371
  target: panel.pane_id,
335
372
  status: "working",
336
373
  });
337
- return await settlement!;
374
+ return { settlement: await settlement! };
338
375
  }
339
376
 
340
377
  export async function readAgentTerminal(
@@ -21,7 +21,7 @@ import {
21
21
  import { type AskAnswer, prepareAskAnswer } from "./ask-answer.js";
22
22
  import type { AgentFleet } from "./fleet.js";
23
23
  import { resolvePiAgent } from "./herdr.js";
24
- import { isHerdrResponseError } from "./herdr-client.js";
24
+ import { isDispatchRejected } from "./herdr-client.js";
25
25
  import {
26
26
  resolvePreparationDirectory,
27
27
  rollbackStartedAgent,
@@ -119,20 +119,23 @@ export function createAgentsTool(fleet: AgentFleet) {
119
119
  runtime.fallbackCwd,
120
120
  runtime.resolveDirectory,
121
121
  );
122
+ const input = required(params.message, "message");
122
123
  const message = await prepareProfileMessage(
123
124
  profile,
124
125
  {
125
126
  cwd,
126
- message: required(params.message, "message"),
127
+ message: input,
127
128
  ...(params.base ? { base: params.base } : {}),
128
129
  },
129
130
  { targetLocal: runtime.local },
130
131
  );
131
132
  const attributedMessage = await attributeAgentPrompt(
132
133
  fleet.connected().client,
133
- message,
134
+ input.startsWith("/") ? input : message,
134
135
  "task",
135
136
  );
137
+ if (input.startsWith("/") && message !== input)
138
+ attributedMessage.context = message;
136
139
  reportProgress(update, `Spawning ${label}`, {
137
140
  machine: runtime.machine,
138
141
  name,
@@ -152,10 +155,10 @@ export function createAgentsTool(fleet: AgentFleet) {
152
155
  );
153
156
  let promptSubmissionStarted = false;
154
157
  let promptAccepted = false;
155
- let settlement;
158
+ let dispatch;
156
159
  const blocking = shouldBlockAgentSpawn(profile.name, params.blocking);
157
160
  try {
158
- settlement = await dispatchAgentWork(
161
+ dispatch = await dispatchAgentWork(
159
162
  runtime,
160
163
  started.agent,
161
164
  message,
@@ -164,37 +167,47 @@ export function createAgentsTool(fleet: AgentFleet) {
164
167
  update,
165
168
  async () => {
166
169
  promptSubmissionStarted = true;
167
- await runtime.client.request("agent.prompt", {
168
- target: started.id,
169
- text: attributedMessage,
170
- });
170
+ const receipt = await runtime.client.sendMessage(
171
+ started.agent,
172
+ attributedMessage,
173
+ );
171
174
  promptAccepted = true;
175
+ return receipt;
172
176
  },
173
177
  { expectUserMessage: true },
174
178
  );
175
179
  } catch (error) {
176
180
  if (
177
181
  !promptAccepted &&
178
- (!promptSubmissionStarted || isHerdrResponseError(error))
182
+ (!promptSubmissionStarted || isDispatchRejected(error))
179
183
  ) {
180
184
  return rollbackStartedAgent(runtime.client, started, error);
181
185
  }
182
186
  throw error;
183
187
  }
184
188
  return toolResult(
185
- settlement
189
+ dispatch.command
186
190
  ? {
187
191
  spawned: true,
188
- ...settlementResult(runtime.machine, settlement),
189
- }
190
- : {
191
- spawned: true,
192
+ commandSubmitted: true,
192
193
  machine: runtime.machine,
193
194
  target: started.id,
194
195
  name,
195
- status: "working",
196
- next: "Completion or blockage will be delivered automatically; do not poll",
197
- },
196
+ }
197
+ : dispatch.settlement
198
+ ? {
199
+ spawned: true,
200
+ ...settlementResult(runtime.machine, dispatch.settlement),
201
+ }
202
+ : {
203
+ spawned: true,
204
+ machine: runtime.machine,
205
+ target: started.id,
206
+ name,
207
+ status: "working",
208
+ next: "Completion or blockage will be delivered automatically; do not poll",
209
+ },
210
+ dispatch.warning,
198
211
  );
199
212
  }
200
213
 
@@ -272,43 +285,47 @@ export function createAgentsTool(fleet: AgentFleet) {
272
285
  );
273
286
  if (params.action === "send") {
274
287
  executionSignal.throwIfAborted();
275
- await runtime.client.request("agent.prompt", {
276
- target: panel.pane_id,
277
- text: attributedMessage,
278
- });
288
+ const receipt = await runtime.client.sendMessage(
289
+ panel,
290
+ attributedMessage,
291
+ );
279
292
  return toolResult({
280
293
  sent: true,
294
+ ...(receipt.command ? { commandSubmitted: true } : {}),
281
295
  machine: runtime.machine,
282
296
  target: panel.pane_id,
283
297
  });
284
298
  }
285
- const settlement = await dispatchAgentWork(
299
+ const dispatch = await dispatchAgentWork(
286
300
  runtime,
287
301
  panel,
288
302
  message,
289
303
  params.blocking !== false,
290
304
  executionSignal,
291
305
  update,
292
- () =>
293
- runtime.client.request("agent.prompt", {
294
- target: panel.pane_id,
295
- text: attributedMessage,
296
- }),
306
+ () => runtime.client.sendMessage(panel, attributedMessage),
297
307
  { expectUserMessage: true },
298
308
  );
299
309
  return toolResult(
300
- settlement
310
+ dispatch.command
301
311
  ? {
302
- assigned: true,
303
- ...settlementResult(runtime.machine, settlement),
304
- }
305
- : {
306
- assigned: true,
312
+ commandSubmitted: true,
307
313
  machine: runtime.machine,
308
314
  target: panel.pane_id,
309
- status: "working",
310
- next: "Completion or blockage will be delivered automatically; do not poll",
311
- },
315
+ }
316
+ : dispatch.settlement
317
+ ? {
318
+ assigned: true,
319
+ ...settlementResult(runtime.machine, dispatch.settlement),
320
+ }
321
+ : {
322
+ assigned: true,
323
+ machine: runtime.machine,
324
+ target: panel.pane_id,
325
+ status: "working",
326
+ next: "Completion or blockage will be delivered automatically; do not poll",
327
+ },
328
+ dispatch.warning,
312
329
  );
313
330
  }
314
331
  if (params.action === "answer") {
@@ -322,7 +339,7 @@ export function createAgentsTool(fleet: AgentFleet) {
322
339
  const task = `Answer: ${prepared.ask.prompts
323
340
  .map((prompt) => prompt.title)
324
341
  .join(", ")}`;
325
- const settlement = await dispatchAgentWork(
342
+ const { settlement, warning } = await dispatchAgentWork(
326
343
  runtime,
327
344
  panel,
328
345
  task,
@@ -344,6 +361,7 @@ export function createAgentsTool(fleet: AgentFleet) {
344
361
  status: "working",
345
362
  next: "Completion or blockage will be delivered automatically; do not poll",
346
363
  },
364
+ warning,
347
365
  );
348
366
  }
349
367
  throw new Error(`unsupported action ${params.action}`);
package/src/delivery.ts CHANGED
@@ -1,14 +1,31 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
2
5
  import type {
3
6
  CodexDeveloperCustomMessage,
4
7
  CodexDeveloperMessageOptions,
5
8
  trySendCodexDeveloperCustomMessage,
9
+ tryStartCodexPreparedIdleKickoff,
10
+ tryStartCodexPreparedIdlePrompt,
6
11
  } from "@howaboua/pi-codex-conversion/developer-messages";
7
12
 
8
13
  const senders = new WeakMap<
9
14
  ExtensionAPI,
10
15
  typeof trySendCodexDeveloperCustomMessage
11
16
  >();
17
+ const preparedKickoffs = new WeakMap<
18
+ ExtensionAPI,
19
+ typeof tryStartCodexPreparedIdleKickoff
20
+ >();
21
+ const fallbackKickoffs = new WeakMap<
22
+ ExtensionAPI,
23
+ "preparing" | "running" | "queued"
24
+ >();
25
+ const preparedPrompts = new WeakMap<
26
+ ExtensionAPI,
27
+ typeof tryStartCodexPreparedIdlePrompt
28
+ >();
12
29
  const PACKAGE = "@howaboua/pi-codex-conversion";
13
30
  const MODULE = `${PACKAGE}/developer-messages`;
14
31
 
@@ -21,9 +38,31 @@ export async function registerDeveloperDelivery(
21
38
  );
22
39
  if (typeof api.trySendCodexDeveloperCustomMessage === "function")
23
40
  senders.set(pi, api.trySendCodexDeveloperCustomMessage);
41
+ if (typeof api.tryStartCodexPreparedIdleKickoff === "function")
42
+ preparedKickoffs.set(pi, api.tryStartCodexPreparedIdleKickoff);
43
+ if (typeof api.tryStartCodexPreparedIdlePrompt === "function")
44
+ preparedPrompts.set(pi, api.tryStartCodexPreparedIdlePrompt);
24
45
  } catch (error) {
25
46
  if (!isUnavailable(error)) throw error;
26
47
  }
48
+ pi.on("session_start", () => {
49
+ fallbackKickoffs.delete(pi);
50
+ });
51
+ pi.on("session_tree", () => {
52
+ fallbackKickoffs.delete(pi);
53
+ });
54
+ pi.on("agent_start", () => {
55
+ if (fallbackKickoffs.get(pi) === "preparing")
56
+ fallbackKickoffs.set(pi, "running");
57
+ });
58
+ pi.on("agent_settled", (_event, ctx) => {
59
+ const state = fallbackKickoffs.get(pi);
60
+ if (state === "running" || state === "queued") fallbackKickoffs.delete(pi);
61
+ if (state === "queued") startPreparedIdleTurn(pi, ctx);
62
+ });
63
+ pi.on("session_shutdown", () => {
64
+ fallbackKickoffs.delete(pi);
65
+ });
27
66
  pi.on("input", (event, ctx) => {
28
67
  // Idle prompts must run Pi's complete before_agent_start preparation chain.
29
68
  if (
@@ -50,6 +89,42 @@ export async function registerDeveloperDelivery(
50
89
  });
51
90
  }
52
91
 
92
+ export function startPreparedIdleTurn(
93
+ pi: ExtensionAPI,
94
+ ctx: Pick<ExtensionContext, "ui">,
95
+ start?: () => void,
96
+ ): void {
97
+ if (start) {
98
+ if (preparedPrompts.get(pi)?.(pi, start)) return;
99
+ if (preparedKickoffs.has(pi) && !preparedPrompts.has(pi))
100
+ throw new Error(
101
+ "Update Pi Codex Conversion and reload before sending slash commands",
102
+ );
103
+ } else if (preparedKickoffs.get(pi)?.(pi, ctx)) return;
104
+ if (fallbackKickoffs.has(pi)) {
105
+ if (start)
106
+ throw new Error(
107
+ "Target has a pending turn; retry after it starts or settles",
108
+ );
109
+ // Pi is already idle while earlier settlement handlers are awaiting.
110
+ if (fallbackKickoffs.get(pi) === "running")
111
+ fallbackKickoffs.set(pi, "queued");
112
+ ctx.ui.notify(
113
+ "An automatic turn is pending. If no turn starts, send a user message or reload the session.",
114
+ "warning",
115
+ );
116
+ return;
117
+ }
118
+ fallbackKickoffs.set(pi, "preparing");
119
+ try {
120
+ if (start) start();
121
+ else pi.sendUserMessage("Continue.", { deliverAs: "steer" });
122
+ } catch (error) {
123
+ fallbackKickoffs.delete(pi);
124
+ throw error;
125
+ }
126
+ }
127
+
53
128
  export function sendPolicyMessage(
54
129
  pi: ExtensionAPI,
55
130
  message: CodexDeveloperCustomMessage,
@@ -1,5 +1,11 @@
1
1
  import { createConnection } from "node:net";
2
- import type { HerdrEvent } from "./types.js";
2
+ import { sendPeerMessage } from "./remote/shepherdr-peer.mjs";
3
+ import type {
4
+ HerdrEvent,
5
+ PaneInfo,
6
+ PeerDelivery,
7
+ PeerMessage,
8
+ } from "./types.js";
3
9
 
4
10
  const MAX_FRAME_BUFFER = 8 * 1024 * 1024;
5
11
 
@@ -28,10 +34,19 @@ function errorFromResponse(value: unknown): Error {
28
34
  return error;
29
35
  }
30
36
 
31
- export function isHerdrResponseError(error: unknown): boolean {
37
+ function isHerdrResponseError(error: unknown): boolean {
32
38
  return (error as Error & { herdrResponse?: unknown }).herdrResponse === true;
33
39
  }
34
40
 
41
+ export function isDispatchRejected(error: unknown): boolean {
42
+ return (
43
+ isHerdrResponseError(error) ||
44
+ (error instanceof Error &&
45
+ "code" in error &&
46
+ error.code === "SHEPHERDR_DELIVERY_REJECTED")
47
+ );
48
+ }
49
+
35
50
  export function isHerdrErrorCode(error: unknown, code: string): boolean {
36
51
  return (
37
52
  isHerdrResponseError(error) &&
@@ -41,6 +56,7 @@ export function isHerdrErrorCode(error: unknown, code: string): boolean {
41
56
 
42
57
  export interface HerdrConnection {
43
58
  request<T>(method: string, params?: object, timeoutMs?: number): Promise<T>;
59
+ sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery>;
44
60
  subscribe(
45
61
  subscriptions: object[],
46
62
  onEvent: (event: HerdrEvent) => void,
@@ -61,6 +77,14 @@ export class HerdrClient implements HerdrConnection {
61
77
  this.socketPath = socketPath;
62
78
  }
63
79
 
80
+ sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery> {
81
+ return sendPeerMessage(
82
+ (method, params) => this.request(method, params),
83
+ agent,
84
+ message,
85
+ );
86
+ }
87
+
64
88
  request<T>(
65
89
  method: string,
66
90
  params: object = {},
@@ -1,4 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { isAbsolute } from "node:path";
2
3
  import { promisify } from "node:util";
3
4
  import { type Static, Type } from "typebox";
4
5
  import { Check } from "typebox/value";
@@ -25,20 +26,36 @@ export type SshMachine = Static<typeof Machine>;
25
26
  export async function readMachineCatalog(): Promise<
26
27
  Record<string, SshMachine>
27
28
  > {
29
+ const inheritedBinary = process.env["HERDR_BIN_PATH"]?.trim() || "herdr";
30
+ let binary = inheritedBinary;
31
+ const read = (path: string) =>
32
+ promisify(execFile)(path, ["machine", "list", "--json"], {
33
+ timeout: 10_000,
34
+ maxBuffer: 1024 * 1024,
35
+ encoding: "utf8",
36
+ });
28
37
  let stdout: string;
29
38
  try {
30
- ({ stdout } = await promisify(execFile)(
31
- process.env["HERDR_BIN_PATH"]?.trim() || "herdr",
32
- ["machine", "list", "--json"],
33
- {
34
- timeout: 10_000,
35
- maxBuffer: 1024 * 1024,
36
- encoding: "utf8",
37
- },
38
- ));
39
+ try {
40
+ ({ stdout } = await read(binary));
41
+ } catch (error) {
42
+ if (
43
+ !(error instanceof Error) ||
44
+ !("code" in error) ||
45
+ error.code !== "ENOENT" ||
46
+ !isAbsolute(binary) ||
47
+ !binary.endsWith(" (deleted)")
48
+ ) {
49
+ throw error;
50
+ }
51
+ // Linux /proc executable paths can retain this suffix after replacement.
52
+ binary = binary.slice(0, -" (deleted)".length);
53
+ ({ stdout } = await read(binary));
54
+ }
39
55
  } catch (error) {
40
56
  throw new Error(
41
- `Could not read Herdr machines; requires Herdr 0.9 or newer: ${error instanceof Error ? error.message : String(error)}`,
57
+ `Could not read Herdr machines${binary !== inheritedBinary ? " after retrying stale HERDR_BIN_PATH" : ""}: ${error instanceof Error ? error.message : String(error)}`,
58
+ { cause: error },
42
59
  );
43
60
  }
44
61
  let value: unknown;