@howaboua/pi-shepherdr 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.2
4
+
5
+ - Removed redundant tool guidance from Ask, Shepherdr, Skills and Browser. Code and Notebook Mode now show one callable contract per tool, with detailed Browser and agent rules in help.
6
+
7
+ ## 0.2.1
8
+
9
+ - Deliver peer messages directly to Pi without submitting unsent human drafts.
10
+
11
+ - Preserve slash-command arguments and use the target session's skill and prompt-template expansion.
12
+ - Return submission-only acknowledgements for registered extension commands instead of waiting for an assistant reply.
13
+
14
+ Requires Pi 0.84.4 or newer. Update and reload Shepherdr on both controllers and workers, and Pi Codex Conversion where installed.
15
+
16
+ - Fixed idle agent reports and manual checkpoint requests to preserve prompt preparation, coalesce concurrent continuations, and process reports arriving during turn settlement.
17
+
18
+ - 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.
19
+ - 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.
20
+ - 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.
21
+ - 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.
22
+
3
23
  ## 0.2.0
4
24
 
5
25
  - 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
 
@@ -36,7 +38,8 @@ async function registerAgentsInCodeMode(
36
38
  const registration = registerCodeModeExtensionTools(pi, () => [
37
39
  adaptToolForCodeMode(tool, {
38
40
  blocking: isBlockingAgentsCall,
39
- usage: 'await tools.agents({ action: "help" }) // first call alone',
41
+ usage:
42
+ 'await tools.agents({ action: "help" }) // Persistent agents; first call alone',
40
43
  }),
41
44
  ]);
42
45
  pi.on("session_shutdown", () => registration.unregister());
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.2",
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.33",
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.33",
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,24 +54,26 @@ 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}]",
55
62
  send: "Peer questions, updates, replies; submission only, no wait or watch",
56
63
  assign: "Delegate a task to an existing agent",
57
64
  blocking:
58
- "spawn/assign/answer default true; false pushes task settlement; reviewers always wait; never poll",
65
+ "spawn/assign/answer default true; false pushes task settlement; never poll. Reviewer spawns always block; await review before working its scope",
59
66
  watch:
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")
66
75
  ? {
67
- general:
68
- "Only when requested/orchestrating. Current repo: create + bootstrap worktree; pass cwd",
76
+ general: "Only when requested/orchestrating",
69
77
  }
70
78
  : {}),
71
79
  },
