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

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 (112) hide show
  1. package/README.md +48 -48
  2. package/index.ts +7 -1
  3. package/package.json +2 -9
  4. package/src/agent-identity.ts +3 -3
  5. package/src/agents-contract.ts +10 -14
  6. package/src/agents-discovery.ts +34 -54
  7. package/src/agents-focus.ts +23 -35
  8. package/src/agents-spawn.ts +24 -23
  9. package/src/agents-tool.ts +4 -19
  10. package/src/agents-work.ts +4 -3
  11. package/src/attachment-notes.ts +8 -7
  12. package/src/attachment-protocol.ts +3 -2
  13. package/src/attachment-routing.ts +1 -1
  14. package/src/attachment-target.ts +10 -18
  15. package/src/attachment.ts +14 -9
  16. package/src/board/discovery.ts +67 -0
  17. package/src/board/host.ts +93 -63
  18. package/src/board/membership.ts +16 -11
  19. package/src/board/records.ts +185 -0
  20. package/src/close-idle.ts +2 -9
  21. package/src/context-briefing.ts +230 -0
  22. package/src/context-routing.ts +1 -1
  23. package/src/control-panel/index.ts +2 -4
  24. package/src/control-panel/items.ts +1 -11
  25. package/src/control-panel/view.ts +3 -9
  26. package/src/controller.ts +50 -63
  27. package/src/core/AGENTS.md +7 -4
  28. package/src/core/admission-broker.mjs +235 -0
  29. package/src/core/admission-endpoint.ts +180 -0
  30. package/src/core/admission-owner.mjs +52 -0
  31. package/src/core/admission-startup.ts +130 -0
  32. package/src/core/admission.ts +181 -0
  33. package/src/core/agents.ts +102 -0
  34. package/src/core/backend.ts +110 -84
  35. package/src/core/client.ts +16 -0
  36. package/src/core/focus-channel-helper.mjs +6 -27
  37. package/src/core/focus-channel-wire.mjs +9 -6
  38. package/src/core/focus-channel.ts +5 -3
  39. package/src/core/focus-window.ts +15 -4
  40. package/src/core/helper-bootstrap.mjs +70 -0
  41. package/src/core/helper-context.mjs +98 -0
  42. package/src/core/helper-core.mjs +121 -0
  43. package/src/core/machines.ts +30 -0
  44. package/src/core/registration.ts +7 -2
  45. package/src/core/remote-endpoint.ts +80 -74
  46. package/src/core/remote-helper.ts +330 -0
  47. package/src/core/remote-reader.ts +3 -42
  48. package/src/core/remote-service.mjs +239 -0
  49. package/src/core/remote-transport.ts +290 -0
  50. package/src/core/spawn.ts +20 -20
  51. package/src/core/terminal-peer.mjs +57 -0
  52. package/src/core/terminal.ts +4 -2
  53. package/src/delivery.ts +39 -0
  54. package/src/fleet/catalog.ts +16 -58
  55. package/src/fleet/connection.ts +9 -18
  56. package/src/fleet/index.ts +38 -76
  57. package/src/fleet/inspection.ts +9 -22
  58. package/src/fleet/machine.ts +28 -12
  59. package/src/fleet/monitor.ts +8 -29
  60. package/src/fleet/persistence.ts +2 -2
  61. package/src/fleet/reconnect.ts +5 -3
  62. package/src/fleet/setup.ts +6 -16
  63. package/src/launch-contract.ts +0 -3
  64. package/src/launch-location.ts +4 -132
  65. package/src/launch.ts +18 -144
  66. package/src/messages/attachments.ts +1 -1
  67. package/src/messages/attribution.ts +9 -14
  68. package/src/messages/events.ts +5 -9
  69. package/src/messages/focus.ts +2 -7
  70. package/src/messages/guidance.ts +2 -43
  71. package/src/messages/peer-sharing.ts +133 -0
  72. package/src/monitor-events.ts +14 -43
  73. package/src/monitor-extension-messages.ts +5 -6
  74. package/src/monitor-record.ts +4 -0
  75. package/src/monitor-state.ts +1 -101
  76. package/src/monitor.ts +38 -66
  77. package/src/notes-discovery.ts +67 -0
  78. package/src/peer-inbox.ts +21 -27
  79. package/src/remote/context-relay.ts +25 -10
  80. package/src/remote/notes-reader.mjs +67 -0
  81. package/src/remote/shepherdr-channel.mjs +1 -1
  82. package/src/remote/shepherdr-checkpoints.mjs +49 -102
  83. package/src/remote/shepherdr-context.mjs +1 -1
  84. package/src/remote/shepherdr-peer.mjs +19 -24
  85. package/src/remote/shepherdr-session.mjs +18 -7
  86. package/src/saved-context.ts +62 -0
  87. package/src/settlement/collector.ts +29 -9
  88. package/src/settlement/index.ts +35 -6
  89. package/src/shared-context-host.ts +27 -33
  90. package/src/shared-context.ts +44 -15
  91. package/src/spawn-context.ts +11 -3
  92. package/src/spawn-ownership.ts +1 -1
  93. package/src/ssh-setup.ts +40 -73
  94. package/src/types.ts +4 -8
  95. package/src/voice-handoff.ts +1 -1
  96. package/src/widget.ts +7 -2
  97. package/src/worker-ownership.ts +2 -8
  98. package/src/worker-service.ts +6 -14
  99. package/src/core/context-relay.mjs +0 -111
  100. package/src/core/remote-exec.ts +0 -122
  101. package/src/core/remote-helper.mjs +0 -244
  102. package/src/core/remote-relay.ts +0 -191
  103. package/src/core/request.ts +0 -124
  104. package/src/herdr-client.ts +0 -364
  105. package/src/herdr.ts +0 -268
  106. package/src/machine-catalog.ts +0 -83
  107. package/src/monitor-event.ts +0 -84
  108. package/src/remote/client.ts +0 -127
  109. package/src/remote/deployment.ts +0 -179
  110. package/src/remote/focus-channels.ts +0 -89
  111. package/src/remote/shepherdr.mjs +0 -504
  112. package/src/remote/transport.ts +0 -369
