@howaboua/pi-shepherdr 0.2.28-core.12.1.gda85fa2e8a0f → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +34 -5
  3. package/biome.json +1 -1
  4. package/index.ts +5 -2
  5. package/package.json +19 -14
  6. package/src/agents-contract.ts +80 -61
  7. package/src/agents-discovery.ts +14 -10
  8. package/src/agents-focus.ts +7 -0
  9. package/src/agents-reply.ts +3 -12
  10. package/src/agents-spawn.ts +26 -2
  11. package/src/agents-tool.ts +57 -21
  12. package/src/agents-work.ts +9 -4
  13. package/src/ancestry-record.ts +116 -0
  14. package/src/attachment-notes.ts +3 -2
  15. package/src/attachment-protocol.ts +124 -68
  16. package/src/attachment-target.ts +8 -7
  17. package/src/attachment.ts +3 -3
  18. package/src/board/records.ts +50 -36
  19. package/src/close-idle.ts +2 -2
  20. package/src/controller.ts +5 -4
  21. package/src/core/backend.ts +26 -3
  22. package/src/core/helper-bootstrap.mjs +1 -1
  23. package/src/core/helper-core.mjs +4 -3
  24. package/src/core/helper-lifetime.mjs +199 -0
  25. package/src/core/remote-endpoint.ts +10 -3
  26. package/src/core/remote-helper.ts +3 -0
  27. package/src/core/remote-service.mjs +9 -0
  28. package/src/core/remote-transport.ts +11 -1
  29. package/src/core/spawn.ts +1 -1
  30. package/src/core/terminal-peer.mjs +26 -5
  31. package/src/core/terminal.ts +2 -1
  32. package/src/fleet/connection.ts +4 -0
  33. package/src/fleet/index.ts +24 -3
  34. package/src/launch-contract.ts +1 -0
  35. package/src/launch.ts +40 -3
  36. package/src/messages/attribution.ts +14 -5
  37. package/src/messages/focus.ts +4 -3
  38. package/src/messages/peer-sharing.ts +34 -20
  39. package/src/monitor-events.ts +10 -10
  40. package/src/monitor-extension-messages.ts +1 -0
  41. package/src/monitor.ts +5 -5
  42. package/src/profiles.ts +1 -8
  43. package/src/remote/shepherdr-session.mjs +43 -0
  44. package/src/settlement/delivery.ts +32 -14
  45. package/src/settlement/index.ts +3 -0
  46. package/src/shared-context.ts +4 -100
  47. package/src/spawn-ancestry.ts +103 -0
  48. package/src/spawn-ownership.ts +93 -5
  49. package/src/types.ts +1 -0
  50. package/src/worker-ownership.ts +41 -32
  51. package/src/worker-resume.ts +231 -0
  52. package/src/worker-role.ts +9 -35
  53. package/src/worker-service.ts +95 -59
  54. package/worker-api.ts +38 -0
  55. package/src/profile-prompt.ts +0 -32
@@ -1,6 +1,7 @@
1
1
  import type { AgentStatus, PaneInfo, SessionSnapshot } from "../types.js";
2
2
  import { object } from "./protocol.js";
3
3
  import { CORE_SESSION_LABEL, CORE_WORKER_LABEL } from "./registration.js";
4
+ import { livePiSession } from "./terminal-peer.mjs";
4
5
 
