@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.
- package/CHANGELOG.md +26 -0
- package/README.md +20 -12
- package/index.ts +2 -2
- package/package.json +10 -11
- package/src/agent-identity.ts +75 -0
- package/src/agents-contract.ts +20 -12
- package/src/agents-discovery.ts +79 -34
- package/src/agents-focus.ts +15 -9
- package/src/agents-spawn.ts +25 -7
- package/src/agents-tool.ts +35 -7
- package/src/agents-work.ts +2 -2
- package/src/attachment-notes.ts +25 -24
- package/src/attachment-protocol.ts +35 -15
- package/src/attachment-routing.ts +28 -24
- package/src/attachment-target.ts +58 -19
- package/src/attachment.ts +13 -17
- package/src/board/host.ts +19 -20
- package/src/board/membership.ts +49 -30
- package/src/close-idle.ts +89 -0
- package/src/context-routing.ts +196 -0
- package/src/control-panel/index.ts +3 -1
- package/src/control-panel/items.ts +14 -2
- package/src/control-panel/view.ts +6 -2
- package/src/controller.ts +11 -2
- package/src/core/AGENTS.md +5 -0
- package/src/core/backend.ts +266 -0
- package/src/core/client.ts +249 -0
- package/src/core/context-relay.mjs +111 -0
- package/src/core/focus-channel-helper.mjs +165 -0
- package/src/core/focus-channel-stream.ts +140 -0
- package/src/core/focus-channel-wire.mjs +160 -0
- package/src/core/focus-channel.ts +213 -0
- package/src/core/focus-window.ts +192 -0
- package/src/core/pi-executable.mjs +34 -0
- package/src/core/protocol.ts +116 -0
- package/src/core/registration.ts +51 -0
- package/src/core/remote-endpoint.ts +119 -0
- package/src/core/remote-exec.ts +122 -0
- package/src/core/remote-helper.mjs +244 -0
- package/src/core/remote-reader.ts +67 -0
- package/src/core/remote-relay.ts +191 -0
- package/src/core/request.ts +124 -0
- package/src/core/spawn.ts +177 -0
- package/src/core/status.ts +68 -0
- package/src/core/terminal.ts +103 -0
- package/src/fleet/catalog.ts +83 -0
- package/src/fleet/connection.ts +111 -0
- package/src/fleet/index.ts +161 -122
- package/src/fleet/inspection.ts +19 -1
- package/src/fleet/machine.ts +3 -0
- package/src/fleet/monitor.ts +18 -4
- package/src/fleet/persistence.ts +26 -3
- package/src/fleet/setup.ts +54 -13
- package/src/herdr.ts +25 -5
- package/src/launch-contract.ts +48 -0
- package/src/launch-location.ts +151 -0
- package/src/launch.ts +30 -183
- package/src/messages/attribution.ts +15 -6
- package/src/messages/events.ts +10 -4
- package/src/messages/focus.ts +11 -2
- package/src/messages/guidance.ts +22 -16
- package/src/monitor-extension-messages.ts +9 -2
- package/src/monitor-record.ts +13 -6
- package/src/monitor-state.ts +18 -4
- package/src/monitor.ts +31 -0
- package/src/peer-commands.ts +11 -0
- package/src/peer-inbox-delivery.ts +171 -0
- package/src/peer-inbox-focus.ts +113 -0
- package/src/peer-inbox.ts +126 -208
- package/src/remote/deployment.ts +1 -1
- package/src/remote/shepherdr-checkpoints.mjs +20 -2
- package/src/remote/shepherdr-context.mjs +15 -3
- package/src/remote/shepherdr-peer.mjs +18 -5
- package/src/remote/shepherdr-session.mjs +9 -2
- package/src/remote/shepherdr.mjs +1 -1
- package/src/settlement/collector.ts +2 -2
- package/src/settlement/index.ts +12 -0
- package/src/shared-context-host.ts +7 -18
- package/src/shared-context.ts +139 -12
- package/src/spawn-context.ts +10 -5
- package/src/spawn-ownership.ts +91 -0
- package/src/types.ts +10 -5
- package/src/worker-ownership.ts +92 -0
- package/src/worker-service.ts +13 -82
- package/changelog.ts +0 -337
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { CoreClient } from "./client.js";
|
|
8
|
+
import { object } from "./protocol.js";
|
|
9
|
+
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
const delay = (ms: number) =>
|
|
12
|
+
new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
13
|
+
|
|
14
|
+
function appSocket(): string {
|
|
15
|
+
return join(
|
|
16
|
+
process.env["HERDR_APP_HOME"] ||
|
|
17
|
+
join(
|
|
18
|
+
process.env["XDG_CONFIG_HOME"] || join(homedir(), ".config"),
|
|
19
|
+
"herdr-app",
|
|
20
|
+
),
|
|
21
|
+
"herdr-app.sock",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function app(args: string[]): Promise<Record<string, unknown>> {
|
|
26
|
+
try {
|
|
27
|
+
const { stdout } = await exec("herdr-app", args, {
|
|
28
|
+
timeout: 7_000,
|
|
29
|
+
maxBuffer: 1024 * 1024,
|
|
30
|
+
});
|
|
31
|
+
const result = object(JSON.parse(stdout));
|
|
32
|
+
if (typeof result["error"] === "string") throw new Error(result["error"]);
|
|
33
|
+
return result;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`Herdr window did not respond: ${error instanceof Error ? error.message : String(error)}`,
|
|
37
|
+
{ cause: error },
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function panes(
|
|
43
|
+
world: Record<string, unknown>,
|
|
44
|
+
): Array<{ space: string; tab: string; terminal: string; name: string }> {
|
|
45
|
+
if (!Array.isArray(world["spaces"]))
|
|
46
|
+
throw new Error("Herdr window returned an invalid workspace list");
|
|
47
|
+
const result: Array<{
|
|
48
|
+
space: string;
|
|
49
|
+
tab: string;
|
|
50
|
+
terminal: string;
|
|
51
|
+
name: string;
|
|
52
|
+
}> = [];
|
|
53
|
+
for (const space of world["spaces"]) {
|
|
54
|
+
const s = object(space);
|
|
55
|
+
if (typeof s["id"] !== "string" || !Array.isArray(s["tabs"]))
|
|
56
|
+
throw new Error("Herdr window returned an invalid workspace");
|
|
57
|
+
for (const tab of s["tabs"]) {
|
|
58
|
+
const t = object(tab);
|
|
59
|
+
if (typeof t["id"] !== "string" || !Array.isArray(t["terminals"]))
|
|
60
|
+
throw new Error("Herdr window returned an invalid tab");
|
|
61
|
+
for (const value of t["terminals"]) {
|
|
62
|
+
const terminal = object(value);
|
|
63
|
+
if (typeof terminal["terminal"] === "string")
|
|
64
|
+
result.push({
|
|
65
|
+
space: s["id"],
|
|
66
|
+
tab: t["id"],
|
|
67
|
+
terminal: terminal["terminal"],
|
|
68
|
+
name: typeof terminal["name"] === "string" ? terminal["name"] : "",
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Verify the selected window sees this Core before acting on its local terminal IDs. */
|
|
77
|
+
export async function focusCoreWindow(
|
|
78
|
+
core: CoreClient,
|
|
79
|
+
target: string,
|
|
80
|
+
): Promise<void> {
|
|
81
|
+
if (!/^t[0-9a-z]+$/.test(target))
|
|
82
|
+
throw new Error("Use the exact local terminal address");
|
|
83
|
+
const socket = appSocket();
|
|
84
|
+
const original = await stat(socket).catch(() => {
|
|
85
|
+
throw new Error("Open the Herdr window on this machine and retry focus");
|
|
86
|
+
});
|
|
87
|
+
const token = randomBytes(12).toString("hex");
|
|
88
|
+
const name = `probe-${token}`;
|
|
89
|
+
const space = `sp${token}`;
|
|
90
|
+
const tab = `tb${token}`;
|
|
91
|
+
let probe: string | undefined;
|
|
92
|
+
let focused = false;
|
|
93
|
+
let failed = false;
|
|
94
|
+
let failure: unknown;
|
|
95
|
+
try {
|
|
96
|
+
const created = object(
|
|
97
|
+
await core.request("terminal.run", {
|
|
98
|
+
argv: [process.execPath, "-e", "setTimeout(()=>{},120000)"],
|
|
99
|
+
name,
|
|
100
|
+
labels: { "herdr.space": space, "herdr.tab": tab },
|
|
101
|
+
no_parent: true,
|
|
102
|
+
no_notify: true,
|
|
103
|
+
rm: true,
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
if (
|
|
107
|
+
typeof created["address"] !== "string" ||
|
|
108
|
+
!/^t[0-9a-z]+$/.test(created["address"])
|
|
109
|
+
)
|
|
110
|
+
throw new Error(
|
|
111
|
+
"Core did not return a probe terminal; inspect its terminals before retrying",
|
|
112
|
+
);
|
|
113
|
+
probe = created["address"];
|
|
114
|
+
const deadline = Date.now() + 8_000;
|
|
115
|
+
let world: ReturnType<typeof panes> = [];
|
|
116
|
+
while (Date.now() < deadline) {
|
|
117
|
+
world = panes(await app(["ls"]));
|
|
118
|
+
if (
|
|
119
|
+
world.some(
|
|
120
|
+
(entry) =>
|
|
121
|
+
entry.space === space &&
|
|
122
|
+
entry.tab === tab &&
|
|
123
|
+
entry.terminal === probe &&
|
|
124
|
+
entry.name === name,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
break;
|
|
128
|
+
await delay(100);
|
|
129
|
+
}
|
|
130
|
+
if (
|
|
131
|
+
!world.some(
|
|
132
|
+
(entry) =>
|
|
133
|
+
entry.space === space &&
|
|
134
|
+
entry.tab === tab &&
|
|
135
|
+
entry.terminal === probe &&
|
|
136
|
+
entry.name === name,
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
throw new Error(
|
|
140
|
+
"This Herdr window is not connected to the target Core; open its window and retry",
|
|
141
|
+
);
|
|
142
|
+
const checkWindow = async () => {
|
|
143
|
+
const current = await stat(socket);
|
|
144
|
+
if (current.dev !== original.dev || current.ino !== original.ino)
|
|
145
|
+
throw new Error(
|
|
146
|
+
"Herdr window changed during focus; inspect it before retrying",
|
|
147
|
+
);
|
|
148
|
+
};
|
|
149
|
+
await checkWindow();
|
|
150
|
+
if (!world.some((entry) => entry.terminal === target)) {
|
|
151
|
+
await app(["do", "space.select", JSON.stringify({ id: space })]);
|
|
152
|
+
await checkWindow();
|
|
153
|
+
await app(["do", "terminal.keep", JSON.stringify({ terminal: target })]);
|
|
154
|
+
const adoptionDeadline = Date.now() + 8_000;
|
|
155
|
+
while (Date.now() < adoptionDeadline) {
|
|
156
|
+
world = panes(await app(["ls"]));
|
|
157
|
+
if (world.some((entry) => entry.terminal === target)) break;
|
|
158
|
+
await delay(100);
|
|
159
|
+
}
|
|
160
|
+
if (!world.some((entry) => entry.terminal === target))
|
|
161
|
+
throw new Error(
|
|
162
|
+
"Herdr did not finish opening the target; inspect its window before retrying",
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
await checkWindow();
|
|
166
|
+
await app(["do", "pane.focus", JSON.stringify({ terminal: target })]);
|
|
167
|
+
focused = true;
|
|
168
|
+
} catch (error) {
|
|
169
|
+
failed = true;
|
|
170
|
+
failure = error;
|
|
171
|
+
} finally {
|
|
172
|
+
if (probe) {
|
|
173
|
+
try {
|
|
174
|
+
await core.request("terminal.kill", { terminal: probe });
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (
|
|
177
|
+
error instanceof Error &&
|
|
178
|
+
"kind" in error &&
|
|
179
|
+
error.kind === "not_found"
|
|
180
|
+
) {
|
|
181
|
+
if (failed) throw failure;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
throw new Error(
|
|
185
|
+
`${focused ? "Focus succeeded" : `Focus failed: ${String(failure)}`} but its temporary terminal could not be closed: ${String(error)}`,
|
|
186
|
+
{ cause: failure ?? error },
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (failed) throw failure;
|
|
192
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, stat } from "node:fs/promises";
|
|
3
|
+
import { delimiter, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** @param {string} cwd Resolve on the target so Core cannot mistake Pi for a template. */
|
|
6
|
+
export async function piExecutable(cwd) {
|
|
7
|
+
const windows = process.platform === "win32";
|
|
8
|
+
const suffixes = windows
|
|
9
|
+
? (process.env["PATHEXT"] || ".COM;.EXE;.BAT;.CMD")
|
|
10
|
+
.split(";")
|
|
11
|
+
.filter(Boolean)
|
|
12
|
+
: [""];
|
|
13
|
+
for (const directory of (process.env["PATH"] || "").split(delimiter)) {
|
|
14
|
+
for (const suffix of suffixes) {
|
|
15
|
+
const path = resolve(cwd, directory || ".", `pi${suffix}`);
|
|
16
|
+
try {
|
|
17
|
+
if (!(await stat(path)).isFile()) continue;
|
|
18
|
+
await access(path, windows ? constants.F_OK : constants.X_OK);
|
|
19
|
+
return windows ? path.replaceAll("\\", "/") : path;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (
|
|
22
|
+
!error ||
|
|
23
|
+
typeof error !== "object" ||
|
|
24
|
+
!("code" in error) ||
|
|
25
|
+
!["ENOENT", "EACCES", "ENOTDIR"].includes(String(error.code))
|
|
26
|
+
)
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
throw new Error(
|
|
32
|
+
"Pi is not on PATH on the target machine; install it before spawning an agent",
|
|
33
|
+
);
|
|
34
|
+
}
|
|
@@ -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
|
+
}
|