@@ -274,9 +282,13 @@ export async function dispatchAgentWork(
274
282
  blocking: boolean,
275
283
  signal: AbortSignal,
276
284
  onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
277
- send: () => Promise<void>,
285
+ send: () => Promise<PeerDelivery | void>,
278
286
  options: { expectUserMessage?: boolean } = {},
279
- ): Promise<ClaimedSettlement | undefined> {
287
+ ): Promise<{
288
+ settlement?: ClaimedSettlement;
289
+ command?: true;
290
+ warning?: string;
291
+ }> {
280
292
  signal.throwIfAborted();
281
293
  const addedWatch = !runtime.monitor
282
294
  .list()
@@ -287,6 +299,7 @@ export async function dispatchAgentWork(
287
299
  );
288
300
  let attempt: WorkAttempt | undefined;
289
301
  let settlement: Promise<ClaimedSettlement> | undefined;
302
+ let receipt: PeerDelivery | void;
290
303
  let sendStarted = false;
291
304
  try {
292
305
  await runtime.monitor.track(panel);
@@ -305,13 +318,12 @@ export async function dispatchAgentWork(
305
318
  void settlement?.catch(() => undefined);
306
319
  signal.throwIfAborted();
307
320
  sendStarted = true;
308
- await send();
309
- runtime.monitor.acceptWork(attempt);
321
+ receipt = await send();
310
322
  } catch (error) {
311
323
  runtime.monitor.releaseWorkClaim(attempt, error);
312
324
  if (sendStarted) await runtime.monitor.handleWorkFailure(attempt, error);
313
325
  else runtime.monitor.rejectWork(attempt);
314
- if (addedWatch && (!sendStarted || isHerdrResponseError(error))) {
326
+ if (addedWatch && (!sendStarted || isDispatchRejected(error))) {
315
327
  const record = runtime.monitor
316
328
  .list()
317
329
  .find((record) => record.terminalId === panel.terminal_id);
@@ -328,13 +340,37 @@ export async function dispatchAgentWork(
328
340
  }
329
341
  throw error;
330
342
  }
331
- if (!blocking) return undefined;
343
+ try {
344
+ if (receipt?.command) {
345
+ runtime.monitor.releaseWorkClaim(
346
+ attempt,
347
+ new Error("Command submitted without task waiting"),
348
+ );
349
+ runtime.monitor.rejectWork(attempt);
350
+ if (addedWatch) {
351
+ const record = runtime.monitor
352
+ .list()
353
+ .find((record) => record.terminalId === panel.terminal_id);
354
+ if (record?.scope === "task" && !activityTask(record.activity))
355
+ await runtime.monitor.unwatch(record.paneId);
356
+ }
357
+ } else runtime.monitor.acceptWork(attempt);
358
+ await runtime.monitor.reconcileNow();
359
+ } catch (error) {
360
+ runtime.monitor.releaseWorkClaim(attempt, error);
361
+ return {
362
+ ...(receipt?.command ? { command: true } : {}),
363
+ warning: `Submitted, but monitoring refresh failed: ${error instanceof Error ? error.message : String(error)}. Inspect the target before resubmitting`,
364
+ };
365
+ }
366
+ if (receipt?.command) return { command: true };
367
+ if (!blocking) return {};
332
368
  reportProgress(onUpdate, `Waiting for ${panel.name ?? panel.pane_id}`, {
333
369
  machine: runtime.machine,
334
370
  target: panel.pane_id,
335
371
  status: "working",
336
372
  });
337
- return await settlement!;
373
+ return { settlement: await settlement! };
338
374
  }
339
375
 
340
376
  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,
@@ -52,15 +52,8 @@ export function createAgentsTool(fleet: AgentFleet) {
52
52
  return defineTool({
53
53
  name: "agents",
54
54
  label: "Shepherdr",
55
- description: "Persistent Pi agents across configured Herdr machines.",
55
+ description: "Delegate to persistent agents; call help first, alone",
56
56
  parameters: AgentsParameters,
57
- promptSnippet: "Load agents help before first use.",
58
- promptGuidelines: [
59
- "agents: send messages to peers; assign delegates work. Reviewer spawns always block; await review before working its scope.",
60
- "agents: Specialists know their job. Give only the concrete task and inaccessible context; never append generic method, evidence, or reporting instructions.",
61
- "agents: Reuse specialists only for the same investigation. Keep reviews independent. New scope gets a new agent.",
62
- "agents: For advanced Herdr workspace, pane, process or layout control, run herdr --skill.",
63
- ],
64
57
  executionMode: "sequential",
65
58
  async execute(
66
59
  _toolCallId,
@@ -119,20 +112,23 @@ export function createAgentsTool(fleet: AgentFleet) {
119
112
  runtime.fallbackCwd,
120
113
  runtime.resolveDirectory,
121
114
  );
115
+ const input = required(params.message, "message");
122
116
  const message = await prepareProfileMessage(
123
117
  profile,
124
118
  {
125
119
  cwd,
126
- message: required(params.message, "message"),
120
+ message: input,
127
121
  ...(params.base ? { base: params.base } : {}),
128
122
  },
129
123
  { targetLocal: runtime.local },
130
124
  );
131
125
  const attributedMessage = await attributeAgentPrompt(
132
126
  fleet.connected().client,
133
- message,
127
+ input.startsWith("/") ? input : message,
134
128
  "task",
135
129
  );
130
+ if (input.startsWith("/") && message !== input)
131
+ attributedMessage.context = message;
136
132
  reportProgress(update, `Spawning ${label}`, {
137
133
  machine: runtime.machine,
138
134
  name,
@@ -152,10 +148,10 @@ export function createAgentsTool(fleet: AgentFleet) {
152
148
  );
153
149
  let promptSubmissionStarted = false;
154
150
  let promptAccepted = false;
155
- let settlement;
151
+ let dispatch;
156
152
  const blocking = shouldBlockAgentSpawn(profile.name, params.blocking);
157
153
  try {
158
- settlement = await dispatchAgentWork(
154
+ dispatch = await dispatchAgentWork(
159
155
  runtime,
160
156
  started.agent,
161
157
  message,
@@ -164,37 +160,47 @@ export function createAgentsTool(fleet: AgentFleet) {
164
160
  update,
165
161
  async () => {
166
162
  promptSubmissionStarted = true;
167
- await runtime.client.request("agent.prompt", {
168
- target: started.id,
169
- text: attributedMessage,
170
- });
163
+ const receipt = await runtime.client.sendMessage(
164
+ started.agent,
165
+ attributedMessage,
166
+ );
171
167
  promptAccepted = true;
168
+ return receipt;
172
169
  },
173
170
  { expectUserMessage: true },
174
171
  );
175
172
  } catch (error) {
176
173
  if (
177
174
  !promptAccepted &&
178
- (!promptSubmissionStarted || isHerdrResponseError(error))
175
+ (!promptSubmissionStarted || isDispatchRejected(error))
179
176
  ) {
180
177
  return rollbackStartedAgent(runtime.client, started, error);
181
178
  }
182
179
  throw error;
183
180
  }
184
181
  return toolResult(
185
- settlement
182
+ dispatch.command
186
183
  ? {
187
184
  spawned: true,
188
- ...settlementResult(runtime.machine, settlement),
189
- }
190
- : {
191
- spawned: true,
185
+ commandSubmitted: true,
192
186
  machine: runtime.machine,
193
187
  target: started.id,
194
188
  name,
195
- status: "working",
196
- next: "Completion or blockage will be delivered automatically; do not poll",
197
- },
189
+ }
190
+ : dispatch.settlement
191
+ ? {
192
+ spawned: true,
193
+ ...settlementResult(runtime.machine, dispatch.settlement),
194
+ }
195
+ : {
196
+ spawned: true,
197
+ machine: runtime.machine,
198
+ target: started.id,
199
+ name,
200
+ status: "working",
201
+ next: "Completion or blockage will be delivered automatically; do not poll",
202
+ },
203
+ dispatch.warning,
198
204
  );
199
205
  }
200
206
 
@@ -272,43 +278,47 @@ export function createAgentsTool(fleet: AgentFleet) {
272
278
  );
273
279
  if (params.action === "send") {
274
280
  executionSignal.throwIfAborted();
275
- await runtime.client.request("agent.prompt", {
276
- target: panel.pane_id,
277
- text: attributedMessage,
278
- });
281
+ const receipt = await runtime.client.sendMessage(
282
+ panel,
283
+ attributedMessage,
284
+ );
279
285
  return toolResult({
280
286
  sent: true,
287
+ ...(receipt.command ? { commandSubmitted: true } : {}),
281
288
  machine: runtime.machine,
282
289
  target: panel.pane_id,
283
290
  });
284
291
  }
285
- const settlement = await dispatchAgentWork(
292
+ const dispatch = await dispatchAgentWork(
286
293
  runtime,
287
294
  panel,
288
295
  message,
289
296
  params.blocking !== false,
290
297
  executionSignal,
291
298
  update,
292
- () =>
293
- runtime.client.request("agent.prompt", {
294
- target: panel.pane_id,
295
- text: attributedMessage,
296
- }),
299
+ () => runtime.client.sendMessage(panel, attributedMessage),
297
300
  { expectUserMessage: true },
298
301
  );
299
302
  return toolResult(
300
- settlement
303
+ dispatch.command
301
304
  ? {
302
- assigned: true,
303
- ...settlementResult(runtime.machine, settlement),
304
- }
305
- : {
306
- assigned: true,
305
+ commandSubmitted: true,
307
306
  machine: runtime.machine,
308
307
  target: panel.pane_id,
309
- status: "working",
310
- next: "Completion or blockage will be delivered automatically; do not poll",
311
- },
308
+ }
309
+ : dispatch.settlement
310
+ ? {
311
+ assigned: true,
312
+ ...settlementResult(runtime.machine, dispatch.settlement),
313
+ }
314
+ : {
315
+ assigned: true,
316
+ machine: runtime.machine,
317
+ target: panel.pane_id,
318
+ status: "working",
319
+ next: "Completion or blockage will be delivered automatically; do not poll",
320
+ },
321
+ dispatch.warning,
312
322
  );
313
323
  }
314
324
  if (params.action === "answer") {
@@ -322,7 +332,7 @@ export function createAgentsTool(fleet: AgentFleet) {
322
332
  const task = `Answer: ${prepared.ask.prompts
323
333
  .map((prompt) => prompt.title)
324
334
  .join(", ")}`;
325
- const settlement = await dispatchAgentWork(
335
+ const { settlement, warning } = await dispatchAgentWork(
326
336
  runtime,
327
337
  panel,
328
338
  task,
@@ -344,6 +354,7 @@ export function createAgentsTool(fleet: AgentFleet) {
344
354
  status: "working",
345
355
  next: "Completion or blockage will be delivered automatically; do not poll",
346
356
  },
357
+ warning,
347
358
  );
348
359
  }
349
360
  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 = {},