@howaboua/pi-shepherdr 0.2.24 → 0.2.26

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 (85) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +20 -12
  3. package/index.ts +2 -2
  4. package/package.json +10 -11
  5. package/src/agent-identity.ts +75 -0
  6. package/src/agents-contract.ts +20 -12
  7. package/src/agents-discovery.ts +79 -34
  8. package/src/agents-focus.ts +15 -9
  9. package/src/agents-spawn.ts +25 -7
  10. package/src/agents-tool.ts +35 -7
  11. package/src/agents-work.ts +2 -2
  12. package/src/attachment-notes.ts +25 -24
  13. package/src/attachment-protocol.ts +35 -15
  14. package/src/attachment-routing.ts +28 -24
  15. package/src/attachment-target.ts +58 -19
  16. package/src/attachment.ts +13 -17
  17. package/src/board/host.ts +19 -20
  18. package/src/board/membership.ts +49 -30
  19. package/src/close-idle.ts +89 -0
  20. package/src/context-routing.ts +196 -0
  21. package/src/control-panel/index.ts +3 -1
  22. package/src/control-panel/items.ts +14 -2
  23. package/src/control-panel/view.ts +6 -2
  24. package/src/controller.ts +11 -2
  25. package/src/core/AGENTS.md +5 -0
  26. package/src/core/backend.ts +266 -0
  27. package/src/core/client.ts +249 -0
  28. package/src/core/context-relay.mjs +111 -0
  29. package/src/core/focus-channel-helper.mjs +165 -0
  30. package/src/core/focus-channel-stream.ts +140 -0
  31. package/src/core/focus-channel-wire.mjs +160 -0
  32. package/src/core/focus-channel.ts +213 -0
  33. package/src/core/focus-window.ts +192 -0
  34. package/src/core/pi-executable.mjs +34 -0
  35. package/src/core/protocol.ts +116 -0
  36. package/src/core/registration.ts +51 -0
  37. package/src/core/remote-endpoint.ts +119 -0
  38. package/src/core/remote-exec.ts +122 -0
  39. package/src/core/remote-helper.mjs +244 -0
  40. package/src/core/remote-reader.ts +67 -0
  41. package/src/core/remote-relay.ts +191 -0
  42. package/src/core/request.ts +124 -0
  43. package/src/core/spawn.ts +177 -0
  44. package/src/core/status.ts +68 -0
  45. package/src/core/terminal.ts +103 -0
  46. package/src/fleet/catalog.ts +83 -0
  47. package/src/fleet/connection.ts +111 -0
  48. package/src/fleet/index.ts +161 -122
  49. package/src/fleet/inspection.ts +19 -1
  50. package/src/fleet/machine.ts +3 -0
  51. package/src/fleet/monitor.ts +18 -4
  52. package/src/fleet/persistence.ts +26 -3
  53. package/src/fleet/setup.ts +54 -13
  54. package/src/herdr.ts +25 -5
  55. package/src/launch-contract.ts +48 -0
  56. package/src/launch-location.ts +151 -0
  57. package/src/launch.ts +30 -183
  58. package/src/messages/attribution.ts +15 -6
  59. package/src/messages/events.ts +10 -4
  60. package/src/messages/focus.ts +11 -2
  61. package/src/messages/guidance.ts +22 -16
  62. package/src/monitor-extension-messages.ts +9 -2
  63. package/src/monitor-record.ts +13 -6
  64. package/src/monitor-state.ts +18 -4
  65. package/src/monitor.ts +31 -0
  66. package/src/peer-commands.ts +11 -0
  67. package/src/peer-inbox-delivery.ts +171 -0
  68. package/src/peer-inbox-focus.ts +113 -0
  69. package/src/peer-inbox.ts +126 -208
  70. package/src/remote/deployment.ts +1 -1
  71. package/src/remote/shepherdr-checkpoints.mjs +20 -2
  72. package/src/remote/shepherdr-context.mjs +15 -3
  73. package/src/remote/shepherdr-peer.mjs +18 -5
  74. package/src/remote/shepherdr-session.mjs +9 -2
  75. package/src/remote/shepherdr.mjs +1 -1
  76. package/src/settlement/collector.ts +2 -2
  77. package/src/settlement/index.ts +12 -0
  78. package/src/shared-context-host.ts +7 -18
  79. package/src/shared-context.ts +139 -12
  80. package/src/spawn-context.ts +10 -5
  81. package/src/spawn-ownership.ts +91 -0
  82. package/src/types.ts +10 -5
  83. package/src/worker-ownership.ts +92 -0
  84. package/src/worker-service.ts +13 -82
  85. package/changelog.ts +0 -337
