@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,116 @@
1
+ export type CoreObject = Record<string, unknown>;
2
+
3
+ export interface CoreSnapshot {
4
+ seq: number;
5
+ terminals: CoreObject[];
6
+ }
7
+
8
+ interface CoreEvent {
9
+ seq: number;
10
+ type: string;
11
+ data: unknown;
12
+ terminal?: string;
13
+ machine?: string;
14
+ }
15
+
16
+ export type CoreNotification =
17
+ | ({ method: "snapshot" | "missed" } & CoreSnapshot)
18
+ | { method: "event"; event: CoreEvent }
19
+ | { method: "heartbeat"; seq: number };
20
+
21
+ class CoreRpcError extends Error {
22
+ readonly code: number;
23
+ readonly kind: string;
24
+ readonly hint: string;
25
+
26
+ constructor(code: number, message: string, kind: string, hint: string) {
27
+ super(message);
28
+ this.name = "CoreRpcError";
29
+ this.code = code;
30
+ this.kind = kind;
31
+ this.hint = hint;
32
+ }
33
+ }
34
+
35
+ export function object(value: unknown): CoreObject {
36
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
37
+ throw new Error("Invalid Core JSON-RPC object");
38
+ }
39
+ return value as CoreObject;
40
+ }
41
+
42
+ function sequence(value: unknown): number {
43
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
44
+ throw new Error("Invalid Core event sequence");
45
+ }
46
+ return value;
47
+ }
48
+
49
+ export function response(message: CoreObject): unknown {
50
+ if (message["jsonrpc"] !== "2.0" || message["id"] !== 1) {
51
+ throw new Error("Invalid Core JSON-RPC response");
52
+ }
53
+ if ("error" in message === "result" in message) {
54
+ throw new Error("Invalid Core JSON-RPC result");
55
+ }
56
+ if ("error" in message) {
57
+ const error = object(message["error"]);
58
+ const data = object(error["data"]);
59
+ if (
60
+ typeof error["code"] !== "number" ||
61
+ !Number.isSafeInteger(error["code"]) ||
62
+ typeof error["message"] !== "string" ||
63
+ typeof data["kind"] !== "string" ||
64
+ typeof data["hint"] !== "string"
65
+ ) {
66
+ throw new Error("Invalid Core JSON-RPC error");
67
+ }
68
+ throw new CoreRpcError(
69
+ error["code"],
70
+ error["message"],
71
+ data["kind"],
72
+ data["hint"],
73
+ );
74
+ }
75
+ return message["result"];
76
+ }
77
+
78
+ export function snapshot(value: unknown): CoreSnapshot {
79
+ const data = object(value);
80
+ const terminals = data["terminals"];
81
+ if (!Array.isArray(terminals)) throw new Error("Invalid Core snapshot");
82
+ return { seq: sequence(data["seq"]), terminals: terminals.map(object) };
83
+ }
84
+
85
+ export function notification(message: CoreObject): CoreNotification {
86
+ if (message["jsonrpc"] !== "2.0" || "id" in message) {
87
+ throw new Error("Invalid Core notification");
88
+ }
89
+ const params = object(message["params"]);
90
+ switch (message["method"]) {
91
+ case "missed":
92
+ return { method: "missed", ...snapshot(params) };
93
+ case "heartbeat":
94
+ return { method: "heartbeat", seq: sequence(params["seq"]) };
95
+ case "event": {
96
+ if (typeof params["type"] !== "string" || !("data" in params)) {
97
+ throw new Error("Invalid Core event");
98
+ }
99
+ const event: CoreEvent = {
100
+ seq: sequence(params["seq"]),
101
+ type: params["type"],
102
+ data: params["data"],
103
+ };
104
+ for (const key of ["terminal", "machine"] as const) {
105
+ if (key in params) {
106
+ if (typeof params[key] !== "string")
107
+ throw new Error("Invalid Core event address");
108
+ event[key] = params[key];
109
+ }
110
+ }
111
+ return { method: "event", event };
112
+ }
113
+ default:
114
+ throw new Error("Unknown Core notification");
115
+ }
116
+ }
@@ -0,0 +1,51 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreClient } from "./client.js";
3
+ import { object } from "./protocol.js";
4
+
5
+ export const CORE_SESSION_LABEL = "pi.session_file";
6
+
7
+ export interface CoreIdentity {
8
+ terminalId: string;
9
+ socketPath: string;
10
+ }
11
+
12
+ export function coreIdentity(ctx: ExtensionContext): CoreIdentity | undefined {
13
+ const terminalId = process.env["HC_TERMINAL_ID"];
14
+ const socketPath = process.env["HC_TERMINAL_SOCKET"];
15
+ return ctx.mode === "tui" && terminalId && socketPath
16
+ ? { terminalId, socketPath }
17
+ : undefined;
18
+ }
19
+
20
+ /** Publish only after the authenticated receiver is ready; never label its token. */
21
+ export async function publishCoreSession(
22
+ identity: CoreIdentity,
23
+ sessionFile: string,
24
+ ): Promise<() => Promise<void>> {
25
+ const client = new CoreClient(identity.socketPath);
26
+ const terminal = identity.terminalId;
27
+ try {
28
+ await client.request("terminal.label", {
29
+ terminal,
30
+ labels: { [CORE_SESSION_LABEL]: sessionFile },
31
+ });
32
+ } catch (error) {
33
+ client.close();
34
+ throw error;
35
+ }
36
+ return async () => {
37
+ try {
38
+ const current = object(
39
+ await client.request("terminal.get", { terminal }),
40
+ );
41
+ const labels = object(current["labels"]);
42
+ if (labels[CORE_SESSION_LABEL] === sessionFile)
43
+ await client.request("terminal.label", {
44
+ terminal,
45
+ labels: { [CORE_SESSION_LABEL]: "" },
46
+ });
47
+ } finally {
48
+ client.close();
49
+ }
50
+ };
51
+ }
@@ -0,0 +1,119 @@
1
+ import {
2
+ CoreClient,
3
+ type CoreEventFilter,
4
+ type CoreRequestOptions,
5
+ type CoreSubscribeOptions,
6
+ } from "./client.js";
7
+ import { type CoreNotification, type CoreObject, object } from "./protocol.js";
8
+ import { type CoreMachine, remoteExec } from "./remote-exec.js";
9
+
10
+ /** Terminal addresses are local within this machine-scoped fleet runtime. */
11
+ export class RemoteCoreEndpoint {
12
+ readonly host: CoreClient;
13
+ readonly machine: CoreMachine;
14
+ constructor(socketPath: string, machine: CoreMachine) {
15
+ this.host = new CoreClient(socketPath);
16
+ this.machine = machine;
17
+ }
18
+ close(): void {
19
+ this.host.close();
20
+ }
21
+ private local(value: unknown): CoreObject {
22
+ const terminal = object(value);
23
+ const prefix = `${this.machine.name}/`;
24
+ if (
25
+ typeof terminal["address"] !== "string" ||
26
+ !terminal["address"].startsWith(prefix)
27
+ )
28
+ throw new Error("Remote Core returned another machine's terminal");
29
+ return { ...terminal, address: terminal["address"].slice(prefix.length) };
30
+ }
31
+ async request(
32
+ method: string,
33
+ params: CoreObject = {},
34
+ options: CoreRequestOptions = {},
35
+ ): Promise<unknown> {
36
+ if (method === "hello") {
37
+ const identity = object(
38
+ await remoteExec(this.host, this.machine, { op: "identity" }, options),
39
+ );
40
+ return { core: { id: identity["session"], name: identity["host"] } };
41
+ }
42
+ if (method === "terminal.list") {
43
+ const result = object(
44
+ await this.host.request("machine.list", {}, options),
45
+ );
46
+ const machines = result["machines"];
47
+ const machine = Array.isArray(machines)
48
+ ? machines.map(object).find((entry) => entry["id"] === this.machine.id)
49
+ : undefined;
50
+ if (
51
+ !machine ||
52
+ machine["state"] !== "connected" ||
53
+ machine["name"] !== this.machine.name
54
+ )
55
+ throw new Error(
56
+ "Remote Core is disconnected or renamed; refresh machines and reconnect before continuing",
57
+ );
58
+ // Aggregate terminal.list silently omits machines slower than 3 seconds.
59
+ // Query the selected Core itself so an incomplete list cannot drop watches.
60
+ return remoteExec(this.host, this.machine, { op: "list" }, options);
61
+ }
62
+ if (method === "terminal.run")
63
+ return this.local(
64
+ await this.host.request(
65
+ method,
66
+ {
67
+ ...params,
68
+ on: this.machine.id,
69
+ no_parent: true,
70
+ parent: undefined,
71
+ env: {},
72
+ },
73
+ options,
74
+ ),
75
+ );
76
+ if (
77
+ typeof params["terminal"] !== "string" ||
78
+ !/^t[0-9a-z]+$/.test(params["terminal"])
79
+ )
80
+ throw new Error("Use an exact terminal address from this machine");
81
+ const result = await this.host.request(
82
+ method,
83
+ { ...params, terminal: `${this.machine.id}/${params["terminal"]}` },
84
+ options,
85
+ );
86
+ return method === "terminal.get" || method === "terminal.kill"
87
+ ? this.local(result)
88
+ : result;
89
+ }
90
+ subscribe(
91
+ _filter: CoreEventFilter,
92
+ onNotification: (message: CoreNotification) => void,
93
+ options: CoreSubscribeOptions = {},
94
+ ) {
95
+ // Core 0.1.14 can retain a pre-rename alias in its event mirror.
96
+ // Treat events only as invalidations; get/list remain authoritative by ID.
97
+ return this.host.subscribe(
98
+ {},
99
+ (message) => {
100
+ if (message.method === "snapshot" || message.method === "missed")
101
+ onNotification({
102
+ ...message,
103
+ terminals: [],
104
+ });
105
+ else if (message.method === "heartbeat") onNotification(message);
106
+ else if (message.method === "event")
107
+ onNotification({
108
+ ...message,
109
+ event: {
110
+ seq: message.event.seq,
111
+ type: "reconcile",
112
+ data: {},
113
+ },
114
+ });
115
+ },
116
+ options,
117
+ );
118
+ }
119
+ }
@@ -0,0 +1,122 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import type { CoreClient, CoreRequestOptions } from "./client.js";
3
+ import { type CoreObject, object } from "./protocol.js";
4
+
5
+ export interface CoreMachine {
6
+ id: string;
7
+ name: string;
8
+ host: string;
9
+ session: string;
10
+ state: string;
11
+ }
12
+
13
+ export async function coreMachines(client: CoreClient): Promise<CoreMachine[]> {
14
+ const machines = object(await client.request("machine.list"))["machines"];
15
+ if (!Array.isArray(machines))
16
+ throw new Error("Core returned no machine catalog");
17
+ return machines.map((value) => {
18
+ const machine = object(value);
19
+ for (const field of ["id", "name", "host", "state"])
20
+ if (typeof machine[field] !== "string" || !machine[field])
21
+ throw new Error("Core returned an invalid machine identity");
22
+ return {
23
+ id: machine["id"] as string,
24
+ name: machine["name"] as string,
25
+ host: machine["host"] as string,
26
+ state: machine["state"] as string,
27
+ session:
28
+ typeof machine["session"] === "string" ? machine["session"] : "default",
29
+ };
30
+ });
31
+ }
32
+
33
+ const moduleUrl = (source: string) =>
34
+ `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`;
35
+ let bundle:
36
+ | Promise<{ source: string; modules: Record<string, string> }>
37
+ | undefined;
38
+ async function sources() {
39
+ const read = (path: string) =>
40
+ readFile(new URL(path, import.meta.url), "utf8");
41
+ const [source, peer, session, watch, checkpoints, context, relay, pi] =
42
+ await Promise.all([
43
+ readFile(new URL("./remote-helper.mjs", import.meta.url), "utf8"),
44
+ read("../remote/shepherdr-peer.mjs"),
45
+ read("../remote/shepherdr-session.mjs"),
46
+ read("../remote/shepherdr-session-watch.mjs"),
47
+ read("../remote/shepherdr-checkpoints.mjs"),
48
+ read("../remote/shepherdr-context.mjs"),
49
+ read("./context-relay.mjs"),
50
+ read("./pi-executable.mjs"),
51
+ ]);
52
+ const peerUrl = moduleUrl(peer);
53
+ return {
54
+ source,
55
+ modules: {
56
+ pi: moduleUrl(pi),
57
+ relay: moduleUrl(relay),
58
+ peer: peerUrl,
59
+ session: moduleUrl(session),
60
+ watch: moduleUrl(watch),
61
+ context: moduleUrl(
62
+ context
63
+ .replace('"./shepherdr-peer.mjs"', JSON.stringify(peerUrl))
64
+ .replace(
65
+ '"./shepherdr-checkpoints.mjs"',
66
+ JSON.stringify(moduleUrl(checkpoints)),
67
+ ),
68
+ ),
69
+ },
70
+ };
71
+ }
72
+
73
+ /** One bounded remote process; never retries a possibly delivered operation. */
74
+ export async function remoteExec(
75
+ client: CoreClient,
76
+ machine: CoreMachine,
77
+ input: CoreObject,
78
+ options: CoreRequestOptions = {},
79
+ ): Promise<unknown> {
80
+ const { source, modules } = await (bundle ??= sources());
81
+ const result = object(
82
+ await client.request(
83
+ "machine.exec",
84
+ {
85
+ on: machine.id,
86
+ argv: ["node", "--input-type=module", "-e", source],
87
+ timeout: input["op"] === "watch" ? 20 : 90,
88
+ input: Buffer.from(
89
+ JSON.stringify({
90
+ ...input,
91
+ coreId: machine.id,
92
+ session: machine.session,
93
+ modules,
94
+ }),
95
+ ).toString("base64"),
96
+ },
97
+ { timeoutMs: 100_000, ...options },
98
+ ),
99
+ );
100
+ if (
101
+ result["timed_out"] ||
102
+ result["truncated"] ||
103
+ result["code"] !== 0 ||
104
+ typeof result["stdout"] !== "string"
105
+ )
106
+ throw new Error(
107
+ "Remote operation did not finish; inspect the target before retrying and verify Node.js and hc are available in the selected Core's PATH",
108
+ );
109
+ const receipt = object(
110
+ JSON.parse(Buffer.from(result["stdout"], "base64").toString()),
111
+ );
112
+ if (receipt["ok"] !== true)
113
+ throw Object.assign(
114
+ new Error(
115
+ typeof receipt["error"] === "string"
116
+ ? receipt["error"]
117
+ : "Remote operation failed",
118
+ ),
119
+ { code: receipt["code"] },
120
+ );
121
+ return receipt["result"];
122
+ }
@@ -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
+ }