package/src/peer-inbox.ts CHANGED
@@ -5,11 +5,10 @@ import type {
5
5
  ExtensionAPI,
6
6
  ExtensionContext,
7
7
  } from "@earendil-works/pi-coding-agent";
8
+ import { getAgent, sessionPath } from "./core/agents.js";
8
9
  import { coreIdentity, publishCoreSession } from "./core/registration.js";
9
10
  import { dispatchExtensionReply } from "./extension-reply.js";
10
11
  import type { AgentFleet } from "./fleet/index.js";
11
- import { getAgent, getCurrentPane, sessionPath } from "./herdr.js";
12
- import { HerdrClient } from "./herdr-client.js";
13
12
  import type { createPeerCommands } from "./peer-commands.js";
14
13
  import { PeerInboxDelivery } from "./peer-inbox-delivery.js";
15
14
  import { receivePeerFocus } from "./peer-inbox-focus.js";
@@ -26,21 +25,16 @@ export function registerPeerInbox(
26
25
  catchup: (
27
26
  ctx: ExtensionContext,
28
27
  ) => Promise<{ content: string; accepted: () => void }>,
28
+ isWorker: (ctx: ExtensionContext) => boolean,
29
29
  ): void {
30
30
  let close: (() => Promise<void>) | undefined;
31
31
  let running = false;
32
32
  let generation = 0;
33
33
  const publish = async (ctx: ExtensionContext) => {
34
34
  const core = coreIdentity(ctx);
35
- if (
36
- !core &&
37
- (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
38
- )
39
- return;
40
- if (core) {
41
- await close?.();
42
- close = undefined;
43
- }
35
+ if (!core) return;
36
+ await close?.();
37
+ close = undefined;
44
38
  close = await openInbox(
45
39
  pi,
46
40
  ctx,
@@ -49,6 +43,7 @@ export function registerPeerInbox(
49
43
  commands,
50
44
  fleet,
51
45
  catchup,
46
+ isWorker(ctx),
52
47
  );
53
48
  };
54
49
  pi.on("before_agent_start", () => {
@@ -81,25 +76,24 @@ async function openInbox(
81
76
  catchup: (
82
77
  ctx: ExtensionContext,
83
78
  ) => Promise<{ content: string; accepted: () => void }>,
79
+ worker: boolean,
84
80
  ): Promise<() => Promise<void>> {
85
81
  const sessionFile = ctx.sessionManager.getSessionFile();
86
82
  if (!sessionFile)
87
83
  throw new Error("Shepherdr peer delivery requires a saved Pi session");
88
84
  const core = coreIdentity(ctx);
89
- const pane = core
90
- ? {
91
- backend: "core" as const,
92
- pane_id: core.terminalId,
93
- terminal_id: core.terminalId,
94
- agent_status: "unknown" as const,
95
- agent_session: {
96
- agent: "pi",
97
- kind: "path" as const,
98
- source: "pi.session_file",
99
- value: sessionFile,
100
- },
101
- }
102
- : await getCurrentPane(new HerdrClient());
85
+ if (!core) throw new Error("Peer delivery requires a Core terminal");
86
+ const pane = {
87
+ pane_id: core.terminalId,
88
+ terminal_id: core.terminalId,
89
+ agent_status: "unknown" as const,
90
+ agent_session: {
91
+ agent: "pi",
92
+ kind: "path" as const,
93
+ source: "pi.session_file",
94
+ value: sessionFile,
95
+ },
96
+ };
103
97
  const terminalId = pane.terminal_id;
104
98
  if (!terminalId)
105
99
  throw new Error("Shepherdr peer receiver has no terminal identity");
@@ -257,7 +251,7 @@ async function openInbox(
257
251
  }
258
252
  try {
259
253
  const livePane = await getAgent(
260
- core ? fleet.connected().client : new HerdrClient(),
254
+ fleet.connected().client,
261
255
  pane.pane_id,
262
256
  );
263
257
  if (
@@ -365,7 +359,7 @@ async function openInbox(
365
359
  { mode: 0o600, flag: "wx" },
366
360
  );
367
361
  await rename(temporary, path);
368
- if (core) clearCoreSession = await publishCoreSession(core, sessionFile);
362
+ clearCoreSession = await publishCoreSession(core, sessionFile, worker);
369
363
  } catch (error) {
370
364
  try {
371
365
  await unlink(temporary).catch((failure: NodeJS.ErrnoException) => {
@@ -1,5 +1,3 @@
1
- import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
-
3
1
  /** Owns relay handlers and incoming cancellation; transport shutdown aborts the whole relay. */
4
2
  export class ContextRelay {
5
3
  private contextHandler:
@@ -7,17 +5,20 @@ export class ContextRelay {
7
5
  | undefined;
8
6
  private readonly incomingContext = new Map<string, AbortController>();
9
7
  private relayPath: string | undefined;
10
- private readonly child: ChildProcessWithoutNullStreams;
8
+ private readonly send: (message: Record<string, unknown>) => void;
11
9
  private readonly closed: () => boolean;
12
10
  private readonly maxFrameBytes: number;
11
+ private readonly onFailure: (error: Error) => void;
13
12
  constructor(
14
- child: ChildProcessWithoutNullStreams,
13
+ send: (message: Record<string, unknown>) => void,
15
14
  closed: () => boolean,
16
15
  maxFrameBytes: number,
16
+ onFailure: (error: Error) => void,
17
17
  ) {
18
- this.child = child;
18
+ this.send = send;
19
19
  this.closed = closed;
20
20
  this.maxFrameBytes = maxFrameBytes;
21
+ this.onFailure = onFailure;
21
22
  }
22
23
  async start(
23
24
  threadId: string,
@@ -50,10 +51,19 @@ export class ContextRelay {
50
51
  this.incomingContext.set(id, controller);
51
52
  const reply = (data: object) => {
52
53
  if (this.closed() || controller.signal.aborted) return;
53
- let frame = `${JSON.stringify({ op: "context_reply", id, ...data })}\n`;
54
- if (Buffer.byteLength(frame) > this.maxFrameBytes)
55
- frame = `${JSON.stringify({ op: "context_reply", id, ok: false, error: "Shared context response is too large" })}\n`;
56
- this.child.stdin.write(frame);
54
+ let frame: Record<string, unknown> = {
55
+ op: "context_reply",
56
+ id,
57
+ ...data,
58
+ };
59
+ if (Buffer.byteLength(JSON.stringify(frame)) > this.maxFrameBytes)
60
+ frame = {
61
+ op: "context_reply",
62
+ id,
63
+ ok: false,
64
+ error: "Shared context response is too large",
65
+ };
66
+ this.send(frame);
57
67
  };
58
68
  void Promise.resolve()
59
69
  .then(() => {
@@ -72,7 +82,12 @@ export class ContextRelay {
72
82
  )
73
83
  .finally(() => {
74
84
  this.incomingContext.delete(id);
75
- });
85
+ })
86
+ .catch((error: unknown) =>
87
+ this.onFailure(
88
+ error instanceof Error ? error : new Error(String(error)),
89
+ ),
90
+ );
76
91
  return true;
77
92
  }
78
93
  return false;
@@ -0,0 +1,67 @@
1
+ import { createRequire } from "node:module";
2
+ import { pathToFileURL } from "node:url";
3
+
4
+ const packages = ["@howaboua/pi-agent-comms", "@howaboua/pi-notes-compaction"];
5
+ export const NOTES_READER_UNAVAILABLE =
6
+ "Saved Notes reads are unavailable. Install Agent Comms or Notes Compaction alongside Shepherdr, then reload Pi. Other agent operations remain available.";
7
+ const INVALID_READER =
8
+ "Saved Notes could not be loaded. Update their extension and reload Pi. Other agent operations remain available.";
9
+
10
+ /** Public Node-only readers have no event API. Resolve only on their optional boundary.
11
+ * @param {"saved-session" | "saved-session-index"} name
12
+ * @returns {URL | undefined}
13
+ */
14
+ export function notesModule(name) {
15
+ const require = createRequire(import.meta.url);
16
+ for (const packageName of packages) {
17
+ const specifier = `${packageName}/${name}`;
18
+ try {
19
+ return pathToFileURL(require.resolve(specifier));
20
+ } catch (error) {
21
+ if (
22
+ !(error instanceof Error) ||
23
+ !("code" in error) ||
24
+ !(
25
+ error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
26
+ (error.code === "MODULE_NOT_FOUND" &&
27
+ error.message.startsWith(`Cannot find module '${specifier}'`))
28
+ )
29
+ )
30
+ throw new Error(INVALID_READER, { cause: error });
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ /** @param {URL} url */
37
+ async function loadReader(url) {
38
+ try {
39
+ return await import(url.href);
40
+ } catch (error) {
41
+ throw new Error(INVALID_READER, { cause: error });
42
+ }
43
+ }
44
+
45
+ /** @param {string} path @param {AbortSignal} [signal] @param {boolean} [history]
46
+ * @returns {ReturnType<typeof import("@howaboua/pi-agent-comms/saved-session").readSavedNotesSession>}
47
+ */
48
+ export async function readSavedNotesSession(path, signal, history = false) {
49
+ signal?.throwIfAborted();
50
+ const url = notesModule("saved-session");
51
+ if (!url) throw new Error(NOTES_READER_UNAVAILABLE);
52
+ const reader = await loadReader(url);
53
+ if (typeof reader.readSavedNotesSession !== "function")
54
+ throw new Error(INVALID_READER);
55
+ return reader.readSavedNotesSession(path, signal, history);
56
+ }
57
+
58
+ /** @param {string} threadId @param {AbortSignal} [signal] @returns {Promise<string[]>} */
59
+ export async function findSavedNotesSessions(threadId, signal) {
60
+ signal?.throwIfAborted();
61
+ const url = notesModule("saved-session-index");
62
+ if (!url) throw new Error(NOTES_READER_UNAVAILABLE);
63
+ const index = await loadReader(url);
64
+ if (typeof index.findSavedNotesSessions !== "function")
65
+ throw new Error(INVALID_READER);
66
+ return index.findSavedNotesSessions(threadId, undefined, signal);
67
+ }
@@ -151,7 +151,7 @@ export function socketChannel(socket, initial = "") {
151
151
  }
152
152
 
153
153
  /**
154
- * @param {(method:string, params:object)=>Promise<unknown>} request
154
+ * @param {import('../core/terminal-peer.mjs').TerminalPeer} request
155
155
  * @param {import("../types.js").PaneInfo} expected
156
156
  * @param {import("../types.js").FocusRequest} focus
157
157
  * @returns {Promise<import("../types.js").PeerChannel>}
@@ -1,118 +1,65 @@
1
1
  // @howaboua/pi-shepherdr managed bridge
2
- import { open } from "node:fs/promises";
3
2
  import { isDeepStrictEqual } from "node:util";
4
3
 
5
- /** @param {import('node:fs/promises').FileHandle} file @param {number} size */
6
- async function* reverseSessionLines(file, size) {
7
- let position = size;
8
- let partial = Buffer.alloc(0);
9
- while (position > 0) {
10
- const length = Math.min(64 * 1024, position);
11
- position -= length;
12
- const chunk = Buffer.allocUnsafe(length);
13
- const { bytesRead } = await file.read(chunk, 0, length, position);
14
- const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
15
- let end = data.length;
16
- for (let index = data.length - 1; index >= 0; index -= 1) {
17
- if (data[index] !== 10) continue;
18
- yield data.subarray(index + 1, end);
19
- end = index;
20
- }
21
- partial = data.subarray(0, end);
22
- }
23
- yield partial;
24
- }
25
-
26
- /** @param {{threadId: string, agentName: string, storageAgentName?: string}} identity */
4
+ /** @param {unknown} identity */
27
5
  function canonicalIdentity(identity) {
6
+ if (
7
+ !identity ||
8
+ typeof identity !== "object" ||
9
+ !("threadId" in identity) ||
10
+ typeof identity.threadId !== "string" ||
11
+ !("agentName" in identity) ||
12
+ typeof identity.agentName !== "string" ||
13
+ ("storageAgentName" in identity &&
14
+ typeof identity.storageAgentName !== "string")
15
+ )
16
+ throw new Error("Saved checkpoint owner identity changed");
28
17
  const agentName = `/${identity.threadId}`;
29
18
  return identity.agentName === agentName
30
19
  ? identity
31
20
  : {
32
21
  ...identity,
33
22
  agentName,
34
- storageAgentName: identity.storageAgentName ?? identity.agentName,
23
+ storageAgentName:
24
+ "storageAgentName" in identity
25
+ ? identity.storageAgentName
26
+ : identity.agentName,
35
27
  };
36
28
  }
37
29
 
38
30
  /** @param {string} path @param {{protocol: 1, threadId: string, sessionId: string, agentName: string, storageAgentName?: string, storage: "session"}} identity */
39
31
  export async function readPersistedNoteEntries(path, identity) {
40
- const file = await open(path, "r");
41
- try {
42
- const metadata = await file.stat();
43
- const head = Buffer.alloc(64 * 1024);
44
- const { bytesRead } = await file.read(head, 0, head.length, 0);
45
- const newline = head.subarray(0, bytesRead).indexOf(10);
46
- if (newline < 0) throw new Error("Invalid saved session header");
47
- const header = JSON.parse(head.subarray(0, newline).toString("utf8"));
48
- if (header.type !== "session" || header.id !== identity.threadId)
49
- throw new Error("Saved checkpoint owner identity changed");
50
- const entries = [];
51
- let target;
52
- let done = false;
53
- let identityChecked = false;
54
- let bytes = 0;
55
- for await (const line of reverseSessionLines(file, metadata.size)) {
56
- if (!line.length) continue;
57
- let entry;
58
- try {
59
- entry = JSON.parse(line.toString("utf8"));
60
- } catch {
61
- throw new Error(
62
- "Saved session contains an incomplete record; retry after the owner settles",
63
- );
64
- }
65
- if (
66
- entry.type === "custom" &&
67
- entry.customType === "codex-context-agent" &&
68
- entry.data?.threadId === identity.threadId
69
- ) {
70
- if (
71
- identityChecked ||
72
- !isDeepStrictEqual(
73
- canonicalIdentity(entry.data),
74
- canonicalIdentity(identity),
75
- )
76
- )
77
- throw new Error("Saved checkpoint owner identity changed");
78
- identityChecked = true;
79
- }
80
- if (done || typeof entry.id !== "string" || entry.type === "session")
81
- continue;
82
- target ??= entry.id;
83
- if (entry.id !== target) continue;
84
- if (
85
- (entry.type === "custom" &&
86
- [
87
- "codex-context-note",
88
- "codex-context-note-snapshot",
89
- "notes-compaction:note:v1",
90
- ].includes(entry.customType)) ||
91
- (entry.type === "branch_summary" &&
92
- entry.details?.codexContextNoteHandoff)
93
- ) {
94
- bytes += line.length;
95
- if (bytes > 7 * 1024 * 1024)
96
- throw new Error("Saved checkpoints exceed the transport limit");
97
- entries.push(entry);
98
- }
99
- if (
100
- entry.type === "custom" &&
101
- entry.customType === "codex-context-note-snapshot"
102
- )
103
- done = true;
104
- if (typeof entry.parentId !== "string") done = true;
105
- else target = entry.parentId;
106
- }
107
- if (!identityChecked)
108
- throw new Error("Saved checkpoint owner identity is unavailable");
109
- const after = await file.stat();
110
- if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs)
111
- throw new Error(
112
- "Saved checkpoint owner is changing; retry after it settles",
113
- );
114
- return { entries: entries.reverse(), savedAt: metadata.mtimeMs };
115
- } finally {
116
- await file.close();
117
- }
32
+ const { readSavedNotesSession } = await import("./notes-reader.mjs");
33
+ const saved = await readSavedNotesSession(path);
34
+ if (saved.threadId !== identity.threadId)
35
+ throw new Error("Saved checkpoint owner identity changed");
36
+ const identities = saved.entries.flatMap((entry) =>
37
+ entry.type === "custom" &&
38
+ entry.customType === "codex-context-agent" &&
39
+ entry.data &&
40
+ typeof entry.data === "object" &&
41
+ "threadId" in entry.data &&
42
+ entry.data.threadId === identity.threadId
43
+ ? [entry.data]
44
+ : [],
45
+ );
46
+ if (!identities.length)
47
+ throw new Error("Saved checkpoint owner identity is unavailable");
48
+ if (
49
+ identities.length !== 1 ||
50
+ !isDeepStrictEqual(
51
+ canonicalIdentity(identities[0]),
52
+ canonicalIdentity(identity),
53
+ )
54
+ )
55
+ throw new Error("Saved checkpoint owner identity changed");
56
+ const snapshot = saved.branch.findLastIndex(
57
+ (entry) =>
58
+ entry.type === "custom" &&
59
+ entry.customType === "codex-context-note-snapshot",
60
+ );
61
+ const entries = saved.branch.slice(Math.max(0, snapshot));
62
+ if (Buffer.byteLength(JSON.stringify(entries)) > 7 * 1024 * 1024)
63
+ throw new Error("Saved checkpoints exceed the transport limit");
64
+ return { entries, savedAt: saved.savedAt };
118
65
  }
@@ -47,7 +47,7 @@ function hasCode(error, code) {
47
47
  return error instanceof Error && "code" in error && error.code === code;
48
48
  }
49
49
 
50
- /** Local authenticated RPC; SSH helpers relay over their existing connection.
50
+ /** Local authenticated RPC; remote helpers relay over their Core attachment.
51
51
  * @param {string} path @param {unknown} request @param {AbortSignal} [signal]
52
52
  * @returns {Promise<unknown>} */
53
53
  export async function requestContext(path, request, signal) {
@@ -8,6 +8,15 @@ import { basename, dirname } from "node:path";
8
8
  export const MAX_PEER_FRAME_BYTES = 8 * 1024 * 1024;
9
9
  export const PEER_PROTOCOL = 4;
10
10
 
11
+ /** @param {unknown} error */
12
+ export function isDispatchRejected(error) {
13
+ return (
14
+ error instanceof Error &&
15
+ "code" in error &&
16
+ error.code === "SHEPHERDR_DELIVERY_REJECTED"
17
+ );
18
+ }
19
+
11
20
  /** @param {string} sessionFile @param {string} terminalId */
12
21
  export function peerInboxPath(sessionFile, terminalId) {
13
22
  const terminal = createHash("sha256")
@@ -89,7 +98,7 @@ export async function readReceiver(path, signal) {
89
98
  }
90
99
 
91
100
  /**
92
- * @param {(method: string, params: object) => Promise<unknown>} request
101
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
93
102
  * @param {import("../types.js").PaneInfo} expected
94
103
  * @param {import("../types.js").PeerMessage} message
95
104
  * @param {import("../types.js").FocusRequest} [focus]
@@ -140,7 +149,7 @@ export async function sendPeerMessage(
140
149
  }
141
150
 
142
151
  /**
143
- * @param {(method: string, params: object) => Promise<unknown>} request
152
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
144
153
  * @param {import("../types.js").PaneInfo} expected
145
154
  * @param {import("../types.js").ExtensionReply} reply
146
155
  * @returns {Promise<string>}
@@ -183,19 +192,11 @@ export async function sendPeerExtensionReply(request, expected, reply) {
183
192
  }
184
193
 
185
194
  /**
186
- * @param {(method: string, params: object) => Promise<unknown>} request
195
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
187
196
  * @param {import("../types.js").PaneInfo} expected
188
197
  */
189
198
  export async function resolvePeerReceiver(request, expected) {
190
- const result = await request("agent.get", { target: expected.pane_id });
191
- const agent =
192
- result &&
193
- typeof result === "object" &&
194
- "agent" in result &&
195
- result.agent &&
196
- typeof result.agent === "object"
197
- ? result.agent
198
- : {};
199
+ const agent = await request.terminal(expected.terminal_id);
199
200
  const session = "agent_session" in agent ? agent.agent_session : undefined;
200
201
  const sessionFile =
201
202
  session &&
@@ -251,7 +252,7 @@ export async function resolvePeerReceiver(request, expected) {
251
252
  }
252
253
 
253
254
  /**
254
- * @param {(method: string, params: object) => Promise<unknown>} request
255
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
255
256
  * @param {import("../types.js").PaneInfo} expected
256
257
  * @param {import("../types.js").PeerMessage} message
257
258
  * @param {import("../types.js").FocusRequest | undefined} focus
@@ -369,7 +370,7 @@ function deliverPeerFrame(
369
370
  }
370
371
 
371
372
  /**
372
- * @param {(method: string, params: object) => Promise<unknown>} request
373
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
373
374
  * @param {import("../types.js").PaneInfo} expected
374
375
  * @param {import("../types.js").FocusRequest} focus
375
376
  */
@@ -401,7 +402,7 @@ export function readPeerCommands(value) {
401
402
  }
402
403
 
403
404
  /**
404
- * @param {(method: string, params: object) => Promise<unknown>} request
405
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
405
406
  * @param {import("../types.js").PaneInfo} expected
406
407
  * @returns {Promise<import("../types.js").PeerCommand[]>}
407
408
  */
@@ -417,18 +418,12 @@ export async function sendPeerCommands(request, expected) {
417
418
  }
418
419
 
419
420
  /**
420
- * @param {(method: string, params: object) => Promise<unknown>} request
421
+ * @param {import("../core/terminal-peer.mjs").TerminalPeer} request
421
422
  * @param {import("../types.js").PaneInfo} expected
422
423
  * @param {string} sessionFile
423
424
  */
424
425
  async function closeExitedPane(request, expected, sessionFile) {
425
- const result = await request("pane.current", {
426
- caller_pane_id: expected.pane_id,
427
- });
428
- const pane =
429
- result && typeof result === "object" && "pane" in result
430
- ? result.pane
431
- : undefined;
426
+ const pane = await request.terminal(expected.terminal_id);
432
427
  if (
433
428
  !pane ||
434
429
  typeof pane !== "object" ||
@@ -446,5 +441,5 @@ async function closeExitedPane(request, expected, sessionFile) {
446
441
  pane.agent_session.value !== sessionFile
447
442
  )
448
443
  throw new Error("Target session changed; resolve it again");
449
- await request("pane.close", { pane_id: pane.pane_id });
444
+ await request.closeTerminal(pane.terminal_id);
450
445
  }
@@ -41,7 +41,6 @@ function assistantFromMessage(id, message) {
41
41
  typeof message["stopReason"] === "string"
42
42
  ? message["stopReason"]
43
43
  : undefined;
44
- if (!joined && stopReason !== "error") return undefined;
45
44
  return {
46
45
  id,
47
46
  text: joined,
@@ -180,19 +179,31 @@ async function sessionView(path, size) {
180
179
  }
181
180
  const message = record(entry["message"]);
182
181
  if (message && typeof message === "object") {
183
- // Never fall back to an older reply behind a tool call or empty final.
182
+ // Empty notice-only turns must not hide this task's useful final reply.
183
+ // Never cross a tool call or the latest task input to find one.
184
184
  if (!assistantSeen && message["role"] === "assistant") {
185
- assistantSeen = true;
186
- assistantPending = message["stopReason"] === "toolUse";
187
- if (!assistantPending)
188
- assistant = assistantFromMessage(entry["id"], message);
189
- if (assistant) assistantDepth = currentDepth;
185
+ if (message["stopReason"] === "toolUse") {
186
+ assistantSeen = true;
187
+ assistantPending = !assistant;
188
+ } else {
189
+ const candidate = assistantFromMessage(entry["id"], message);
190
+ if (
191
+ !assistant ||
192
+ candidate?.text ||
193
+ candidate?.stopReason !== "stop"
194
+ ) {
195
+ assistant = candidate;
196
+ if (assistant) assistantDepth = currentDepth;
197
+ }
198
+ assistantSeen = !!candidate?.text || candidate?.stopReason !== "stop";
199
+ }
190
200
  }
191
201
  if (!input) {
192
202
  input = inputFromMessage(entry["id"], message);
193
203
  if (input) inputDepth = currentDepth;
194
204
  }
195
205
  }
206
+ if (input) assistantSeen = true;
196
207
  if (typeof entry["parentId"] !== "string") return true;
197
208
  targetId = entry["parentId"];
198
209
  return false;
@@ -0,0 +1,62 @@
1
+ import type {
2
+ SavedSessionLoader,
3
+ SavedSessionLocator,
4
+ } from "@howaboua/pi-agent-comms/context-sharing";
5
+ import type { AgentFleet } from "./fleet/index.js";
6
+
7
+ /** Discovery supplies locations, never family membership or permission to read them. */
8
+ export function savedContextLoader(fleet: AgentFleet): SavedSessionLoader {
9
+ return Object.assign(
10
+ (location: SavedSessionLocator, history: boolean, signal?: AbortSignal) =>
11
+ fleet
12
+ .connected(location.machine)
13
+ .client.readSavedSession(location.sessionFile, history, signal),
14
+ {
15
+ async find(threadId: string, signal?: AbortSignal) {
16
+ signal?.throwIfAborted();
17
+ const machines = fleet.statuses();
18
+ const connected = machines.filter(
19
+ (machine) => machine.status === "connected",
20
+ );
21
+ const results = await Promise.allSettled(
22
+ connected.map(async (machine) => ({
23
+ machine: machine.id,
24
+ paths: await fleet
25
+ .connected(machine.id)
26
+ .client.findSavedSessions(threadId, signal),
27
+ })),
28
+ );
29
+ signal?.throwIfAborted();
30
+ const locations: SavedSessionLocator[] = [];
31
+ const unavailable = machines
32
+ .filter((machine) => machine.status !== "connected")
33
+ .map((machine) => machine.label ?? machine.id);
34
+ for (const [index, result] of results.entries()) {
35
+ if (result.status === "rejected") {
36
+ const machine = connected[index];
37
+ if (machine) unavailable.push(machine.label ?? machine.id);
38
+ continue;
39
+ }
40
+ const { machine, paths } = result.value;
41
+ if (
42
+ !Array.isArray(paths) ||
43
+ paths.some((path) => typeof path !== "string" || !path)
44
+ )
45
+ throw new Error("Saved session lookup returned invalid locations");
46
+ for (const sessionFile of paths)
47
+ locations.push({ machine, sessionFile });
48
+ }
49
+ // A missing peer cannot veto candidates elsewhere; Notes verifies them.
50
+ // Without candidates, report incomplete discovery rather than absence.
51
+ if (!locations.length && unavailable.length)
52
+ throw Object.assign(
53
+ new Error(
54
+ `Saved sessions could not be searched on ${unavailable.join(", ")}. Reconnect those machines and check access to their Pi session storage, then retry.`,
55
+ ),
56
+ { code: "SAVED_SESSION_UNAVAILABLE" },
57
+ );
58
+ return locations;
59
+ },
60
+ },
61
+ );
62
+ }