@howaboua/pi-shepherdr 0.2.19 → 0.2.21

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,17 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.21
4
+
5
+ - Fixed duplicate sessions showing a stack trace instead of a warning explaining how to restore shared context.
6
+
7
+ ## 0.2.20
8
+
9
+ - Requires Pi 1.2.0 or newer.
10
+
11
+ - Idle assignments and completion reports now apply Pi's full prompt and tool preparation.
12
+ - Fixed local and remote spawns failing during session startup.
13
+ - Supervision reminders now distinguish other agents' tasks from the current task after compaction.
14
+
3
15
  ## 0.2.19
4
16
 
5
17
  - Added Codex parent-child metadata for workers when used with PCC, preserved on resume and independent of shared notes.
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 1.1.0 or newer, Node.js 22.18 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
17
+ Requires Pi 1.2.0 or newer, Node.js 22.18 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
18
18
 
19
19
  ```bash
20
20
  herdr integration install pi
@@ -120,7 +120,7 @@ Keys are command names without `/`; values are nonempty descriptions. Only the g
120
120
 
121
121
  Blocked commands return the built-in commands and currently registered, allowed extension commands. Commands return `commandSubmitted: true` without adding a task watch, even through `spawn` or `assign`. Submission does not confirm command success, except `/quit`, which waits for Pi to exit and its pane to close. Built-in commands other than `/quit` require an idle target. Skills and prompt templates keep their existing behavior.
122
122
 
123
- 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.
123
+ Idle messages start a custom-message turn through Pi’s complete preparation chain. 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.
124
124
 
125
125
  ### Extension messages
126
126
 
package/index.ts CHANGED
@@ -11,7 +11,7 @@ import { registerAgentEventRenderer } from "./src/messages.js";
11
11
  import { createPeerCommands } from "./src/peer-commands.js";
12
12
  import { registerPeerInbox } from "./src/peer-inbox.js";
13
13
  import { installAgentProfiles } from "./src/profiles.js";
14
- import { registerSharedAgentContext } from "./src/shared-context.js";
14
+ import { registerSharedAgentContext } from "./src/shared-context-host.js";
15
15
  import { registerVoiceFocusReceiver } from "./src/voice-handoff.js";
16
16
 
17
17
  const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
@@ -23,7 +23,7 @@ export default async function shepherdrExtension(
23
23
  registerPackageChangelog(pi);
24
24
 
25
25
  await installAgentProfiles();
26
- await registerDeveloperDelivery(pi);
26
+ registerDeveloperDelivery(pi);
27
27
  const peerCommands = createPeerCommands(pi);
28
28
  const fleet = new AgentFleet(pi);
29
29
  registerFocusArrivals(pi);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.19",
3
+ "version": "0.2.21",
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.51",
46
+ "@howaboua/pi-codex-conversion": ">=4.0.1",
47
47
  "@earendil-works/pi-ai": ">=1.1.0",
48
- "@earendil-works/pi-coding-agent": ">=1.1.0",
48
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
49
49
  "@earendil-works/pi-tui": ">=1.1.0",
50
50
  "typebox": "*"
51
51
  },
@@ -58,13 +58,13 @@
58
58
  "@howaboua/pi-agent-board": "0.0.1"
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.51",
61
+ "@howaboua/pi-codex-conversion": "4.0.1",
62
62
  "@biomejs/biome": "^2.5.15",
63
- "@earendil-works/pi-ai": "1.1.0",
64
- "@earendil-works/pi-coding-agent": "1.1.0",
65
- "@earendil-works/pi-tui": "1.1.0",
63
+ "@earendil-works/pi-ai": "1.3.0",
64
+ "@earendil-works/pi-coding-agent": "1.3.0",
65
+ "@earendil-works/pi-tui": "1.3.0",
66
66
  "@types/node": "^26.6.5",
67
- "typebox": "1.3.36",
67
+ "typebox": "1.3.37",
68
68
  "typescript": "^7.0.2"
69
69
  },
70
70
  "pi": {
@@ -123,7 +123,7 @@ export async function spawnAgent(
123
123
  status: "starting",
124
124
  });
125
125
  const agentArgs = profileAgentArgs(profile, { targetLocal: runtime.local });
126
- const relationship = sharedContext.prepareRelationship(
126
+ const relationship = sharedContext.spawns.prepareRelationship(
127
127
  ctx,
128
128
  runtime,
129
129
  agentArgs,
@@ -131,7 +131,7 @@ export async function spawnAgent(
131
131
  const sharing =
132
132
  profile.shareContext === false
133
133
  ? undefined
134
- : await sharedContext.prepare(ctx, runtime, name, agentArgs);
134
+ : await sharedContext.spawns.prepare(ctx, runtime, name, agentArgs);
135
135
  const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
136
136
  const started = await startAgent(
137
137
  runtime.client,
package/src/delivery.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type {
2
3
  ExtensionAPI,
3
4
  ExtensionContext,
@@ -5,66 +6,68 @@ import type {
5
6
  import type {
6
7
  CodexDeveloperCustomMessage,
7
8
  CodexDeveloperMessageOptions,
8
- trySendCodexDeveloperCustomMessage,
9
- tryStartCodexPreparedIdleKickoff,
10
- tryStartCodexPreparedIdlePrompt,
9
+ CodexDeveloperMessageRequest,
11
10
  } from "@howaboua/pi-codex-conversion/developer-messages";
12
11
 
13
- const senders = new WeakMap<
14
- ExtensionAPI,
15
- typeof trySendCodexDeveloperCustomMessage
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
- >();
29
- const PACKAGE = "@howaboua/pi-codex-conversion";
30
- const MODULE = `${PACKAGE}/developer-messages`;
31
-
32
- export async function registerDeveloperDelivery(
33
- pi: ExtensionAPI,
34
- ): Promise<void> {
35
- try {
36
- const api = await import(
37
- "@howaboua/pi-codex-conversion/developer-messages"
12
+ const contexts = new WeakMap<ExtensionAPI, ExtensionContext>();
13
+ const PENDING_MESSAGE = "herdr-pending-message";
14
+ interface PendingMessage {
15
+ sessionId: string;
16
+ message: CodexDeveloperCustomMessage & {
17
+ details: { herdrAdmissionId: string };
18
+ };
19
+ queued?: boolean;
20
+ }
21
+ export function registerDeveloperDelivery(pi: ExtensionAPI): void {
22
+ pi.on("session_start", (event, ctx) => {
23
+ contexts.set(pi, ctx);
24
+ const entries = ctx.sessionManager.getEntries();
25
+ const pending = entries.flatMap((entry) =>
26
+ entry.type === "custom" && entry.customType === PENDING_MESSAGE
27
+ ? [readPendingMessage(entry.data)]
28
+ : [],
38
29
  );
39
- if (typeof api.trySendCodexDeveloperCustomMessage === "function")
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);
45
- } catch (error) {
46
- if (!isUnavailable(error)) throw error;
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);
30
+ const queued = new Set(
31
+ pending
32
+ .filter((data) => data.queued)
33
+ .map((data) => data.message.details.herdrAdmissionId),
34
+ );
35
+ const delivered = new Set(
36
+ entries.flatMap((entry) =>
37
+ entry.type === "custom_message" &&
38
+ entry.details &&
39
+ typeof entry.details === "object" &&
40
+ "herdrAdmissionId" in entry.details
41
+ ? [entry.details.herdrAdmissionId]
42
+ : [],
43
+ ),
44
+ );
45
+ for (const data of pending) {
46
+ const id = data.message.details.herdrAdmissionId;
47
+ if (
48
+ data.sessionId !== ctx.sessionManager.getSessionId() ||
49
+ delivered.has(id) ||
50
+ (event.reason === "reload" && queued.has(id))
51
+ )
52
+ continue;
53
+ pi.sendMessage(data.message, {
54
+ deliverAs: "nextTurn",
55
+ triggerTurn: false,
56
+ });
57
+ delivered.add(id);
58
+ if (!data.queued)
59
+ pi.appendEntry(PENDING_MESSAGE, { ...data, queued: true });
60
+ ctx.ui.notify(
61
+ "Pending coordination restored. Send a message to continue.",
62
+ "warning",
63
+ );
64
+ }
62
65
  });
63
66
  pi.on("session_shutdown", () => {
64
- fallbackKickoffs.delete(pi);
67
+ contexts.delete(pi);
65
68
  });
66
69
  pi.on("input", (event, ctx) => {
67
- // Idle prompts must run Pi's complete before_agent_start preparation chain.
70
+ // Input hooks run before Pi reserves a user kickoff; only real steering is promoted.
68
71
  if (
69
72
  ctx.isIdle() ||
70
73
  event.streamingBehavior === undefined ||
@@ -73,7 +76,7 @@ export async function registerDeveloperDelivery(
73
76
  )
74
77
  return;
75
78
  if (
76
- senders.get(pi)?.(
79
+ trySendDeveloperMessage(
77
80
  pi,
78
81
  {
79
82
  customType: "herdr-agent-message",
@@ -89,51 +92,34 @@ export async function registerDeveloperDelivery(
89
92
  });
90
93
  }
91
94
 
92
- export function startPreparedIdleTurn(
93
- pi: ExtensionAPI,
94
- ctx: Pick<ExtensionContext, "ui" | "sessionManager">,
95
- start?: () => void,
96
- ): void {
97
- // Session history survives tree cuts; a new active branch is not a fresh agent.
98
- const prompt =
99
- !start &&
100
- ctx.sessionManager
101
- .getEntries()
102
- .some(
103
- (entry) =>
104
- entry.type === "message" && entry.message.role === "assistant",
105
- )
106
- ? "Continue, unless awaiting for user approval."
107
- : "Continue.";
108
- if (start) {
109
- if (preparedPrompts.get(pi)?.(pi, start)) return;
110
- if (preparedKickoffs.has(pi) && !preparedPrompts.has(pi))
111
- throw new Error(
112
- "Update Pi Codex Conversion and reload before sending slash commands",
113
- );
114
- } else if (preparedKickoffs.get(pi)?.(pi, ctx, prompt)) return;
115
- if (fallbackKickoffs.has(pi)) {
116
- if (start)
117
- throw new Error(
118
- "Target has a pending turn; retry after it starts or settles",
119
- );
120
- // Pi is already idle while earlier settlement handlers are awaiting.
121
- if (fallbackKickoffs.get(pi) === "running")
122
- fallbackKickoffs.set(pi, "queued");
123
- ctx.ui.notify(
124
- "An automatic turn is pending. If no turn starts, send a user message or reload the session.",
125
- "warning",
126
- );
127
- return;
128
- }
129
- fallbackKickoffs.set(pi, "preparing");
130
- try {
131
- if (start) start();
132
- else pi.sendUserMessage(prompt, { deliverAs: "steer" });
133
- } catch (error) {
134
- fallbackKickoffs.delete(pi);
135
- throw error;
95
+ function readPendingMessage(value: unknown): PendingMessage {
96
+ if (
97
+ value &&
98
+ typeof value === "object" &&
99
+ "sessionId" in value &&
100
+ typeof value.sessionId === "string" &&
101
+ "message" in value &&
102
+ value.message &&
103
+ typeof value.message === "object"
104
+ ) {
105
+ const message = value.message as PendingMessage["message"];
106
+ if (
107
+ typeof message.customType === "string" &&
108
+ typeof message.content === "string" &&
109
+ typeof message.display === "boolean" &&
110
+ message.details &&
111
+ typeof message.details === "object" &&
112
+ typeof message.details.herdrAdmissionId === "string"
113
+ )
114
+ return {
115
+ sessionId: value.sessionId,
116
+ message,
117
+ queued: "queued" in value && value.queued === true,
118
+ };
136
119
  }
120
+ throw new Error(
121
+ "Stored pending coordination is invalid. Reload a valid session before continuing.",
122
+ );
137
123
  }
138
124
 
139
125
  export function sendPolicyMessage(
@@ -141,45 +127,62 @@ export function sendPolicyMessage(
141
127
  message: CodexDeveloperCustomMessage,
142
128
  options: CodexDeveloperMessageOptions,
143
129
  ): void {
144
- if (senders.get(pi)?.(pi, message, options)) return;
145
- // Without Conversion there is no Notes admission to defer. Persist before
146
- // kickoff so failed preflight cannot strand an accepted report in memory.
147
- pi.sendMessage(
148
- message,
149
- options.deliverAs === "nextTurn"
150
- ? { ...options, deliverAs: "steer" }
151
- : options,
152
- );
130
+ if (trySendDeveloperMessage(pi, message, options)) return;
131
+ const ctx = contexts.get(pi);
132
+ if (options.deliverAs !== "nextTurn" && options.triggerTurn && ctx) {
133
+ const request: {
134
+ protocol: 1;
135
+ ctx: ExtensionContext;
136
+ preparation?: Promise<void>;
137
+ } = { protocol: 1, ctx };
138
+ pi.events.emit("pi-notes-compaction:custom-turn-admission:v1", request);
139
+ if (request.preparation) {
140
+ const sessionId = ctx.sessionManager.getSessionId();
141
+ const pending = {
142
+ ...message,
143
+ details: { ...message.details, herdrAdmissionId: randomUUID() },
144
+ };
145
+ pi.appendEntry(PENDING_MESSAGE, { sessionId, message: pending });
146
+ void request.preparation
147
+ .then(() => {
148
+ if (
149
+ contexts.get(pi) !== ctx ||
150
+ ctx.sessionManager.getSessionId() !== sessionId
151
+ )
152
+ throw new Error("Session changed before message delivery");
153
+ pi.sendMessage(pending, options);
154
+ })
155
+ .catch((error) => {
156
+ if (contexts.get(pi) !== ctx) return;
157
+ ctx.ui.notify(
158
+ `Coordination remains pending: ${String(error)}. Retry rollover or reload the session.`,
159
+ "error",
160
+ );
161
+ });
162
+ return;
163
+ }
164
+ }
165
+ pi.sendMessage(message, options);
153
166
  }
154
167
 
155
- function isUnavailable(error: unknown): boolean {
156
- if (
157
- !error ||
158
- typeof error !== "object" ||
159
- !("code" in error) ||
160
- !("message" in error) ||
161
- typeof error.message !== "string"
162
- )
163
- return false;
164
- if (
165
- error.code === "ERR_MODULE_NOT_FOUND" ||
166
- error.code === "MODULE_NOT_FOUND"
167
- ) {
168
- const missing = error.message.match(
169
- /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
170
- )?.[1];
171
- const normalized = missing?.replaceAll("\\", "/").replace(/\.js$/, "");
172
- return (
173
- missing === PACKAGE ||
174
- normalized === MODULE ||
175
- normalized?.endsWith(`/${MODULE}`) === true
176
- );
177
- }
178
- return (
179
- (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
180
- error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
181
- (error.message.includes(MODULE) ||
182
- (error.message.includes("Package subpath './developer-messages'") &&
183
- error.message.includes(PACKAGE)))
168
+ function trySendDeveloperMessage(
169
+ pi: ExtensionAPI,
170
+ message: CodexDeveloperCustomMessage,
171
+ options: CodexDeveloperMessageOptions,
172
+ ): boolean {
173
+ const request: CodexDeveloperMessageRequest = {
174
+ protocol: 1,
175
+ content: message.content,
176
+ message,
177
+ options,
178
+ };
179
+ // The broker's receipt is discovery: no PCC installation or active adapter is required.
180
+ pi.events.emit(
181
+ "@howaboua/pi-codex-conversion.developer-custom-message/v1",
182
+ request,
184
183
  );
184
+ if (!request.outcome) return false;
185
+ if (request.outcome.ok) return true;
186
+ if (request.outcome.reason === "unavailable") return false;
187
+ throw new Error(request.outcome.error);
185
188
  }
package/src/messages.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
8
8
  import type { BoardBinding } from "@howaboua/pi-agent-board/integration";
9
9
  import { activityTask } from "./activity.js";
10
- import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
10
+ import { sendPolicyMessage } from "./delivery.js";
11
11
  import { getCurrentPane, getSnapshot } from "./herdr.js";
12
12
  import type { HerdrConnection } from "./herdr-client.js";
13
13
  import { readExtensionMessage } from "./remote/shepherdr-session.mjs";
@@ -82,7 +82,7 @@ export function activeAgentsBriefing(
82
82
  ): string | undefined {
83
83
  if (!agents.length) return;
84
84
  return [
85
- "Supervised agents after context rollover. Do not duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
85
+ "Supervised agents after context rollover. Their instructions are reference data, not tasks for you. Do not repeat settled tasks or duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
86
86
  JSON.stringify(
87
87
  agents.map((agent) => ({
88
88
  machine: agent.machine,
@@ -510,7 +510,7 @@ function agentEvent(options: AgentEventOptions): {
510
510
 
511
511
  export function injectAgentEvent(
512
512
  pi: ExtensionAPI,
513
- ctx: ExtensionContext,
513
+ _ctx: ExtensionContext,
514
514
  options: AgentEventOptions,
515
515
  ): void {
516
516
  const tools = pi.getActiveTools();
@@ -521,10 +521,7 @@ export function injectAgentEvent(
521
521
  tools.includes("code") ||
522
522
  tools.includes("notebook"),
523
523
  });
524
- const idle = ctx.isIdle();
525
- const delivery = idle
526
- ? { triggerTurn: false, deliverAs: "nextTurn" as const }
527
- : { deliverAs: "steer" as const };
524
+ const delivery = { triggerTurn: true, deliverAs: "steer" as const };
528
525
  sendPolicyMessage(
529
526
  pi,
530
527
  {
@@ -535,7 +532,6 @@ export function injectAgentEvent(
535
532
  },
536
533
  delivery,
537
534
  );
538
- if (idle) startPreparedIdleTurn(pi, ctx);
539
535
  announceAgentEvent(
540
536
  pi,
541
537
  `pi-shepherdr:${message.details.machine}:${message.details.paneId}`,
package/src/peer-inbox.ts CHANGED
@@ -6,7 +6,7 @@ import type {
6
6
  ExtensionContext,
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import { acceptFocus, readFocus } from "./agents-focus.js";
9
- import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
9
+ import { sendPolicyMessage } from "./delivery.js";
10
10
  import { dispatchExtensionReply } from "./extension-reply.js";
11
11
  import type { AgentFleet } from "./fleet.js";
12
12
  import { getCurrentPane } from "./herdr.js";
@@ -34,20 +34,23 @@ export function registerPeerInbox(
34
34
  ): void {
35
35
  let close: (() => Promise<void>) | undefined;
36
36
  let running = false;
37
- pi.on("agent_start", () => {
37
+ const publish = async (ctx: ExtensionContext) => {
38
+ if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
39
+ return;
40
+ close = await openInbox(pi, ctx, () => running, commands, fleet, catchup);
41
+ };
42
+ pi.on("before_agent_start", () => {
38
43
  running = true;
39
44
  });
40
45
  pi.on("agent_settled", () => {
41
46
  running = false;
42
47
  });
43
- pi.on("session_start", async (_event, ctx) => {
48
+ pi.on("session_start", async () => {
44
49
  await close?.();
45
50
  close = undefined;
46
51
  running = false;
47
- if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
48
- return;
49
- close = await openInbox(pi, ctx, () => running, commands, fleet, catchup);
50
52
  });
53
+ pi.on("resources_discover", async (_event, ctx) => publish(ctx));
51
54
  pi.on("session_shutdown", async () => {
52
55
  await close?.();
53
56
  close = undefined;
@@ -334,8 +337,7 @@ async function openInbox(
334
337
  } else reply({ ok: true, command }, execute);
335
338
  return;
336
339
  }
337
- if (idle && !command) startPreparedIdleTurn(pi, ctx, submit);
338
- else submit();
340
+ submit();
339
341
  reply({ ok: true, command });
340
342
  return;
341
343
  }
@@ -361,7 +363,6 @@ async function openInbox(
361
363
  });
362
364
  return;
363
365
  }
364
- const promptIdle = ctx.isIdle();
365
366
  submitted = true;
366
367
  sendPolicyMessage(
367
368
  pi,
@@ -370,14 +371,9 @@ async function openInbox(
370
371
  content: `${sender}\n${text}${notice.content}`,
371
372
  display: true,
372
373
  },
373
- promptIdle
374
- ? { triggerTurn: false, deliverAs: "nextTurn" }
375
- : { deliverAs: "steer" },
374
+ { triggerTurn: true, deliverAs: "steer" },
376
375
  );
377
376
  notice.accepted();
378
- // Keep arrivals out of history until idle rollover and preparation
379
- // finish. The shared kickoff coalesces arrivals during preparation.
380
- if (promptIdle) startPreparedIdleTurn(pi, ctx);
381
377
  // Voice failure must not turn accepted delivery into a retry.
382
378
  try {
383
379
  announcePeerMessage(pi, {
@@ -187,8 +187,11 @@ export async function listenContext(path, handle) {
187
187
  else throw error;
188
188
  }
189
189
  if (alive)
190
- throw new Error(
191
- "This shared context session is already open; close its other live owner first",
190
+ throw Object.assign(
191
+ new Error(
192
+ "This shared context session is already open; close its other live owner first",
193
+ ),
194
+ { code: "SHARED_CONTEXT_ALREADY_OPEN" },
192
195
  );
193
196
  }
194
197
  } catch (error) {
@@ -61,7 +61,7 @@ export async function readReceiver(path) {
61
61
  code: "ENOENT",
62
62
  }),
63
63
  ),
64
- 5_000,
64
+ 30_000,
65
65
  );
66
66
  const read = () => {
67
67
  void readFile(path, "utf8").then(
@@ -18,7 +18,7 @@ import {
18
18
  import { readSessionView } from "./shepherdr-session.mjs";
19
19
  import { watchSessions } from "./shepherdr-session-watch.mjs";
20
20
 
21
- const BRIDGE_VERSION = 20;
21
+ const BRIDGE_VERSION = 22;
22
22
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
23
23
  const subscriptions = new Map();
24
24
  const contextRelays = new Map();
@@ -17,7 +17,7 @@ import type {
17
17
  SessionView,
18
18
  } from "./types.js";
19
19
 
20
- const BRIDGE_VERSION = 20;
20
+ const BRIDGE_VERSION = 22;
21
21
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
22
22
  const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
23
23
  const REMOTE_CHANNEL_HELPER = "~/.pi/agent/shepherdr-channel.mjs";
@@ -0,0 +1,137 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type {
6
+ SharedContextRequest,
7
+ SharedContextResult,
8
+ } from "@howaboua/pi-codex-conversion/context-sharing";
9
+ import { attachmentOwner, attachmentRoutes } from "./attachment-protocol.js";
10
+ import type { AgentBoard } from "./board/host.js";
11
+ import type { AgentFleet } from "./fleet.js";
12
+ import {
13
+ listenContext,
14
+ sessionContextPath,
15
+ } from "./remote/shepherdr-context.mjs";
16
+ import { SharedAgentContext } from "./shared-context.js";
17
+
18
+ export async function registerSharedAgentContext(
19
+ pi: ExtensionAPI,
20
+ fleet: AgentFleet,
21
+ board: AgentBoard,
22
+ ): Promise<SharedAgentContext> {
23
+ let api:
24
+ | typeof import("@howaboua/pi-codex-conversion/context-sharing")
25
+ | undefined;
26
+ try {
27
+ api = await import("@howaboua/pi-codex-conversion/context-sharing");
28
+ } catch (error) {
29
+ const failure = error as { code?: string; message?: string };
30
+ const missing = failure.message?.match(
31
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
32
+ )?.[1];
33
+ const module = "@howaboua/pi-codex-conversion/context-sharing";
34
+ const unavailable =
35
+ ((failure.code === "ERR_MODULE_NOT_FOUND" ||
36
+ failure.code === "MODULE_NOT_FOUND") &&
37
+ (missing === "@howaboua/pi-codex-conversion" ||
38
+ missing === module ||
39
+ missing?.endsWith(`/${module}`))) ||
40
+ (failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
41
+ failure.message?.includes("@howaboua/pi-codex-conversion") &&
42
+ failure.message.includes("./context-sharing"));
43
+ if (!unavailable)
44
+ throw new Error(
45
+ "Update pi-codex-conversion to use shared agent context",
46
+ { cause: error },
47
+ );
48
+ }
49
+ const connection = api?.connectCodexContextSharing(pi);
50
+ const shared = new SharedAgentContext(
51
+ pi,
52
+ fleet,
53
+ () => connection?.service,
54
+ board,
55
+ );
56
+ let close: (() => Promise<void>) | undefined;
57
+ let unregister: (() => void) | undefined;
58
+ const publish = async (ctx: ExtensionContext) => {
59
+ const file = ctx.sessionManager.getSessionFile();
60
+ if (!file) return;
61
+ try {
62
+ close = await listenContext(
63
+ sessionContextPath(file),
64
+ (request: unknown, signal: AbortSignal) =>
65
+ shared.handle(ctx, request, signal),
66
+ );
67
+ } catch (error) {
68
+ if (
69
+ !(error instanceof Error) ||
70
+ !("code" in error) ||
71
+ error.code !== "SHARED_CONTEXT_ALREADY_OPEN"
72
+ )
73
+ throw error;
74
+ ctx.ui.notify(
75
+ "This session is open in another window. Agents remain available, but shared context is unavailable here. Close the other window, then /reload here to enable sharing.",
76
+ "warning",
77
+ );
78
+ }
79
+ };
80
+ pi.on("session_start", async () => {
81
+ await close?.();
82
+ close = undefined;
83
+ unregister?.();
84
+ unregister = connection?.service?.registerRouter(
85
+ Object.assign(
86
+ async (
87
+ context: ExtensionContext,
88
+ request: SharedContextRequest,
89
+ signal?: AbortSignal,
90
+ ) => {
91
+ const attached = await shared.attachment.routing.route(
92
+ context,
93
+ request,
94
+ [],
95
+ (route, next) =>
96
+ fleet
97
+ .connected(route.machine)
98
+ .client.requestContext(
99
+ sessionContextPath(route.sessionFile),
100
+ next,
101
+ signal,
102
+ ),
103
+ signal,
104
+ );
105
+ if (attached) return attached;
106
+ if (connection?.service?.describe(context)?.storage === "remote")
107
+ return undefined;
108
+ return shared.handle(
109
+ context,
110
+ { operation: "context", request, visited: [] },
111
+ signal,
112
+ ) as Promise<SharedContextResult>;
113
+ },
114
+ {
115
+ requiresRemoteScope: (context: ExtensionContext) =>
116
+ attachmentOwner(context)?.context?.controller.storage ===
117
+ "remote" ||
118
+ attachmentRoutes(context).some(
119
+ (route) =>
120
+ route.phase === "ready" &&
121
+ route.plan.context?.target.storage === "remote",
122
+ ),
123
+ },
124
+ ),
125
+ );
126
+ });
127
+ pi.on("resources_discover", async (_event, ctx) => publish(ctx));
128
+ pi.on("session_shutdown", async () => {
129
+ unregister?.();
130
+ await close?.();
131
+ connection?.dispose();
132
+ });
133
+ fleet.setContextRelay((ctx, request, signal) =>
134
+ shared.handle(ctx, request, signal),
135
+ );
136
+ return shared;
137
+ }
@@ -11,29 +11,16 @@ import type {
11
11
  } from "@howaboua/pi-codex-conversion/context-sharing";
12
12
  import { Check } from "typebox/value";
13
13
  import { AgentAttachment } from "./attachment.js";
14
- import {
15
- attachmentOwner,
16
- attachmentRoutes,
17
- Identity,
18
- } from "./attachment-protocol.js";
14
+ import { Identity } from "./attachment-protocol.js";
19
15
  import type { AgentBoard } from "./board/host.js";
20
- import type { AgentFleet, ConnectedMachine } from "./fleet.js";
16
+ import type { AgentFleet } from "./fleet.js";
21
17
  import { sessionPath } from "./herdr.js";
22
18
  import {
23
- listenContext,
24
19
  requestContext,
25
20
  sessionContextPath,
26
21
  } from "./remote/shepherdr-context.mjs";
27
- import type { PaneInfo } from "./types.js";
22
+ import { MEMBER_ENTRY, type Member, SpawnContext } from "./spawn-context.js";
28
23
 
29
- const MEMBER_ENTRY = "herdr-context-child";
30
- interface Member {
31
- agentName: string;
32
- sessionId: string;
33
- threadId: string;
34
- machine: string;
35
- sessionFile: string;
36
- }
37
24
  interface Routing {
38
25
  transport: "shepherdr";
39
26
  parent: string;
@@ -45,12 +32,12 @@ interface ContextEnvelope {
45
32
  }
46
33
 
47
34
  export class SharedAgentContext {
48
- private readonly pi: ExtensionAPI;
49
35
  private readonly fleet: AgentFleet;
50
36
  private readonly getService: () => ContextSharingService | undefined;
51
37
  private readonly board: AgentBoard;
52
38
  private running = false;
53
39
  readonly attachment: AgentAttachment;
40
+ readonly spawns: SpawnContext;
54
41
 
55
42
  constructor(
56
43
  pi: ExtensionAPI,
@@ -58,12 +45,12 @@ export class SharedAgentContext {
58
45
  getService: () => ContextSharingService | undefined,
59
46
  board: AgentBoard,
60
47
  ) {
61
- this.pi = pi;
62
48
  this.fleet = fleet;
63
49
  this.getService = getService;
64
50
  this.board = board;
65
51
  this.attachment = new AgentAttachment(pi, board, getService);
66
- pi.on("agent_start", () => {
52
+ this.spawns = new SpawnContext(pi, getService);
53
+ pi.on("before_agent_start", () => {
67
54
  this.running = true;
68
55
  });
69
56
  pi.on("agent_settled", () => {
@@ -297,235 +284,4 @@ export class SharedAgentContext {
297
284
  );
298
285
  return matches[0]!;
299
286
  }
300
-
301
- prepareRelationship(
302
- ctx: ExtensionContext,
303
- runtime: ConnectedMachine,
304
- args: readonly string[],
305
- ) {
306
- if (!this.getService()?.bindRelationship) return undefined;
307
- // Session-selection profiles resume existing identities rather than creating workers.
308
- if (
309
- args.some((arg) =>
310
- /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
311
- arg,
312
- ),
313
- )
314
- )
315
- return undefined;
316
- const parentThreadId = ctx.sessionManager.getSessionId();
317
- const relationship = { parentThreadId, subagentKind: "collab_spawn" };
318
- return {
319
- accept: async (agent: PaneInfo) => {
320
- const file = sessionPath(agent);
321
- if (!file) throw new Error("Spawned agent has no saved Pi session");
322
- const value = await runtime.client.requestContext(
323
- sessionContextPath(file),
324
- {
325
- operation: "bind-relationship",
326
- relationship,
327
- },
328
- );
329
- if (ctx.sessionManager.getSessionId() !== parentThreadId)
330
- throw new Error("Controller session changed during spawn");
331
- if (value === null)
332
- return {
333
- warning:
334
- "Worker relationship marking requires Codex conversion on the target",
335
- };
336
- if (!isDeepStrictEqual(value, relationship))
337
- throw new Error(
338
- "Spawned agent did not adopt its parent relationship",
339
- );
340
- return undefined;
341
- },
342
- };
343
- }
344
-
345
- async prepare(
346
- ctx: ExtensionContext,
347
- runtime: ConnectedMachine,
348
- name: string,
349
- args: readonly string[] = [],
350
- ) {
351
- const service = this.getService();
352
- if (!service?.canCreateChild(ctx)) return undefined;
353
- const parent = service.describe(ctx);
354
- if (!parent) return undefined;
355
- if (
356
- args.some((arg) =>
357
- /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
358
- arg,
359
- ),
360
- )
361
- )
362
- throw new Error(
363
- "Shared context spawn cannot use profile session-selection arguments; use assign for existing agents",
364
- );
365
- const parentFile = ctx.sessionManager.getSessionFile();
366
- if (!parentFile)
367
- throw new Error(
368
- "Shared context spawn requires a saved controller session",
369
- );
370
- const routing: Routing | undefined =
371
- parent.storage === "session"
372
- ? {
373
- transport: "shepherdr",
374
- parent: runtime.local
375
- ? sessionContextPath(parentFile)
376
- : runtime.client.contextRelayPath(),
377
- }
378
- : undefined;
379
- const { binding, adopt } = await service.createChild(ctx, {
380
- name,
381
- ...(routing ? { routing } : {}),
382
- });
383
- return {
384
- accept: async (agent: PaneInfo) => {
385
- const sessionFile = sessionPath(agent);
386
- if (!sessionFile)
387
- throw new Error("Spawned agent has no native Pi session path");
388
- const value = await runtime.client.requestContext(
389
- sessionContextPath(sessionFile),
390
- { operation: "bind", binding },
391
- );
392
- if (!value)
393
- return {
394
- warning:
395
- "Spawned without shared context: the target needs Codex conversion with notes-based continuity",
396
- };
397
- if (
398
- typeof value !== "object" ||
399
- !("sessionId" in value) ||
400
- value.sessionId !== binding.sessionId ||
401
- !("agentName" in value) ||
402
- value.agentName !== binding.agentName ||
403
- !("storage" in value) ||
404
- value.storage !== binding.storage ||
405
- (binding.accountScope !== undefined &&
406
- (!("accountScope" in value) ||
407
- value.accountScope !== binding.accountScope))
408
- )
409
- throw new Error(
410
- "Spawned agent did not adopt its shared context identity and storage mode",
411
- );
412
- if (ctx.sessionManager.getSessionId() !== parent.threadId)
413
- throw new Error("Controller session changed during spawn");
414
- await adopt();
415
- this.pi.appendEntry<Member>(MEMBER_ENTRY, {
416
- agentName: binding.agentName,
417
- sessionId: parent.sessionId,
418
- threadId: parent.threadId,
419
- machine: runtime.machine,
420
- sessionFile,
421
- });
422
- return { agentName: binding.agentName };
423
- },
424
- };
425
- }
426
- }
427
-
428
- export async function registerSharedAgentContext(
429
- pi: ExtensionAPI,
430
- fleet: AgentFleet,
431
- board: AgentBoard,
432
- ): Promise<SharedAgentContext> {
433
- let api:
434
- | typeof import("@howaboua/pi-codex-conversion/context-sharing")
435
- | undefined;
436
- try {
437
- api = await import("@howaboua/pi-codex-conversion/context-sharing");
438
- } catch (error) {
439
- const failure = error as { code?: string; message?: string };
440
- const missing = failure.message?.match(
441
- /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
442
- )?.[1];
443
- const module = "@howaboua/pi-codex-conversion/context-sharing";
444
- const unavailable =
445
- ((failure.code === "ERR_MODULE_NOT_FOUND" ||
446
- failure.code === "MODULE_NOT_FOUND") &&
447
- (missing === "@howaboua/pi-codex-conversion" ||
448
- missing === module ||
449
- missing?.endsWith(`/${module}`))) ||
450
- (failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
451
- failure.message?.includes("@howaboua/pi-codex-conversion") &&
452
- failure.message.includes("./context-sharing"));
453
- if (!unavailable)
454
- throw new Error(
455
- "Update pi-codex-conversion to use shared agent context",
456
- { cause: error },
457
- );
458
- }
459
- const connection = api?.connectCodexContextSharing(pi);
460
- const shared = new SharedAgentContext(
461
- pi,
462
- fleet,
463
- () => connection?.service,
464
- board,
465
- );
466
- let close: (() => Promise<void>) | undefined;
467
- let unregister: (() => void) | undefined;
468
- pi.on("session_start", async (_event, ctx) => {
469
- await close?.();
470
- close = undefined;
471
- unregister?.();
472
- unregister = connection?.service?.registerRouter(
473
- Object.assign(
474
- async (
475
- context: ExtensionContext,
476
- request: SharedContextRequest,
477
- signal?: AbortSignal,
478
- ) => {
479
- const attached = await shared.attachment.routing.route(
480
- context,
481
- request,
482
- [],
483
- (route, next) =>
484
- fleet
485
- .connected(route.machine)
486
- .client.requestContext(
487
- sessionContextPath(route.sessionFile),
488
- next,
489
- signal,
490
- ),
491
- signal,
492
- );
493
- if (attached) return attached;
494
- if (connection?.service?.describe(context)?.storage === "remote")
495
- return undefined;
496
- return shared.handle(
497
- context,
498
- { operation: "context", request, visited: [] },
499
- signal,
500
- ) as Promise<SharedContextResult>;
501
- },
502
- {
503
- requiresRemoteScope: (context: ExtensionContext) =>
504
- attachmentOwner(context)?.context?.controller.storage ===
505
- "remote" ||
506
- attachmentRoutes(context).some(
507
- (route) =>
508
- route.phase === "ready" &&
509
- route.plan.context?.target.storage === "remote",
510
- ),
511
- },
512
- ),
513
- );
514
- const file = ctx.sessionManager.getSessionFile();
515
- if (file)
516
- close = await listenContext(
517
- sessionContextPath(file),
518
- (request: unknown, signal: AbortSignal) =>
519
- shared.handle(ctx, request, signal),
520
- );
521
- });
522
- pi.on("session_shutdown", async () => {
523
- unregister?.();
524
- await close?.();
525
- connection?.dispose();
526
- });
527
- fleet.setContextRelay((ctx, request, signal) =>
528
- shared.handle(ctx, request, signal),
529
- );
530
- return shared;
531
287
  }
@@ -0,0 +1,159 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
7
+ import type { ConnectedMachine } from "./fleet.js";
8
+ import { sessionPath } from "./herdr.js";
9
+ import { sessionContextPath } from "./remote/shepherdr-context.mjs";
10
+ import type { PaneInfo } from "./types.js";
11
+
12
+ export const MEMBER_ENTRY = "herdr-context-child";
13
+ export interface Member {
14
+ agentName: string;
15
+ sessionId: string;
16
+ threadId: string;
17
+ machine: string;
18
+ sessionFile: string;
19
+ }
20
+ interface Routing {
21
+ transport: "shepherdr";
22
+ parent: string;
23
+ }
24
+ export class SpawnContext {
25
+ private readonly pi: ExtensionAPI;
26
+ private readonly getService: () => ContextSharingService | undefined;
27
+ constructor(
28
+ pi: ExtensionAPI,
29
+ getService: () => ContextSharingService | undefined,
30
+ ) {
31
+ this.pi = pi;
32
+ this.getService = getService;
33
+ }
34
+ prepareRelationship(
35
+ ctx: ExtensionContext,
36
+ runtime: ConnectedMachine,
37
+ args: readonly string[],
38
+ ) {
39
+ if (!this.getService()?.bindRelationship) return undefined;
40
+ // Session-selection profiles resume existing identities rather than creating workers.
41
+ if (
42
+ args.some((arg) =>
43
+ /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
44
+ arg,
45
+ ),
46
+ )
47
+ )
48
+ return undefined;
49
+ const parentThreadId = ctx.sessionManager.getSessionId();
50
+ const relationship = { parentThreadId, subagentKind: "collab_spawn" };
51
+ return {
52
+ accept: async (agent: PaneInfo) => {
53
+ const file = sessionPath(agent);
54
+ if (!file) throw new Error("Spawned agent has no saved Pi session");
55
+ const value = await runtime.client.requestContext(
56
+ sessionContextPath(file),
57
+ {
58
+ operation: "bind-relationship",
59
+ relationship,
60
+ },
61
+ );
62
+ if (ctx.sessionManager.getSessionId() !== parentThreadId)
63
+ throw new Error("Controller session changed during spawn");
64
+ if (value === null)
65
+ return {
66
+ warning:
67
+ "Worker relationship marking requires Codex conversion on the target",
68
+ };
69
+ if (!isDeepStrictEqual(value, relationship))
70
+ throw new Error(
71
+ "Spawned agent did not adopt its parent relationship",
72
+ );
73
+ return undefined;
74
+ },
75
+ };
76
+ }
77
+
78
+ async prepare(
79
+ ctx: ExtensionContext,
80
+ runtime: ConnectedMachine,
81
+ name: string,
82
+ args: readonly string[] = [],
83
+ ) {
84
+ const service = this.getService();
85
+ if (!service?.canCreateChild(ctx)) return undefined;
86
+ const parent = service.describe(ctx);
87
+ if (!parent) return undefined;
88
+ if (
89
+ args.some((arg) =>
90
+ /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
91
+ arg,
92
+ ),
93
+ )
94
+ )
95
+ throw new Error(
96
+ "Shared context spawn cannot use profile session-selection arguments; use assign for existing agents",
97
+ );
98
+ const parentFile = ctx.sessionManager.getSessionFile();
99
+ if (!parentFile)
100
+ throw new Error(
101
+ "Shared context spawn requires a saved controller session",
102
+ );
103
+ const routing: Routing | undefined =
104
+ parent.storage === "session"
105
+ ? {
106
+ transport: "shepherdr",
107
+ parent: runtime.local
108
+ ? sessionContextPath(parentFile)
109
+ : runtime.client.contextRelayPath(),
110
+ }
111
+ : undefined;
112
+ const { binding, adopt } = await service.createChild(ctx, {
113
+ name,
114
+ ...(routing ? { routing } : {}),
115
+ });
116
+ return {
117
+ accept: async (agent: PaneInfo) => {
118
+ const sessionFile = sessionPath(agent);
119
+ if (!sessionFile)
120
+ throw new Error("Spawned agent has no native Pi session path");
121
+ const value = await runtime.client.requestContext(
122
+ sessionContextPath(sessionFile),
123
+ { operation: "bind", binding },
124
+ );
125
+ if (!value)
126
+ return {
127
+ warning:
128
+ "Spawned without shared context: the target needs Codex conversion with notes-based continuity",
129
+ };
130
+ if (
131
+ typeof value !== "object" ||
132
+ !("sessionId" in value) ||
133
+ value.sessionId !== binding.sessionId ||
134
+ !("agentName" in value) ||
135
+ value.agentName !== binding.agentName ||
136
+ !("storage" in value) ||
137
+ value.storage !== binding.storage ||
138
+ (binding.accountScope !== undefined &&
139
+ (!("accountScope" in value) ||
140
+ value.accountScope !== binding.accountScope))
141
+ )
142
+ throw new Error(
143
+ "Spawned agent did not adopt its shared context identity and storage mode",
144
+ );
145
+ if (ctx.sessionManager.getSessionId() !== parent.threadId)
146
+ throw new Error("Controller session changed during spawn");
147
+ await adopt();
148
+ this.pi.appendEntry<Member>(MEMBER_ENTRY, {
149
+ agentName: binding.agentName,
150
+ sessionId: parent.sessionId,
151
+ threadId: parent.threadId,
152
+ machine: runtime.machine,
153
+ sessionFile,
154
+ });
155
+ return { agentName: binding.agentName };
156
+ },
157
+ };
158
+ }
159
+ }