@howaboua/pi-shepherdr 0.2.23 → 0.2.25

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 (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
@@ -0,0 +1,127 @@
1
+ import type { HerdrConnection } from "../herdr-client.js";
2
+ import type { SshMachine } from "../machine-catalog.js";
3
+ import type { AssistantReader } from "../session-reader.js";
4
+ import type {
5
+ LatestAssistant,
6
+ PaneInfo,
7
+ PeerDelivery,
8
+ PeerMessage,
9
+ SessionView,
10
+ } from "../types.js";
11
+ import { connectRemoteBridge } from "./deployment.js";
12
+ import { readPeerCommands } from "./shepherdr-peer.mjs";
13
+ import { RemoteTransport } from "./transport.js";
14
+
15
+ /** Operation-specific RPC shapes and responses; transport owns all live resources. */
16
+ export class RemoteHerdrClient
17
+ extends RemoteTransport
18
+ implements HerdrConnection, AssistantReader
19
+ {
20
+ static async connect(
21
+ config: SshMachine,
22
+ onClose: (error: Error) => void,
23
+ ): Promise<RemoteHerdrClient> {
24
+ const child = await connectRemoteBridge(config);
25
+ const client = new RemoteHerdrClient(child, onClose);
26
+ try {
27
+ await client.ready();
28
+ return client;
29
+ } catch (error) {
30
+ client.close();
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ async request<T>(
36
+ method: string,
37
+ params: object = {},
38
+ timeoutMs = 10_000,
39
+ ): Promise<T> {
40
+ return (await this.call(
41
+ { op: "request", method, params, timeoutMs },
42
+ timeoutMs + 1_000,
43
+ )) as T;
44
+ }
45
+
46
+ async replyExtension(
47
+ agent: PaneInfo,
48
+ reply: import("../types.js").ExtensionReply,
49
+ ): Promise<string> {
50
+ const result = await this.call(
51
+ { op: "extension-reply", agent, reply },
52
+ 60_000,
53
+ );
54
+ if (typeof result !== "string")
55
+ throw new Error(
56
+ "Invalid extension reply receipt; inspect the target before retrying",
57
+ );
58
+ return result;
59
+ }
60
+
61
+ async commands(
62
+ agent: PaneInfo,
63
+ ): Promise<import("../types.js").PeerCommand[]> {
64
+ const result = await this.call({ op: "commands", agent }, 26_000);
65
+ return readPeerCommands(result);
66
+ }
67
+
68
+ async sendMessage(
69
+ agent: PaneInfo,
70
+ message: PeerMessage,
71
+ ): Promise<PeerDelivery> {
72
+ const result = await this.call(
73
+ { op: "message", agent, message },
74
+ message.text.trim() === "/quit" ? 0 : 26_000,
75
+ );
76
+ if (
77
+ !result ||
78
+ typeof result !== "object" ||
79
+ !("command" in result) ||
80
+ typeof result.command !== "boolean"
81
+ )
82
+ throw new Error(
83
+ "Invalid peer acknowledgement; inspect the target before retrying",
84
+ );
85
+ return { command: result.command };
86
+ }
87
+
88
+ async machineIdentity(): Promise<import("../types.js").MachineIdentity> {
89
+ const result = await this.call({ op: "identity" });
90
+ if (
91
+ !result ||
92
+ typeof result !== "object" ||
93
+ !("host" in result) ||
94
+ typeof result.host !== "string" ||
95
+ !("session" in result) ||
96
+ typeof result.session !== "string"
97
+ )
98
+ throw new Error("Could not identify remote Herdr session");
99
+ return { host: result.host, session: result.session };
100
+ }
101
+
102
+ focus(
103
+ agent: PaneInfo,
104
+ request: import("../types.js").FocusRequest,
105
+ ): Promise<unknown> {
106
+ return this.call({ op: "focus", agent, request }, 60_000);
107
+ }
108
+
109
+ async latest(path?: string): Promise<LatestAssistant | undefined> {
110
+ return (await this.view(path)).assistant;
111
+ }
112
+
113
+ async view(path?: string): Promise<SessionView> {
114
+ return (await this.call({ op: "view", path })) as SessionView;
115
+ }
116
+
117
+ async keybindings(): Promise<Record<string, unknown>> {
118
+ return (await this.call({ op: "keybindings" })) as Record<string, unknown>;
119
+ }
120
+
121
+ async directory(
122
+ value: string | undefined,
123
+ fallback: string,
124
+ ): Promise<string> {
125
+ return (await this.call({ op: "directory", value, fallback })) as string;
126
+ }
127
+ }
@@ -0,0 +1,84 @@
1
+ import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
+
3
+ /** Owns relay handlers and incoming cancellation; transport shutdown aborts the whole relay. */
4
+ export class ContextRelay {
5
+ private contextHandler:
6
+ | ((request: unknown, signal: AbortSignal) => Promise<unknown>)
7
+ | undefined;
8
+ private readonly incomingContext = new Map<string, AbortController>();
9
+ private relayPath: string | undefined;
10
+ private readonly child: ChildProcessWithoutNullStreams;
11
+ private readonly closed: () => boolean;
12
+ private readonly maxFrameBytes: number;
13
+ constructor(
14
+ child: ChildProcessWithoutNullStreams,
15
+ closed: () => boolean,
16
+ maxFrameBytes: number,
17
+ ) {
18
+ this.child = child;
19
+ this.closed = closed;
20
+ this.maxFrameBytes = maxFrameBytes;
21
+ }
22
+ async start(
23
+ threadId: string,
24
+ routeId: string,
25
+ handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
26
+ call: (message: Record<string, unknown>) => Promise<unknown>,
27
+ ): Promise<void> {
28
+ this.contextHandler = handler;
29
+ const path = await call({ op: "context_relay", threadId, routeId });
30
+ if (typeof path !== "string")
31
+ throw new Error("Invalid shared context relay path");
32
+ this.relayPath = path;
33
+ }
34
+
35
+ path(): string {
36
+ if (!this.relayPath)
37
+ throw new Error(
38
+ "Shared context relay is unavailable; open /herdr → Status to retry",
39
+ );
40
+ return this.relayPath;
41
+ }
42
+
43
+ consume(id: string, value: Record<string, unknown>): boolean {
44
+ if (value["type"] === "context_cancel") {
45
+ this.incomingContext.get(id)?.abort();
46
+ return true;
47
+ }
48
+ if (value["type"] === "context_request") {
49
+ const controller = new AbortController();
50
+ this.incomingContext.set(id, controller);
51
+ const reply = (data: object) => {
52
+ 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);
57
+ };
58
+ void Promise.resolve()
59
+ .then(() => {
60
+ if (!this.contextHandler)
61
+ throw new Error("Shared context controller is unavailable");
62
+ controller.signal.throwIfAborted();
63
+ return this.contextHandler(value["request"], controller.signal);
64
+ })
65
+ .then(
66
+ (result) => reply({ ok: true, result }),
67
+ (error: unknown) =>
68
+ reply({
69
+ ok: false,
70
+ error: error instanceof Error ? error.message : String(error),
71
+ }),
72
+ )
73
+ .finally(() => {
74
+ this.incomingContext.delete(id);
75
+ });
76
+ return true;
77
+ }
78
+ return false;
79
+ }
80
+ abortAll() {
81
+ for (const controller of this.incomingContext.values()) controller.abort();
82
+ this.incomingContext.clear();
83
+ }
84
+ }
@@ -0,0 +1,179 @@
1
+ import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { SshMachine } from "../machine-catalog.js";
5
+
6
+ export const BRIDGE_VERSION = 24;
7
+ const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
8
+ const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
9
+ const REMOTE_CHANNEL_HELPER = "~/.pi/agent/shepherdr-channel.mjs";
10
+ const REMOTE_SESSION_HELPER = "~/.pi/agent/shepherdr-session.mjs";
11
+ const REMOTE_SESSION_WATCH_HELPER = "~/.pi/agent/shepherdr-session-watch.mjs";
12
+ const REMOTE_CHECKPOINT_HELPER = "~/.pi/agent/shepherdr-checkpoints.mjs";
13
+ const REMOTE_CONTEXT_HELPER = "~/.pi/agent/shepherdr-context.mjs";
14
+ const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
15
+ const DEPLOY_TIMEOUT_MS = 20_000;
16
+
17
+ const DEPLOY_SOURCE = String.raw`
18
+ const { randomUUID } = require("node:crypto");
19
+ const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
20
+ const { homedir } = require("node:os");
21
+ const { dirname, join } = require("node:path");
22
+ const targetValue = process.argv[1];
23
+ const marker = "// @howaboua/pi-shepherdr managed bridge";
24
+ const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
25
+ const chunks = [];
26
+ let size = 0;
27
+ process.stdin.on("data", chunk => { size += chunk.length; if (size > 1024 * 1024) { process.stderr.write("bridge source is too large\n"); process.exit(1); } chunks.push(chunk); });
28
+ process.stdin.on("end", () => { void (async () => {
29
+ const source = Buffer.concat(chunks);
30
+ let existing;
31
+ try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
32
+ if (existing) {
33
+ if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
34
+ if (!existing.toString("utf8", 0, marker.length + 32).startsWith(marker)) throw new Error(target + " is not owned by Shepherdr");
35
+ }
36
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
37
+ const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
38
+ try {
39
+ await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
40
+ await rename(temporary, target);
41
+ } catch (error) {
42
+ await unlink(temporary).catch(() => undefined);
43
+ throw error;
44
+ }
45
+ process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
46
+ })().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
47
+ `;
48
+
49
+ function shellQuote(value: string): string {
50
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
51
+ }
52
+
53
+ function executablePath(path: string): string {
54
+ return path.startsWith("~/")
55
+ ? `"$HOME"/${shellQuote(path.slice(2))}`
56
+ : shellQuote(path);
57
+ }
58
+
59
+ function remoteCommand(config: SshMachine): string {
60
+ const args = [
61
+ "exec",
62
+ "node",
63
+ executablePath(REMOTE_HELPER),
64
+ "--session",
65
+ shellQuote(config.session),
66
+ ];
67
+ return args.join(" ");
68
+ }
69
+
70
+ function spawnConnector(
71
+ config: SshMachine,
72
+ command: string,
73
+ ): ChildProcessWithoutNullStreams {
74
+ return spawn(
75
+ "ssh",
76
+ ["-T", "-o", "BatchMode=yes", "--", config.target, command],
77
+ {
78
+ stdio: ["pipe", "pipe", "pipe"],
79
+ },
80
+ );
81
+ }
82
+
83
+ export function appendBounded(current: string, chunk: Buffer): string {
84
+ const next = current + chunk.toString("utf8");
85
+ return next.length <= MAX_DIAGNOSTIC_BYTES
86
+ ? next
87
+ : next.slice(next.length - MAX_DIAGNOSTIC_BYTES);
88
+ }
89
+
90
+ async function deploy(
91
+ config: SshMachine,
92
+ source: Buffer,
93
+ target: string,
94
+ ): Promise<void> {
95
+ const command = [
96
+ "node",
97
+ "-e",
98
+ shellQuote(DEPLOY_SOURCE),
99
+ shellQuote(target),
100
+ ].join(" ");
101
+ const child = spawnConnector(config, command);
102
+ let stdout = "";
103
+ let stderr = "";
104
+ child.stdout.on("data", (chunk: Buffer) => {
105
+ stdout = appendBounded(stdout, chunk);
106
+ });
107
+ child.stderr.on("data", (chunk: Buffer) => {
108
+ stderr = appendBounded(stderr, chunk);
109
+ });
110
+ await new Promise<void>((resolve, reject) => {
111
+ const timer = setTimeout(() => {
112
+ child.kill();
113
+ reject(new Error("remote bridge deployment timed out"));
114
+ }, DEPLOY_TIMEOUT_MS);
115
+ timer.unref();
116
+ child.stdin.on("error", (error) => {
117
+ clearTimeout(timer);
118
+ child.kill();
119
+ reject(error);
120
+ });
121
+ child.on("error", (error) => {
122
+ clearTimeout(timer);
123
+ reject(error);
124
+ });
125
+ child.on("exit", (code) => {
126
+ clearTimeout(timer);
127
+ if (code === 0) resolve();
128
+ else
129
+ reject(
130
+ new Error(
131
+ stderr.trim() ||
132
+ stdout.trim() ||
133
+ `remote bridge deployment exited ${code ?? "without status"}`,
134
+ ),
135
+ );
136
+ });
137
+ child.stdin.end(source);
138
+ });
139
+ }
140
+
141
+ export async function connectRemoteBridge(
142
+ config: SshMachine,
143
+ ): Promise<ChildProcessWithoutNullStreams> {
144
+ const [
145
+ source,
146
+ peerSource,
147
+ channelSource,
148
+ sessionSource,
149
+ contextSource,
150
+ checkpointSource,
151
+ sessionWatchSource,
152
+ ] = await Promise.all([
153
+ readFile(fileURLToPath(new URL("./shepherdr.mjs", import.meta.url))),
154
+ readFile(fileURLToPath(new URL("./shepherdr-peer.mjs", import.meta.url))),
155
+ readFile(
156
+ fileURLToPath(new URL("./shepherdr-channel.mjs", import.meta.url)),
157
+ ),
158
+ readFile(
159
+ fileURLToPath(new URL("./shepherdr-session.mjs", import.meta.url)),
160
+ ),
161
+ readFile(
162
+ fileURLToPath(new URL("./shepherdr-context.mjs", import.meta.url)),
163
+ ),
164
+ readFile(
165
+ fileURLToPath(new URL("./shepherdr-checkpoints.mjs", import.meta.url)),
166
+ ),
167
+ readFile(
168
+ fileURLToPath(new URL("./shepherdr-session-watch.mjs", import.meta.url)),
169
+ ),
170
+ ]);
171
+ await deploy(config, peerSource, REMOTE_PEER_HELPER);
172
+ await deploy(config, channelSource, REMOTE_CHANNEL_HELPER);
173
+ await deploy(config, sessionSource, REMOTE_SESSION_HELPER);
174
+ await deploy(config, sessionWatchSource, REMOTE_SESSION_WATCH_HELPER);
175
+ await deploy(config, checkpointSource, REMOTE_CHECKPOINT_HELPER);
176
+ await deploy(config, contextSource, REMOTE_CONTEXT_HELPER);
177
+ await deploy(config, source, REMOTE_HELPER);
178
+ return spawnConnector(config, remoteCommand(config));
179
+ }
@@ -0,0 +1,89 @@
1
+ import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import type { PaneInfo, PeerChannel } from "../types.js";
4
+ import { createBufferedChannel } from "./shepherdr-channel.mjs";
5
+
6
+ /** Owns admitted duplex channels; the transport closes all on its single teardown path. */
7
+ export class FocusChannels {
8
+ private readonly channels = new Map<
9
+ string,
10
+ ReturnType<typeof createBufferedChannel>
11
+ >();
12
+ private readonly child: ChildProcessWithoutNullStreams;
13
+ private readonly closed: () => boolean;
14
+ constructor(child: ChildProcessWithoutNullStreams, closed: () => boolean) {
15
+ this.child = child;
16
+ this.closed = closed;
17
+ }
18
+ async open(
19
+ agent: PaneInfo,
20
+ request: import("../types.js").FocusRequest,
21
+ call: (
22
+ message: Record<string, unknown>,
23
+ timeoutMs: number,
24
+ ) => Promise<unknown>,
25
+ ): Promise<PeerChannel> {
26
+ const id = randomUUID();
27
+ const state = createBufferedChannel(
28
+ (message) => {
29
+ const frame = `${JSON.stringify({ op: "channel_send", id, message })}\n`;
30
+ if (
31
+ this.closed() ||
32
+ this.child.stdin.writableLength + Buffer.byteLength(frame) >
33
+ 1024 * 1024
34
+ )
35
+ throw new Error(
36
+ "Focus channel output is unavailable or exceeded its buffer",
37
+ );
38
+ this.child.stdin.write(frame);
39
+ },
40
+ () => {
41
+ this.channels.delete(id);
42
+ if (!this.closed())
43
+ this.child.stdin.write(
44
+ `${JSON.stringify({ op: "channel_close", id })}\n`,
45
+ );
46
+ },
47
+ );
48
+ this.channels.set(id, state);
49
+ try {
50
+ const result = await call(
51
+ { op: "channel_open", id, agent, request },
52
+ 60_000,
53
+ );
54
+ if (
55
+ !result ||
56
+ typeof result !== "object" ||
57
+ !("admitted" in result) ||
58
+ result.admitted !== true
59
+ )
60
+ throw new Error("Focus channel was not admitted");
61
+ return state.channel;
62
+ } catch (error) {
63
+ state.fail(error instanceof Error ? error : new Error(String(error)));
64
+ throw error;
65
+ }
66
+ }
67
+
68
+ consume(value: Record<string, unknown>): boolean {
69
+ if (value["type"] === "channel" && typeof value["channel"] === "string") {
70
+ const state = this.channels.get(value["channel"]);
71
+ if (value["closed"] === true)
72
+ state?.fail(
73
+ new Error(
74
+ typeof value["error"] === "string"
75
+ ? value["error"]
76
+ : "Focus channel disconnected",
77
+ ),
78
+ );
79
+ else if ("message" in value) state?.receive(value["message"]);
80
+ else state?.fail(new Error("Invalid focus channel frame"));
81
+ return true;
82
+ }
83
+ return false;
84
+ }
85
+ failAll(error: Error) {
86
+ for (const state of this.channels.values()) state.fail(error);
87
+ this.channels.clear();
88
+ }
89
+ }
@@ -88,7 +88,7 @@ export async function requestContext(path, request, signal) {
88
88
  }
89
89
  let descriptor;
90
90
  try {
91
- descriptor = JSON.parse(await readReceiver(path));
91
+ descriptor = JSON.parse(await readReceiver(path, signal));
92
92
  } catch (error) {
93
93
  throw new Error(
94
94
  "Shared context owner is unavailable; resume it and reconnect its machine",
@@ -31,10 +31,10 @@ function isMissing(error) {
31
31
  return error instanceof Error && "code" in error && error.code === "ENOENT";
32
32
  }
33
33
 
34
- /** @param {string} path @returns {Promise<string>} */
35
- export async function readReceiver(path) {
34
+ /** @param {string} path @param {AbortSignal} [signal] @returns {Promise<string>} */
35
+ export async function readReceiver(path, signal) {
36
36
  try {
37
- return await readFile(path, "utf8");
37
+ return await readFile(path, { encoding: "utf8", signal });
38
38
  } catch (error) {
39
39
  if (!isMissing(error)) throw error;
40
40
  }
@@ -47,6 +47,7 @@ export async function readReceiver(path) {
47
47
  if (settled) return false;
48
48
  settled = true;
49
49
  clearTimeout(timer);
50
+ signal?.removeEventListener("abort", aborted);
50
51
  watcher.close();
51
52
  return true;
52
53
  };
@@ -54,6 +55,7 @@ export async function readReceiver(path) {
54
55
  const fail = (error) => {
55
56
  if (finish()) reject(error);
56
57
  };
58
+ const aborted = () => fail(signal?.reason);
57
59
  const timer = setTimeout(
58
60
  () =>
59
61
  fail(
@@ -64,7 +66,7 @@ export async function readReceiver(path) {
64
66
  30_000,
65
67
  );
66
68
  const read = () => {
67
- void readFile(path, "utf8").then(
69
+ void readFile(path, { encoding: "utf8", signal }).then(
68
70
  (value) => {
69
71
  if (finish()) resolve(value);
70
72
  },
@@ -77,6 +79,11 @@ export async function readReceiver(path) {
77
79
  watcher.on("change", (_event, file) => {
78
80
  if (file === null || file === basename(path)) read();
79
81
  });
82
+ signal?.addEventListener("abort", aborted, { once: true });
83
+ if (signal?.aborted) {
84
+ aborted();
85
+ return;
86
+ }
80
87
  read();
81
88
  });
82
89
  }
@@ -104,7 +111,13 @@ export async function sendPeerMessage(
104
111
  const frame =
105
112
  JSON.stringify({
106
113
  protocol: PEER_PROTOCOL,
107
- kind: commands ? "commands" : focus ? "focus" : "message",
114
+ kind: message.closeIfIdle
115
+ ? "close-idle"
116
+ : commands
117
+ ? "commands"
118
+ : focus
119
+ ? "focus"
120
+ : "message",
108
121
  focus,
109
122
  id,
110
123
  token: descriptor.token,
@@ -103,6 +103,8 @@ async function sessionView(path, size) {
103
103
  let targetId;
104
104
  /** @type {import("../types.js").LatestAssistant | undefined} */
105
105
  let assistant;
106
+ let assistantSeen = false;
107
+ let assistantPending = false;
106
108
  /** @type {number | undefined} */
107
109
  let assistantDepth;
108
110
  /** @type {import("../types.js").ExtensionMessage[]} */
@@ -115,6 +117,7 @@ async function sessionView(path, size) {
115
117
  const resolved = new Set();
116
118
  const result = () => ({
117
119
  ...(assistant ? { assistant } : {}),
120
+ ...(assistantPending ? { assistantPending: true } : {}),
118
121
  ...(extensionMessages.length ? { extensionMessages } : {}),
119
122
  ...(input ? { input } : {}),
120
123
  ...(assistantDepth !== undefined && inputDepth !== undefined
@@ -177,8 +180,12 @@ async function sessionView(path, size) {
177
180
  }
178
181
  const message = record(entry["message"]);
179
182
  if (message && typeof message === "object") {
180
- if (!assistant) {
181
- assistant = assistantFromMessage(entry["id"], message);
183
+ // Never fall back to an older reply behind a tool call or empty final.
184
+ if (!assistantSeen && message["role"] === "assistant") {
185
+ assistantSeen = true;
186
+ assistantPending = message["stopReason"] === "toolUse";
187
+ if (!assistantPending)
188
+ assistant = assistantFromMessage(entry["id"], message);
182
189
  if (assistant) assistantDepth = currentDepth;
183
190
  }
184
191
  if (!input) {
@@ -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 = 22;
21
+ const BRIDGE_VERSION = 23;
22
22
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
23
23
  const subscriptions = new Map();
24
24
  const contextRelays = new Map();