5
6
  export function terminalPane(value: unknown): PaneInfo {
6
7
  const terminal = object(value);
@@ -19,7 +20,7 @@ export function terminalPane(value: unknown): PaneInfo {
19
20
  state === "done"
20
21
  ? state
21
22
  : "unknown";
22
- const session = labels[CORE_SESSION_LABEL];
23
+ const session = livePiSession(terminal);
23
24
  const live = terminal["state"] === "live";
24
25
  return {
25
26
  // The shared legacy key is an address, not a fabricated app pane ID.
@@ -40,6 +40,10 @@ export async function connectMachine(
40
40
  client = new CoreConnection(
41
41
  process.env["HC_TERMINAL_SOCKET"],
42
42
  runtime.coreMachine,
43
+ (message) => {
44
+ if (events.isCurrent() && runtime.client === client)
45
+ ctx.ui.notify(`${runtime.coreMachine?.name}: ${message}`, "warning");
46
+ },
43
47
  );
44
48
  if (!events.isCurrent() || runtimes.get(name) !== runtime) {
45
49
  client.close();
@@ -2,7 +2,7 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
- import { CoreConnection } from "../core/backend.js";
5
+ import { CORE_REQUIRED, CoreConnection } from "../core/backend.js";
6
6
  import { CoreClient } from "../core/client.js";
7
7
  import { type CoreMachine, coreMachines } from "../core/machines.js";
8
8
  import { AgentMonitor } from "../monitor.js";
@@ -76,6 +76,7 @@ export class AgentFleet {
76
76
  );
77
77
  }
78
78
  private context: ExtensionContext | undefined;
79
+ private activationFailure: Error | undefined;
79
80
  private generation = 0;
80
81
  private readonly pi: ExtensionAPI;
81
82
  private readonly runtimes = new Map<string, MachineRuntime>();
@@ -98,8 +99,14 @@ export class AgentFleet {
98
99
  try {
99
100
  coreId = (await identityClient.machineIdentity()).session;
100
101
  } catch (error) {
102
+ const reason =
103
+ error instanceof Error &&
104
+ "code" in error &&
105
+ typeof error.code === "string"
106
+ ? "Core is unreachable"
107
+ : errorMessage(error);
101
108
  throw new Error(
102
- `Shepherdr could not connect to Core: ${errorMessage(error)}. Start or reconnect Core, then retry from a Core terminal.`,
109
+ `Shepherdr could not connect to Core: ${reason}. Start or reconnect Core, then open /herdr → Status to retry.`,
103
110
  { cause: error },
104
111
  );
105
112
  } finally {
@@ -170,8 +177,9 @@ export class AgentFleet {
170
177
  void this.connectMachine(machine.id, generation, true);
171
178
  }
172
179
 
173
- deactivate(): void {
180
+ deactivate(activationFailure?: Error): void {
174
181
  this.generation += 1;
182
+ this.activationFailure = activationFailure;
175
183
  this.localCoreId = undefined;
176
184
  this.lastPersistedState = undefined;
177
185
  for (const runtime of this.runtimes.values()) {
@@ -188,6 +196,17 @@ export class AgentFleet {
188
196
  return this.context !== undefined;
189
197
  }
190
198
 
199
+ inactiveError(): Error {
200
+ if (!process.env["HC_TERMINAL_ID"] || !process.env["HC_TERMINAL_SOCKET"])
201
+ return new Error(CORE_REQUIRED);
202
+ return (
203
+ this.activationFailure ??
204
+ new Error(
205
+ "Agent operations are unavailable; open /herdr → Status to reconnect Core. Help and current-session command discovery remain available.",
206
+ )
207
+ );
208
+ }
209
+
191
210
  async reload(): Promise<void> {
192
211
  const ctx = this.context;
193
212
  if (!ctx) return;
@@ -216,6 +235,7 @@ export class AgentFleet {
216
235
  }
217
236
  connected(machine?: string): ConnectedMachine {
218
237
  const ctx = this.context;
238
+ if (!ctx) throw this.inactiveError();
219
239
  return connectedMachine(
220
240
  this.runtimes,
221
241
  ctx,
@@ -249,6 +269,7 @@ export class AgentFleet {
249
269
  }
250
270
 
251
271
  async snapshots(machine?: string): Promise<MachineSnapshot[]> {
272
+ if (!this.isActive()) throw this.inactiveError();
252
273
  return machineSnapshots(this.runtimes, machine);
253
274
  }
254
275
  connect(machine?: string): string {
@@ -12,6 +12,7 @@ export interface StartAgentParams {
12
12
  name?: string;
13
13
  placement?: (typeof START_PLACEMENTS)[number];
14
14
  workspace?: string;
15
+ outliveParent?: true;
15
16
  }
16
17
 
17
18
  export interface CreatedLocationCleanup {
package/src/launch.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import { parseArgs } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ ANCESTRY_FLAG,
6
+ parseSpawnAncestry,
7
+ type SpawnAncestry,
8
+ } from "./ancestry-record.js";
4
9
  import type { CoreConnection } from "./core/backend.js";
5
10
  import { startCoreAgent } from "./core/spawn.js";
6
11
  import {
@@ -48,9 +53,33 @@ export async function resolvePreparationDirectory(
48
53
  return resolveDirectory(params.cwd, fallbackCwd);
49
54
  }
50
55
 
51
- interface StartAgentOptions {
56
+ export interface StartAgentOptions {
52
57
  agentArgs?: string[];
53
58
  signal?: AbortSignal;
59
+ ancestry?: SpawnAncestry;
60
+ }
61
+
62
+ // Pi restores these from the session. Initial profile defaults must not reset them.
63
+ export function resumeAgentArgs(args: readonly string[]): string[] {
64
+ const restored = new Set([
65
+ "--model",
66
+ "--provider",
67
+ "--thinking",
68
+ "--name",
69
+ "-n",
70
+ "--shepherdr-profile-prompt",
71
+ ]);
72
+ const result: string[] = [];
73
+ for (let index = 0; index < args.length; index += 1) {
74
+ const arg = args[index]!;
75
+ if (restored.has(arg)) {
76
+ index += 1;
77
+ continue;
78
+ }
79
+ if ([...restored].some((flag) => arg.startsWith(`${flag}=`))) continue;
80
+ result.push(arg);
81
+ }
82
+ return result;
54
83
  }
55
84
 
56
85
  export async function startAgent(
@@ -67,11 +96,19 @@ export async function startAgent(
67
96
  );
68
97
  }
69
98
  const label = params.label?.trim() || name;
99
+ const resuming = options.agentArgs?.some((arg) =>
100
+ /^--session(?:=|$)/.test(arg),
101
+ );
70
102
  const args = [
71
103
  `--${WORKER_FLAG}`,
72
- "--name",
73
- label,
104
+ ...(resuming && !params.label?.trim() ? [] : ["--name", label]),
74
105
  ...(options.agentArgs ?? []),
106
+ ...(options.ancestry
107
+ ? [
108
+ `--${ANCESTRY_FLAG}`,
109
+ JSON.stringify(parseSpawnAncestry(options.ancestry)),
110
+ ]
111
+ : []),
75
112
  ];
76
113
  const parsed = parseArgs(args);
77
114
  if (parsed.unknownFlags.get(WORKER_FLAG) !== true) {
@@ -4,8 +4,6 @@ import type { PaneInfo, PeerMessage } from "../types.js";
4
4
 
5
5
  const DELEGATED_WORKER_GUIDANCE =
6
6
  "If blocked mid-run, use a question-asking tool, not peer messages. Without one, end with the blocker. Finish with an assistant reply, not a separate send report; never watch your parent.";
7
- const PEER_MESSAGE_GUIDANCE =
8
- "A peer message does not make you the sender's sub-agent or establish shared context.";
9
7
 
10
8
  export function xml(value: string): string {
11
9
  return value
@@ -51,8 +49,10 @@ export function sourceAttributes(
51
49
 
52
50
  export async function attributeAgentPrompt(
53
51
  client: CoreConnection,
52
+ sessionId: string,
54
53
  message: string,
55
54
  kind: "message" | "task",
55
+ initialProfile?: string,
56
56
  ): Promise<PeerMessage> {
57
57
  const [pane, snapshot] = await Promise.all([
58
58
  getCurrentPane(client),
@@ -62,9 +62,12 @@ export async function attributeAgentPrompt(
62
62
  (workspace) => workspace.workspace_id === pane.workspace_id,
63
63
  )?.label;
64
64
  const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
65
+ const identity = await client.machineIdentity();
65
66
  const source = {
66
67
  kind,
67
- ...(await client.machineIdentity()),
68
+ host: identity.host,
69
+ machine: identity.session,
70
+ agent: `/${sessionId}`,
68
71
  ...agentSource(pane, {
69
72
  ...(workspace ? { workspace } : {}),
70
73
  ...(tab ? { tab } : {}),
@@ -73,7 +76,13 @@ export async function attributeAgentPrompt(
73
76
  return {
74
77
  sender: `<herdr_sender ${sourceAttributes(source)} />`,
75
78
  text: message,
76
- context:
77
- kind === "task" ? DELEGATED_WORKER_GUIDANCE : PEER_MESSAGE_GUIDANCE,
79
+ context: [
80
+ ...(initialProfile
81
+ ? [
82
+ `<initial_worker_profile>\n${initialProfile}\n</initial_worker_profile>`,
83
+ ]
84
+ : []),
85
+ ...(kind === "task" ? [DELEGATED_WORKER_GUIDANCE] : []),
86
+ ].join("\n\n"),
78
87
  };
79
88
  }
@@ -3,7 +3,8 @@ import type { FocusRequest } from "../types.js";
3
3
  function focusOrigin({ source }: FocusRequest) {
4
4
  return {
5
5
  host: source.host,
6
- session: source.session,
6
+ machine: source.session,
7
+ ...(source.agent ? { agent: source.agent } : {}),
7
8
  terminal: source.terminal,
8
9
  };
9
10
  }
@@ -23,12 +24,12 @@ export function focusArrivalContent(
23
24
  const callable = codeMode ? `await tools.agents(${args})` : `agents ${args}`;
24
25
  return {
25
26
  returnFocus,
26
- content: `User arrived from ${JSON.stringify({ ...focusOrigin(request), machine })}\nReturn: ${callable}${request.voice ? "\nVoice transfer pending" : ""}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`,
27
+ content: `User arrived from ${JSON.stringify(focusOrigin(request))}\nReturn: ${callable}${request.voice ? "\nVoice transfer pending" : ""}${request.handoff ? `\nHandoff from that agent:\n${request.handoff}` : ""}`,
27
28
  };
28
29
  }
29
30
 
30
31
  export function voiceFocusContinuity(request: FocusRequest): string {
31
- return `User transferring voice from ${JSON.stringify(focusOrigin(request))}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`;
32
+ return `User transferring voice from ${JSON.stringify(focusOrigin(request))}${request.handoff ? `\nHandoff from that agent:\n${request.handoff}` : ""}`;
32
33
  }
33
34
 
34
35
  export function voiceFocusReport(
@@ -1,12 +1,19 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ compile,
5
+ nul,
6
+ obj,
7
+ type Static,
8
+ str,
9
+ union,
10
+ } from "@earendil-works/pi-schema";
3
11
  import type { ContextSharingService } from "@howaboua/pi-agent-comms/context-sharing";
4
- import { type Static, Type } from "typebox";
5
- import { Check } from "typebox/value";
6
12
  import {
7
13
  attachmentOwner,
8
14
  attachmentRoutes,
9
15
  canonicalContextIdentity,
16
+ checkIdentity,
10
17
  detachment,
11
18
  Identity,
12
19
  } from "../attachment-protocol.js";
@@ -17,11 +24,15 @@ import { sessionContextPath } from "../remote/shepherdr-context.mjs";
17
24
  import { MEMBER_ENTRY } from "../spawn-context.js";
18
25
  import type { PaneInfo } from "../types.js";
19
26
 
20
- const Sharing = Type.Object({
21
- sessionId: Type.String({ minLength: 1 }),
22
- notes: Type.Union([Identity, Type.Null()]),
23
- boardId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
24
- });
27
+ const Sharing = obj(
28
+ {
29
+ sessionId: str({ minLength: 1 }),
30
+ notes: union([Identity, nul()]),
31
+ boardId: union([str({ minLength: 1 }), nul()]),
32
+ },
33
+ { open: true },
34
+ );
35
+ const checkSharing = compile(Sharing).check;
25
36
  type Sharing = Static<typeof Sharing>;
26
37
  type Access = "shared" | "not shared" | "retained checkpoints only" | "unknown";
27
38
 
@@ -32,7 +43,7 @@ export function describePeerSharing(
32
43
  board: AgentBoard,
33
44
  ): Sharing {
34
45
  const notes = service?.describe(ctx);
35
- if (notes && !Check(Identity, notes))
46
+ if (notes && !checkIdentity(notes))
36
47
  throw new Error("Sharing status unavailable");
37
48
  return {
38
49
  sessionId: ctx.sessionManager.getSessionId(),
@@ -82,15 +93,18 @@ function notesAccess(
82
93
  !from.routing &&
83
94
  !owner?.context &&
84
95
  !routes.some((route) => route.plan.context) &&
85
- !ctx.sessionManager
86
- .getEntries()
87
- .some(
88
- (entry) =>
89
- entry.type === "custom" &&
90
- entry.customType === MEMBER_ENTRY &&
91
- (entry.data as { threadId?: unknown } | undefined)?.threadId ===
92
- from.threadId,
93
- )
96
+ !ctx.sessionManager.getEntries().some(
97
+ (entry) =>
98
+ entry.type === "custom" &&
99
+ entry.customType === MEMBER_ENTRY &&
100
+ (
101
+ entry.data as
102
+ | {
103
+ threadId?: unknown;
104
+ }
105
+ | undefined
106
+ )?.threadId === from.threadId,
107
+ )
94
108
  )
95
109
  return "not shared";
96
110
  return "unknown";
@@ -109,14 +123,14 @@ export async function peerReplyContext(
109
123
  try {
110
124
  const file = sessionPath(panel);
111
125
  if (!file) throw new Error("Target has no saved session");
112
- const deadline = AbortSignal.timeout(2_000);
126
+ const deadline = AbortSignal.timeout(2000);
113
127
  const result = await runtime.client.requestContext(
114
128
  sessionContextPath(file),
115
129
  { operation: "peer-sharing" },
116
130
  signal ? AbortSignal.any([signal, deadline]) : deadline,
117
131
  );
118
132
  if (
119
- !Check(Sharing, result) ||
133
+ !checkSharing(result) ||
120
134
  (result.notes && result.notes.threadId !== result.sessionId)
121
135
  )
122
136
  throw new Error("Sharing status unavailable");
@@ -129,5 +143,5 @@ export async function peerReplyContext(
129
143
  // visible rather than turning a failed lookup into an access claim.
130
144
  signal?.throwIfAborted();
131
145
  }
132
- return `Sender access at send time — your current Notes: ${notes}; your current Board: ${board}.`;
146
+ return `Sender access: your Notes ${notes}; your Board ${board}`;
133
147
  }
@@ -114,7 +114,7 @@ export class MonitorEvents {
114
114
  () => {
115
115
  if (this.isLive(candidate)) this.options.onChange();
116
116
  },
117
- (error) => this.disconnected(candidate, error),
117
+ () => this.disconnected(candidate),
118
118
  candidate.controller.signal,
119
119
  );
120
120
  if (!this.isLive(candidate) || key !== this.targetKey()) {
@@ -141,7 +141,7 @@ export class MonitorEvents {
141
141
  )
142
142
  return;
143
143
  const failure = error instanceof Error ? error : new Error(String(error));
144
- this.warn(failure.message);
144
+ this.warn();
145
145
  if (this.options.reconnect === false) throw failure;
146
146
  this.scheduleReconnect();
147
147
  } finally {
@@ -170,25 +170,25 @@ export class MonitorEvents {
170
170
  subscription?.unsubscribe();
171
171
  }
172
172
 
173
- private disconnected(attempt: SubscriptionAttempt, error?: Error): void {
173
+ private disconnected(attempt: SubscriptionAttempt): void {
174
174
  if (!this.isLive(attempt)) return;
175
175
  if (this.subscription?.attempt === attempt) this.closeSubscription();
176
176
  if (this.pending === attempt) this.cancelPending();
177
- this.warn(error?.message ?? "event stream closed");
177
+ this.warn();
178
178
  this.scheduleReconnect();
179
179
  }
180
180
 
181
- private warn(detail: string): void {
181
+ private warn(): void {
182
182
  const state = this.subscription ? "degraded" : "unavailable";
183
183
  if (this.warning === state) return;
184
184
  this.warning = state;
185
185
  const message =
186
186
  state === "degraded"
187
- ? "Core monitor update failed. Existing stream retained, coverage may be incomplete"
188
- : "Core monitoring unavailable";
187
+ ? "Some agent status updates may be delayed. Existing monitoring is still active."
188
+ : "Agent status updates are unavailable.";
189
189
  this.options.onWarning({
190
190
  state,
191
- message: `${message}: ${detail}${this.options.reconnect === false ? "" : ". Retrying"}`,
191
+ message: `${message}${this.options.reconnect === false ? "" : " Retrying automatically."}`,
192
192
  });
193
193
  }
194
194
 
@@ -209,9 +209,9 @@ export class MonitorEvents {
209
209
  const epoch = this.epoch;
210
210
  this.reconnectTimer = setTimeout(() => {
211
211
  this.reconnectTimer = undefined;
212
- void this.retry().catch((error) => {
212
+ void this.retry().catch(() => {
213
213
  if (!this.active || epoch !== this.epoch) return;
214
- this.warn(error instanceof Error ? error.message : String(error));
214
+ this.warn();
215
215
  this.scheduleReconnect();
216
216
  });
217
217
  }, 1_000);
@@ -103,6 +103,7 @@ export class MonitorExtensionMessages {
103
103
  return;
104
104
  }
105
105
  this.unsubscribe = close;
106
+ this.warned = false;
106
107
  }
107
108
  this.key = key;
108
109
  }
package/src/monitor.ts CHANGED
@@ -206,6 +206,9 @@ export class AgentMonitor {
206
206
  ): Promise<ClaimedSettlement> | undefined {
207
207
  return this.settlements.claim(attempt, signal, replyingTo);
208
208
  }
209
+ observeReply(attempt: WorkAttempt, reply: ExtensionReply): void {
210
+ this.settlements.observeReply(attempt, reply);
211
+ }
209
212
 
210
213
  noteMessage(paneId: string, message: string): void {
211
214
  if (this.state.noteMessage(paneId, message)) this.persist();
@@ -312,12 +315,9 @@ export class AgentMonitor {
312
315
  await this.reconcile(generation, context);
313
316
  }
314
317
  })
315
- .catch((error) => {
318
+ .catch(() => {
316
319
  if (generation === this.activationGeneration) {
317
- this.context?.ui.notify(
318
- `Core monitoring reconciliation failed: ${String(error)}`,
319
- "warning",
320
- );
320
+ // The subscription owner reports unavailable coverage and recovery.
321
321
  void this.events.retry().catch(() => undefined);
322
322
  }
323
323
  })
package/src/profiles.ts CHANGED
@@ -13,7 +13,6 @@ import {
13
13
  import { homedir } from "node:os";
14
14
  import { join, resolve } from "node:path";
15
15
  import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { PROFILE_PROMPT_FLAG } from "./profile-prompt.js";
17
16
 
18
17
  const PROFILE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
19
18
  const AGENT_DIRECTORY =
@@ -260,18 +259,12 @@ export async function loadAgentProfiles(): Promise<Map<string, AgentProfile>> {
260
259
  return profiles;
261
260
  }
262
261
 
263
- export function profileAgentArgs(
264
- profile: AgentProfile,
265
- options: { includePrompt?: boolean } = {},
266
- ): string[] {
267
- const prompt = options.includePrompt === false ? undefined : profile.prompt;
262
+ export function profileAgentArgs(profile: AgentProfile): string[] {
268
263
  return [
269
264
  "--model",
270
265
  profile.model,
271
266
  "--thinking",
272
267
  profile.thinking,
273
- // JSON keeps newlines/control characters out of argv without altering role text.
274
- ...(prompt ? [`--${PROFILE_PROMPT_FLAG}`, JSON.stringify(prompt)] : []),
275
268
  ...profile.piArgs,
276
269
  ];
277
270
  }
@@ -256,3 +256,46 @@ export async function readSessionView(path) {
256
256
  });
257
257
  return result;
258
258
  }
259
+
260
+ /** Native session identity only; never create or load an entire transcript.
261
+ * @param {string} path
262
+ * @returns {Promise<{id:string,cwd:string}>}
263
+ */
264
+ export async function readSessionHeader(path) {
265
+ const file = await open(expandHome(path), "r").catch((cause) => {
266
+ throw new Error(
267
+ "Saved worker session could not be opened; check that its file is available on the original machine",
268
+ { cause },
269
+ );
270
+ });
271
+ try {
272
+ const bytes = Buffer.alloc(64 * 1024);
273
+ let size = 0;
274
+ while (size < bytes.length) {
275
+ const read = await file.read(bytes, size, bytes.length - size, size);
276
+ size += read.bytesRead;
277
+ const end = bytes.subarray(0, size).indexOf(10);
278
+ if (end >= 0 || read.bytesRead === 0) {
279
+ const header = record(
280
+ JSON.parse(bytes.subarray(0, end < 0 ? size : end).toString("utf8")),
281
+ );
282
+ if (
283
+ header?.["type"] !== "session" ||
284
+ typeof header["id"] !== "string" ||
285
+ !header["id"] ||
286
+ typeof header["cwd"] !== "string" ||
287
+ !header["cwd"]
288
+ )
289
+ throw new Error(
290
+ "Saved worker has no valid Pi session header; open its saved session manually",
291
+ );
292
+ return { id: header["id"], cwd: header["cwd"] };
293
+ }
294
+ }
295
+ throw new Error(
296
+ "Saved worker session header is too large; open its saved session manually",
297
+ );
298
+ } finally {
299
+ await file.close();
300
+ }
301
+ }
@@ -18,13 +18,16 @@ export interface ClaimedSettlement extends CollectedSettlement {
18
18
  record: MonitoredAgent;
19
19
  }
20
20
 
21
- interface SettlementClaim {
22
- replyingTo?: ExtensionReply;
21
+ interface SettlementWaiter {
23
22
  cleanup(): void;
24
23
  reject(error: Error): void;
25
24
  resolve(settlement: ClaimedSettlement): void;
26
25
  }
27
26
 
27
+ type SettlementClaim =
28
+ | { replyingTo: ExtensionReply; waiter?: SettlementWaiter }
29
+ | { replyingTo?: ExtensionReply; waiter: SettlementWaiter };
30
+
28
31
  /** Claims are per-attempt capabilities; delivery chooses exactly one waiter or controller. */
29
32
  export class SettlementDelivery {
30
33
  private readonly claims = new Map<string, SettlementClaim>();
@@ -44,10 +47,17 @@ export class SettlementDelivery {
44
47
  replyingTo(attemptId: string) {
45
48
  return this.claims.get(attemptId)?.replyingTo;
46
49
  }
50
+ observeReply(attempt: WorkAttempt, reply: ExtensionReply): void {
51
+ const claim = this.claims.get(attempt.attemptId);
52
+ this.claims.set(attempt.attemptId, {
53
+ ...(claim?.waiter ? { waiter: claim.waiter } : {}),
54
+ replyingTo: reply,
55
+ });
56
+ }
47
57
  stop() {
48
58
  for (const claim of this.claims.values()) {
49
- claim.cleanup();
50
- claim.reject(new Error("Shepherdr monitor stopped"));
59
+ claim.waiter?.cleanup();
60
+ claim.waiter?.reject(new Error("Shepherdr monitor stopped"));
51
61
  }
52
62
  this.claims.clear();
53
63
  }
@@ -58,13 +68,15 @@ export class SettlementDelivery {
58
68
  ): Promise<ClaimedSettlement> | undefined {
59
69
  signal.throwIfAborted();
60
70
  // Updates share the worker's current settlement, without stealing its waiter.
61
- if (this.claims.has(attempt.attemptId)) return;
71
+ const existing = this.claims.get(attempt.attemptId);
72
+ if (existing?.waiter) return;
73
+ const reply = replyingTo ?? existing?.replyingTo;
62
74
  return new Promise<ClaimedSettlement>((resolve, reject) => {
63
75
  const abort = () => {
64
76
  const claim = this.claims.get(attempt.attemptId);
65
77
  if (!claim) return;
66
78
  this.claims.delete(attempt.attemptId);
67
- claim.cleanup();
79
+ claim.waiter?.cleanup();
68
80
  reject(
69
81
  signal.reason instanceof Error
70
82
  ? signal.reason
@@ -72,10 +84,12 @@ export class SettlementDelivery {
72
84
  );
73
85
  };
74
86
  const claim: SettlementClaim = {
75
- ...(replyingTo ? { replyingTo } : {}),
76
- cleanup: () => signal.removeEventListener("abort", abort),
77
- reject,
78
- resolve,
87
+ ...(reply ? { replyingTo: reply } : {}),
88
+ waiter: {
89
+ cleanup: () => signal.removeEventListener("abort", abort),
90
+ reject,
91
+ resolve,
92
+ },
79
93
  };
80
94
  this.claims.set(attempt.attemptId, claim);
81
95
  signal.addEventListener("abort", abort, { once: true });
@@ -96,8 +110,10 @@ export class SettlementDelivery {
96
110
  const claim = this.claims.get(attemptId);
97
111
  if (!claim) return;
98
112
  this.claims.delete(attemptId);
99
- claim.cleanup();
100
- claim.reject(error instanceof Error ? error : new Error(String(error)));
113
+ claim.waiter?.cleanup();
114
+ claim.waiter?.reject(
115
+ error instanceof Error ? error : new Error(String(error)),
116
+ );
101
117
  }
102
118
 
103
119
  deliverSettlement(
@@ -111,13 +127,15 @@ export class SettlementDelivery {
111
127
  const claim = attemptId ? this.claims.get(attemptId) : undefined;
112
128
  if (claim && attemptId) {
113
129
  this.claims.delete(attemptId);
114
- claim.cleanup();
130
+ }
131
+ if (claim?.waiter) {
132
+ claim.waiter.cleanup();
115
133
  const {
116
134
  reply: _latestReply,
117
135
  session: _session,
118
136
  ...claimedSettlement
119
137
  } = settlement;
120
- claim.resolve({
138
+ claim.waiter.resolve({
121
139
  ...claimedSettlement,
122
140
  record,
123
141
  ...(blockedMessage ? { blockedMessage } : {}),
@@ -112,6 +112,9 @@ export class SettlementReporter {
112
112
  ) {
113
113
  return this.delivery.claim(attempt, signal, replyingTo);
114
114
  }
115
+ observeReply(attempt: WorkAttempt, reply: ExtensionReply): void {
116
+ this.delivery.observeReply(attempt, reply);
117
+ }
115
118
  releaseClaim(attempt: WorkAttempt | undefined, error: unknown) {
116
119
  this.delivery.releaseClaim(attempt, error);
117
120
  }