@@ -0,0 +1,244 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { homedir, hostname, tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { createInterface } from "node:readline";
6
+
7
+ const chunks = [];
8
+ for await (const chunk of process.stdin) chunks.push(chunk);
9
+ const input = JSON.parse(Buffer.concat(chunks).toString());
10
+ const child = spawn(
11
+ "hc",
12
+ ["connect", "--session", input.session || "default"],
13
+ { stdio: ["pipe", "pipe", "pipe"] },
14
+ );
15
+ const pending = new Map();
16
+ let id = 0;
17
+ let diagnostic = "";
18
+ child.stderr.on("data", (chunk) => {
19
+ diagnostic = (diagnostic + chunk).slice(-4096);
20
+ });
21
+ function failed(error) {
22
+ for (const entry of pending.values()) entry.reject(error);
23
+ pending.clear();
24
+ }
25
+ child.on("error", failed);
26
+ child.stdin.on("error", failed);
27
+ child.on("exit", () =>
28
+ failed(new Error(diagnostic || "Remote Core connection closed")),
29
+ );
30
+ createInterface({ input: child.stdout }).on("line", (line) => {
31
+ try {
32
+ const reply = JSON.parse(line);
33
+ const entry = pending.get(reply.id);
34
+ if (!entry) return;
35
+ pending.delete(reply.id);
36
+ if (reply.error) entry.reject(new Error(reply.error.message));
37
+ else entry.resolve(reply.result);
38
+ } catch (error) {
39
+ failed(error);
40
+ }
41
+ });
42
+ function rpc(method, params = {}) {
43
+ return new Promise((resolve, reject) => {
44
+ pending.set(++id, { resolve, reject });
45
+ child.stdin.write(
46
+ JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n",
47
+ );
48
+ });
49
+ }
50
+ function rejected(message) {
51
+ return Object.assign(new Error(message), {
52
+ code: "SHEPHERDR_DELIVERY_REJECTED",
53
+ });
54
+ }
55
+ async function nativeRequest(method, params) {
56
+ const terminal = params.target ?? params.pane_id ?? params.caller_pane_id;
57
+ if (typeof terminal !== "string" || !/^t[0-9a-z]+$/.test(terminal))
58
+ throw rejected("Use the exact remote terminal address");
59
+ const record = await rpc("terminal.get", { terminal });
60
+ if (record.address !== terminal)
61
+ throw rejected("Remote terminal changed; resolve it again");
62
+ if (method === "pane.close") {
63
+ if (record.state === "live") await rpc("terminal.kill", { terminal });
64
+ return rpc("terminal.rm", { terminal });
65
+ }
66
+ const path = record.labels["pi.session_file"];
67
+ const agent = {
68
+ pane_id: terminal,
69
+ terminal_id: terminal,
70
+ agent: path ? "pi" : null,
71
+ ...(path ? { agent_session: { kind: "path", value: path } } : {}),
72
+ };
73
+ if (method === "agent.get") return { agent };
74
+ if (method === "pane.current") return { pane: agent };
75
+ throw rejected("Remote peer action is unavailable");
76
+ }
77
+ async function run() {
78
+ const hello = await rpc("hello");
79
+ if (hello.core.id !== input.coreId)
80
+ throw rejected(
81
+ "Remote Core identity changed; refresh machines before retrying",
82
+ );
83
+ const peer = await import(input.modules.peer);
84
+ switch (input.op) {
85
+ case "list": {
86
+ const result = await rpc("terminal.list");
87
+ return {
88
+ terminals: result.terminals.filter(
89
+ (terminal) => !terminal.address.includes("/"),
90
+ ),
91
+ };
92
+ }
93
+ case "identity":
94
+ return { host: hostname(), session: hello.core.id };
95
+ case "pi-executable":
96
+ return (await import(input.modules.pi)).piExecutable(input.cwd);
97
+ case "message":
98
+ return peer.sendPeerMessage(nativeRequest, input.agent, input.message);
99
+ case "focus":
100
+ return peer.sendPeerFocus(nativeRequest, input.agent, input.focus);
101
+ case "commands":
102
+ return peer.sendPeerCommands(nativeRequest, input.agent);
103
+ case "reply":
104
+ return peer.sendPeerExtensionReply(
105
+ nativeRequest,
106
+ input.agent,
107
+ input.reply,
108
+ );
109
+ case "context":
110
+ return (await import(input.modules.context)).requestContext(
111
+ input.path,
112
+ input.request,
113
+ );
114
+ case "relay-close": {
115
+ await (await import(input.modules.context)).requestContext(input.path, {
116
+ relayToken: input.relayToken,
117
+ action: "close",
118
+ });
119
+ for (let attempt = 0; attempt < 100; attempt++) {
120
+ try {
121
+ await stat(input.path);
122
+ } catch (error) {
123
+ if (error.code === "ENOENT") return true;
124
+ throw error;
125
+ }
126
+ await new Promise((resolve) => setTimeout(resolve, 20));
127
+ }
128
+ throw new Error(
129
+ "Context sharing is still stopping; wait a moment before reconnecting",
130
+ );
131
+ }
132
+ case "relay-start": {
133
+ // machine.exec ends all descendants, even detached ones. Give the
134
+ // leased relay to Core explicitly; rm removes its terminal on exit.
135
+ const directory = await mkdtemp(join(tmpdir(), "shepherdr-relay-"));
136
+ const script = join(directory, "relay.mjs");
137
+ let terminal;
138
+ try {
139
+ await writeFile(
140
+ script,
141
+ `import {rm} from "node:fs/promises"; await rm(${JSON.stringify(directory)}, {recursive:true,force:true}); const input=${JSON.stringify(input)}; await (await import(input.modules.relay)).serveRelay(input);`,
142
+ { mode: 0o600, flag: "wx" },
143
+ );
144
+ terminal = await rpc("terminal.run", {
145
+ argv: ["node", script],
146
+ no_parent: true,
147
+ no_notify: true,
148
+ outlive_parent: true,
149
+ rm: true,
150
+ labels: { "shepherdr.role": "context-relay" },
151
+ });
152
+ const context = await import(input.modules.context);
153
+ const path = context.relayContextPath(input.threadId, input.routeId);
154
+ for (let attempt = 0; attempt < 100; attempt++) {
155
+ const record = await rpc("terminal.get", {
156
+ terminal: terminal.address,
157
+ });
158
+ if (record.state !== "live")
159
+ throw new Error(
160
+ "Context sharing could not start; wait 30 seconds and reconnect this machine",
161
+ );
162
+ try {
163
+ const descriptor = JSON.parse(await readFile(path, "utf8"));
164
+ if (descriptor.pid === record.pid) return path;
165
+ } catch (error) {
166
+ if (error.code !== "ENOENT") throw error;
167
+ }
168
+ await new Promise((resolve) => setTimeout(resolve, 50));
169
+ }
170
+ throw new Error(
171
+ "Shared context relay did not start; inspect its Core terminal output",
172
+ );
173
+ } catch (error) {
174
+ if (terminal)
175
+ await rpc("terminal.kill", { terminal: terminal.address }).catch(
176
+ () => {},
177
+ );
178
+ throw error;
179
+ } finally {
180
+ await rm(directory, { recursive: true, force: true });
181
+ }
182
+ }
183
+ case "view":
184
+ return (await import(input.modules.session)).readSessionView(input.path);
185
+ case "directory": {
186
+ const expand = (value) =>
187
+ value === "~"
188
+ ? homedir()
189
+ : value.startsWith("~/")
190
+ ? resolve(homedir(), value.slice(2))
191
+ : value;
192
+ const path = resolve(
193
+ expand(input.fallback),
194
+ expand(input.value?.trim() || "."),
195
+ );
196
+ if (!(await stat(path)).isDirectory())
197
+ throw new Error("Remote working directory is not a directory");
198
+ return path;
199
+ }
200
+ case "watch": {
201
+ const watcher = await import(input.modules.watch);
202
+ return new Promise((resolve, reject) => {
203
+ let close = () => {};
204
+ const timer = setTimeout(() => {
205
+ close();
206
+ resolve([]);
207
+ }, 10_000);
208
+ try {
209
+ close = watcher.watchSessions(
210
+ input.paths,
211
+ (path) => {
212
+ clearTimeout(timer);
213
+ close();
214
+ resolve([path]);
215
+ },
216
+ (error) => {
217
+ clearTimeout(timer);
218
+ close();
219
+ reject(error);
220
+ },
221
+ );
222
+ } catch (error) {
223
+ clearTimeout(timer);
224
+ reject(error);
225
+ }
226
+ });
227
+ }
228
+ default:
229
+ throw rejected("Unknown remote operation");
230
+ }
231
+ }
232
+ try {
233
+ process.stdout.write(
234
+ JSON.stringify({ ok: true, result: await run() }) + "\n",
235
+ );
236
+ } catch (error) {
237
+ process.stdout.write(
238
+ JSON.stringify({ ok: false, error: error.message, code: error.code }) +
239
+ "\n",
240
+ );
241
+ } finally {
242
+ child.stdin.end();
243
+ child.kill();
244
+ }
@@ -0,0 +1,67 @@
1
+ import type { AssistantReader } from "../session-reader.js";
2
+ import type { SessionView } from "../types.js";
3
+ import { object } from "./protocol.js";
4
+ import type { RemoteCoreEndpoint } from "./remote-endpoint.js";
5
+ import { remoteExec } from "./remote-exec.js";
6
+
7
+ export class CoreRemoteReader implements AssistantReader {
8
+ private readonly endpoint: RemoteCoreEndpoint;
9
+ constructor(endpoint: RemoteCoreEndpoint) {
10
+ this.endpoint = endpoint;
11
+ }
12
+ async view(path?: string): Promise<SessionView> {
13
+ if (!path) return {};
14
+ return object(
15
+ await remoteExec(this.endpoint.host, this.endpoint.machine, {
16
+ op: "view",
17
+ path,
18
+ }),
19
+ ) as SessionView;
20
+ }
21
+ async latest(path?: string) {
22
+ return (await this.view(path)).assistant;
23
+ }
24
+ async watch(
25
+ paths: string[],
26
+ onChange: (path: string) => void,
27
+ onError: (error: Error) => void,
28
+ signal: AbortSignal,
29
+ ): Promise<() => void> {
30
+ const lifetime = new AbortController();
31
+ const abort = () => lifetime.abort();
32
+ signal.addEventListener("abort", abort, { once: true });
33
+ if (signal.aborted) abort();
34
+ const close = () => {
35
+ signal.removeEventListener("abort", abort);
36
+ lifetime.abort();
37
+ };
38
+ void (async () => {
39
+ try {
40
+ while (!lifetime.signal.aborted) {
41
+ const changed = await remoteExec(
42
+ this.endpoint.host,
43
+ this.endpoint.machine,
44
+ { op: "watch", paths },
45
+ { signal: lifetime.signal },
46
+ );
47
+ if (lifetime.signal.aborted) break;
48
+ if (
49
+ !Array.isArray(changed) ||
50
+ !changed.every(
51
+ (path) => typeof path === "string" && paths.includes(path),
52
+ )
53
+ )
54
+ throw new Error("Remote session watch returned invalid paths");
55
+ // A bounded long-poll cannot promise continuity between processes.
56
+ for (const path of changed.length ? changed : paths) onChange(path);
57
+ }
58
+ } catch (error) {
59
+ if (!lifetime.signal.aborted)
60
+ onError(error instanceof Error ? error : new Error(String(error)));
61
+ } finally {
62
+ close();
63
+ }
64
+ })();
65
+ return close;
66
+ }
67
+ }
@@ -0,0 +1,191 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { CoreClient } from "./client.js";
3
+ import { object } from "./protocol.js";
4
+ import { type CoreMachine, remoteExec } from "./remote-exec.js";
5
+
6
+ // Fleet closes synchronously and can immediately construct a replacement owner.
7
+ // Retain only live/closing routes, including starts not yet acknowledged by Core.
8
+ const routes = new Map<string, CoreContextRelay>();
9
+ // Match context-relay.mjs: sixfold Notes escaping plus envelope headroom.
10
+ const RELAY_PAYLOAD_BYTES = 6_250_000;
11
+
12
+ /** Owns the reverse route, its bounded polling and all host-side handlers. */
13
+ export class CoreContextRelay {
14
+ private readonly client: CoreClient;
15
+ private readonly machine: CoreMachine;
16
+ private readonly token = randomBytes(32).toString("hex");
17
+ private readonly controller = new AbortController();
18
+ private readonly incoming = new Map<string, AbortController>();
19
+ private pathValue: string | undefined;
20
+ private failed: Error | undefined;
21
+ private closed = false;
22
+ private closing: Promise<void> | undefined;
23
+ private starting: Promise<void> | undefined;
24
+ private route: string | undefined;
25
+ private readonly socket: string;
26
+ private onFailure: ((error: Error) => void) | undefined;
27
+ constructor(socket: string, machine: CoreMachine) {
28
+ this.socket = socket;
29
+ this.client = new CoreClient(socket);
30
+ this.machine = machine;
31
+ }
32
+ start(
33
+ threadId: string,
34
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
35
+ onFailure: (error: Error) => void,
36
+ ): Promise<void> {
37
+ if (this.starting || this.closed)
38
+ return Promise.reject(
39
+ new Error("Shared context relay is already started or closed"),
40
+ );
41
+ this.route = JSON.stringify([this.socket, this.machine.id, threadId]);
42
+ const previous = routes.get(this.route);
43
+ routes.set(this.route, this);
44
+ this.starting = this.open(threadId, handle, onFailure, previous);
45
+ return this.starting;
46
+ }
47
+ private async open(
48
+ threadId: string,
49
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
50
+ onFailure: (error: Error) => void,
51
+ previous: CoreContextRelay | undefined,
52
+ ): Promise<void> {
53
+ await previous?.close();
54
+ this.controller.signal.throwIfAborted();
55
+ this.onFailure = onFailure;
56
+ const path = await remoteExec(
57
+ this.client,
58
+ this.machine,
59
+ {
60
+ op: "relay-start",
61
+ threadId,
62
+ routeId: createHash("sha256")
63
+ .update(this.machine.id)
64
+ .digest("hex")
65
+ .slice(0, 32),
66
+ relayToken: this.token,
67
+ },
68
+ // Accepted machine.exec is not cancelled by closing its local socket.
69
+ // Finish this bounded start so close can remove its actual daemon.
70
+ );
71
+ if (typeof path !== "string")
72
+ throw new Error("Invalid shared context relay path");
73
+ this.pathValue = path;
74
+ if (this.closed) return;
75
+ void this.poll(handle).catch((error: unknown) => {
76
+ this.fail(error);
77
+ });
78
+ }
79
+ path(): string {
80
+ if (this.failed)
81
+ throw new Error(
82
+ `Shared context relay disconnected: ${this.failed.message}. Open /herdr → Status to retry sharing`,
83
+ );
84
+ if (!this.pathValue || this.controller.signal.aborted)
85
+ throw new Error(
86
+ "Shared context relay is unavailable; open /herdr → Status to retry sharing",
87
+ );
88
+ return this.pathValue;
89
+ }
90
+ private call(request: object, signal?: AbortSignal) {
91
+ return remoteExec(
92
+ this.client,
93
+ this.machine,
94
+ {
95
+ op: "context",
96
+ path: this.pathValue,
97
+ request: { ...request, relayToken: this.token },
98
+ },
99
+ { timeoutMs: 25_000, ...(signal ? { signal } : {}) },
100
+ );
101
+ }
102
+ private async poll(
103
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
104
+ ) {
105
+ while (!this.controller.signal.aborted) {
106
+ const batch = object(
107
+ await this.call({ action: "poll" }, this.controller.signal),
108
+ );
109
+ if (!Array.isArray(batch["requests"]) || !Array.isArray(batch["active"]))
110
+ throw new Error("Invalid shared context relay batch");
111
+ const active = batch["active"];
112
+ for (const [id, controller] of this.incoming)
113
+ if (!active.includes(id)) controller.abort();
114
+ for (const value of batch["requests"]) {
115
+ const entry = object(value);
116
+ const id = entry["id"];
117
+ if (typeof id !== "string" || this.incoming.has(id))
118
+ throw new Error("Invalid shared context relay request");
119
+ const controller = new AbortController();
120
+ this.incoming.set(id, controller);
121
+ void this.respond(id, entry["request"], controller, handle)
122
+ .catch((error: unknown) => {
123
+ this.fail(error);
124
+ })
125
+ .finally(() => this.incoming.delete(id));
126
+ }
127
+ }
128
+ if (this.failed) throw this.failed;
129
+ }
130
+ private async respond(
131
+ id: string,
132
+ request: unknown,
133
+ controller: AbortController,
134
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
135
+ ) {
136
+ let reply: object;
137
+ try {
138
+ controller.signal.throwIfAborted();
139
+ const result = await handle(request, controller.signal);
140
+ reply = { ok: true, result };
141
+ } catch (error) {
142
+ reply = {
143
+ ok: false,
144
+ error: error instanceof Error ? error.message : String(error),
145
+ };
146
+ }
147
+ if (controller.signal.aborted || this.controller.signal.aborted) return;
148
+ if (Buffer.byteLength(JSON.stringify(reply)) > RELAY_PAYLOAD_BYTES)
149
+ reply = {
150
+ ok: false,
151
+ error: "Shared context response is too large; narrow the request",
152
+ };
153
+ await this.call({ action: "reply", id, ...reply }, this.controller.signal);
154
+ }
155
+ private fail(error: unknown): void {
156
+ if (this.closed) return;
157
+ this.failed = error instanceof Error ? error : new Error(String(error));
158
+ void this.close();
159
+ this.onFailure?.(this.failed);
160
+ }
161
+ close(): Promise<void> {
162
+ if (this.closing) return this.closing;
163
+ this.closed = true;
164
+ this.controller.abort();
165
+ for (const controller of this.incoming.values()) controller.abort();
166
+ this.incoming.clear();
167
+ // A separate bounded connection can close the accepted remote daemon.
168
+ // If the machine disappeared, its 30-second lease performs cleanup.
169
+ this.closing = (async () => {
170
+ await this.starting?.catch(() => {});
171
+ if (this.pathValue)
172
+ await remoteExec(
173
+ this.client,
174
+ this.machine,
175
+ { op: "relay-close", path: this.pathValue, relayToken: this.token },
176
+ { timeoutMs: 10_000 },
177
+ );
178
+ })()
179
+ .catch(async () => {
180
+ // A failed close cannot prove removal. Keep replacement starts
181
+ // behind the daemon's 30-second no-poll lease, not a stale owner.
182
+ await new Promise((resolve) => setTimeout(resolve, 31_000));
183
+ })
184
+ .finally(() => {
185
+ this.client.close();
186
+ if (this.route && routes.get(this.route) === this)
187
+ routes.delete(this.route);
188
+ });
189
+ return this.closing;
190
+ }
191
+ }
@@ -0,0 +1,124 @@
1
+ import type { CoreClient } from "./client.js";
2
+ import { focusCoreWindow } from "./focus-window.js";
3
+ import { object } from "./protocol.js";
4
+ import { RemoteCoreEndpoint } from "./remote-endpoint.js";
5
+ import { terminalPane, terminalSnapshot } from "./terminal.js";
6
+
7
+ function unavailableFocus(): Error {
8
+ return Object.assign(
9
+ new Error(
10
+ "Focus is unavailable: the Herdr window cannot confirm which Core it controls. Use hc attach with the terminal address on this Core; messages and supervision remain available.",
11
+ ),
12
+ { code: "SHEPHERDR_DELIVERY_REJECTED" },
13
+ );
14
+ }
15
+
16
+ /** Translate legacy connection operations to Core without owning connection lifetime. */
17
+ export async function dispatchCoreRequest(
18
+ core: CoreClient | RemoteCoreEndpoint,
19
+ method: string,
20
+ params: Record<string, unknown>,
21
+ timeoutMs: number,
22
+ ): Promise<unknown> {
23
+ const options = { timeoutMs };
24
+ switch (method) {
25
+ case "ping":
26
+ return core.request("hello", {}, options);
27
+ case "session.snapshot":
28
+ return {
29
+ snapshot: terminalSnapshot(
30
+ await core.request("terminal.list", {}, options),
31
+ ),
32
+ };
33
+ case "agent.get": {
34
+ const listing = object(await core.request("terminal.list", {}, options));
35
+ const snapshot = terminalSnapshot(listing);
36
+ const terminals = listing["terminals"];
37
+ // Include finished and non-Pi terminals: an address must not redirect.
38
+ const exact =
39
+ Array.isArray(terminals) &&
40
+ terminals.some(
41
+ (terminal) => object(terminal)["address"] === params["target"],
42
+ );
43
+ const matches = exact
44
+ ? []
45
+ : snapshot.agents.filter((agent) => agent.name === params["target"]);
46
+ if (matches.length > 1)
47
+ throw new Error("Agent name is ambiguous; use its terminal address");
48
+ return {
49
+ agent: terminalPane(
50
+ await core.request(
51
+ "terminal.get",
52
+ { terminal: matches[0]?.terminal_id ?? params["target"] },
53
+ options,
54
+ ),
55
+ ),
56
+ };
57
+ }
58
+ case "pane.get":
59
+ case "pane.current":
60
+ return {
61
+ pane: terminalPane(
62
+ await core.request(
63
+ "terminal.get",
64
+ { terminal: params["pane_id"] ?? params["caller_pane_id"] },
65
+ options,
66
+ ),
67
+ ),
68
+ };
69
+ case "agent.read": {
70
+ const result = object(
71
+ await core.request(
72
+ "terminal.read",
73
+ {
74
+ terminal: params["target"],
75
+ lines: params["source"] === "visible" ? 0 : params["lines"],
76
+ },
77
+ options,
78
+ ),
79
+ );
80
+ return {
81
+ read: {
82
+ text: result["text"],
83
+ truncated: result["complete"] === false,
84
+ },
85
+ };
86
+ }
87
+ case "agent.focus":
88
+ if (core instanceof RemoteCoreEndpoint) throw unavailableFocus();
89
+ if (typeof params["target"] !== "string")
90
+ throw new Error("Use the exact local terminal address");
91
+ return focusCoreWindow(core, params["target"]);
92
+ case "workspace.close":
93
+ case "tab.close":
94
+ throw new Error(
95
+ "Window-location cleanup is unavailable through Core; close only the created terminal by its exact address",
96
+ );
97
+ case "terminal.close":
98
+ case "pane.close": {
99
+ const terminal = params["pane_id"] ?? params["id"];
100
+ if (typeof terminal !== "string" || !/^t[0-9a-z]+$/.test(terminal))
101
+ throw new Error(
102
+ "Cleanup requires an exact local Core terminal address",
103
+ );
104
+ const current = object(
105
+ await core.request("terminal.get", { terminal }, options),
106
+ );
107
+ if (current["address"] !== terminal)
108
+ throw new Error(
109
+ "Core terminal identity changed; resolve the target again",
110
+ );
111
+ if (current["state"] === "live")
112
+ await core.request("terminal.kill", { terminal }, options);
113
+ else if (current["state"] !== "finished")
114
+ throw new Error(
115
+ "Core terminal state is unknown; inspect it before cleanup",
116
+ );
117
+ return core.request("terminal.rm", { terminal }, options);
118
+ }
119
+ default:
120
+ throw new Error(
121
+ `Action ${method} is unavailable through Core; use Core terminal operations or the Herdr window commands`,
122
+ );
123
+ }
124
+ }