@howaboua/pi-shepherdr 0.2.27 → 0.2.28-core.12.1.gda85fa2e8a0f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -48
- package/index.ts +7 -1
- package/package.json +2 -9
- package/src/agent-identity.ts +3 -3
- package/src/agents-contract.ts +10 -14
- package/src/agents-discovery.ts +34 -54
- package/src/agents-focus.ts +23 -35
- package/src/agents-spawn.ts +24 -23
- package/src/agents-tool.ts +4 -19
- package/src/agents-work.ts +4 -3
- package/src/attachment-notes.ts +8 -7
- package/src/attachment-protocol.ts +3 -2
- package/src/attachment-routing.ts +1 -1
- package/src/attachment-target.ts +10 -18
- package/src/attachment.ts +14 -9
- package/src/board/discovery.ts +67 -0
- package/src/board/host.ts +93 -63
- package/src/board/membership.ts +16 -11
- package/src/board/records.ts +185 -0
- package/src/close-idle.ts +2 -9
- package/src/context-briefing.ts +230 -0
- package/src/context-routing.ts +1 -1
- package/src/control-panel/index.ts +2 -4
- package/src/control-panel/items.ts +1 -11
- package/src/control-panel/view.ts +3 -9
- package/src/controller.ts +50 -63
- package/src/core/AGENTS.md +7 -4
- package/src/core/admission-broker.mjs +235 -0
- package/src/core/admission-endpoint.ts +180 -0
- package/src/core/admission-owner.mjs +52 -0
- package/src/core/admission-startup.ts +130 -0
- package/src/core/admission.ts +181 -0
- package/src/core/agents.ts +102 -0
- package/src/core/backend.ts +110 -84
- package/src/core/client.ts +16 -0
- package/src/core/focus-channel-helper.mjs +6 -27
- package/src/core/focus-channel-wire.mjs +9 -6
- package/src/core/focus-channel.ts +5 -3
- package/src/core/focus-window.ts +15 -4
- package/src/core/helper-bootstrap.mjs +70 -0
- package/src/core/helper-context.mjs +98 -0
- package/src/core/helper-core.mjs +121 -0
- package/src/core/machines.ts +30 -0
- package/src/core/registration.ts +7 -2
- package/src/core/remote-endpoint.ts +80 -74
- package/src/core/remote-helper.ts +330 -0
- package/src/core/remote-reader.ts +3 -42
- package/src/core/remote-service.mjs +239 -0
- package/src/core/remote-transport.ts +290 -0
- package/src/core/spawn.ts +20 -20
- package/src/core/terminal-peer.mjs +57 -0
- package/src/core/terminal.ts +4 -2
- package/src/delivery.ts +39 -0
- package/src/fleet/catalog.ts +16 -58
- package/src/fleet/connection.ts +9 -18
- package/src/fleet/index.ts +38 -76
- package/src/fleet/inspection.ts +9 -22
- package/src/fleet/machine.ts +28 -12
- package/src/fleet/monitor.ts +8 -29
- package/src/fleet/persistence.ts +2 -2
- package/src/fleet/reconnect.ts +5 -3
- package/src/fleet/setup.ts +6 -16
- package/src/launch-contract.ts +0 -3
- package/src/launch-location.ts +4 -132
- package/src/launch.ts +18 -144
- package/src/messages/attachments.ts +1 -1
- package/src/messages/attribution.ts +9 -14
- package/src/messages/events.ts +5 -9
- package/src/messages/focus.ts +2 -7
- package/src/messages/guidance.ts +2 -43
- package/src/messages/peer-sharing.ts +133 -0
- package/src/monitor-events.ts +14 -43
- package/src/monitor-extension-messages.ts +5 -6
- package/src/monitor-record.ts +4 -0
- package/src/monitor-state.ts +1 -101
- package/src/monitor.ts +38 -66
- package/src/notes-discovery.ts +67 -0
- package/src/peer-inbox.ts +21 -27
- package/src/remote/context-relay.ts +25 -10
- package/src/remote/notes-reader.mjs +67 -0
- package/src/remote/shepherdr-channel.mjs +1 -1
- package/src/remote/shepherdr-checkpoints.mjs +49 -102
- package/src/remote/shepherdr-context.mjs +1 -1
- package/src/remote/shepherdr-peer.mjs +19 -24
- package/src/remote/shepherdr-session.mjs +18 -7
- package/src/saved-context.ts +62 -0
- package/src/settlement/collector.ts +29 -9
- package/src/settlement/index.ts +35 -6
- package/src/shared-context-host.ts +27 -33
- package/src/shared-context.ts +44 -15
- package/src/spawn-context.ts +11 -3
- package/src/spawn-ownership.ts +1 -1
- package/src/ssh-setup.ts +40 -73
- package/src/types.ts +4 -8
- package/src/voice-handoff.ts +1 -1
- package/src/widget.ts +7 -2
- package/src/worker-ownership.ts +2 -8
- package/src/worker-service.ts +6 -14
- package/src/core/context-relay.mjs +0 -111
- package/src/core/remote-exec.ts +0 -122
- package/src/core/remote-helper.mjs +0 -244
- package/src/core/remote-relay.ts +0 -191
- package/src/core/request.ts +0 -124
- package/src/herdr-client.ts +0 -364
- package/src/herdr.ts +0 -268
- package/src/machine-catalog.ts +0 -83
- package/src/monitor-event.ts +0 -84
- package/src/remote/client.ts +0 -127
- package/src/remote/deployment.ts +0 -179
- package/src/remote/focus-channels.ts +0 -89
- package/src/remote/shepherdr.mjs +0 -504
- package/src/remote/transport.ts +0 -369
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createServer } from "node:net";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import {
|
|
5
|
+
readAdmissionStart,
|
|
6
|
+
releaseAdmissionStart,
|
|
7
|
+
} from "./admission-owner.mjs";
|
|
8
|
+
|
|
9
|
+
export const LANE_LIMITS = Object.freeze({ launch: 4, bulk: 8 });
|
|
10
|
+
export const MAX_FRAME_BYTES = 8 * 1024;
|
|
11
|
+
export const MAX_CLIENT_REQUESTS = 64;
|
|
12
|
+
export const MAX_REQUESTS = 1024;
|
|
13
|
+
|
|
14
|
+
/** @typedef {'launch' | 'bulk'} Lane */
|
|
15
|
+
/** @typedef {{lane: Lane, active: boolean}} Permit */
|
|
16
|
+
/** @typedef {{socket: import('node:net').Socket, requests: Map<string, Permit>, queues: Record<Lane, string[]>}} Client */
|
|
17
|
+
/** @typedef {{active: number, ready: Client[]}} LaneState */
|
|
18
|
+
|
|
19
|
+
/** The caller owns the private directory and stale-socket recovery.
|
|
20
|
+
* @param {string} socketPath
|
|
21
|
+
* @param {()=>Promise<void>} [releaseStartup]
|
|
22
|
+
*/
|
|
23
|
+
export function startAdmissionBroker(
|
|
24
|
+
socketPath,
|
|
25
|
+
releaseStartup = async () => {},
|
|
26
|
+
) {
|
|
27
|
+
/** @type {Set<Client>} */
|
|
28
|
+
const clients = new Set();
|
|
29
|
+
/** @type {Record<Lane, LaneState>} */
|
|
30
|
+
const lanes = {
|
|
31
|
+
launch: { active: 0, ready: [] },
|
|
32
|
+
bulk: { active: 0, ready: [] },
|
|
33
|
+
};
|
|
34
|
+
let requests = 0;
|
|
35
|
+
let stopping = false;
|
|
36
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
37
|
+
let idle;
|
|
38
|
+
const server = createServer(connect);
|
|
39
|
+
let starting = true;
|
|
40
|
+
function started() {
|
|
41
|
+
if (!starting) return;
|
|
42
|
+
starting = false;
|
|
43
|
+
void releaseStartup().catch(() => {
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
stop();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function stop() {
|
|
50
|
+
if (stopping) return;
|
|
51
|
+
stopping = true;
|
|
52
|
+
started();
|
|
53
|
+
clearTimeout(idle);
|
|
54
|
+
for (const client of clients) client.socket.destroy();
|
|
55
|
+
// net.Server owns unlinking its successfully bound Unix socket. Never
|
|
56
|
+
// unlink by pathname here: a losing EADDRINUSE contender owns nothing.
|
|
57
|
+
server.close();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @param {number} delay */
|
|
61
|
+
function armIdle(delay) {
|
|
62
|
+
clearTimeout(idle);
|
|
63
|
+
idle = setTimeout(stop, delay);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @param {Client} client @param {object} response */
|
|
67
|
+
function send(client, response) {
|
|
68
|
+
const frame = `${JSON.stringify(response)}\n`;
|
|
69
|
+
if (
|
|
70
|
+
Buffer.byteLength(frame) > MAX_FRAME_BYTES ||
|
|
71
|
+
client.socket.writableLength > MAX_FRAME_BYTES * MAX_CLIENT_REQUESTS
|
|
72
|
+
) {
|
|
73
|
+
client.socket.destroy();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
client.socket.write(frame);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function drain() {
|
|
80
|
+
if (stopping) return;
|
|
81
|
+
for (const lane of /** @type {Lane[]} */ (["launch", "bulk"])) {
|
|
82
|
+
const state = lanes[lane];
|
|
83
|
+
while (state.active < LANE_LIMITS[lane] && state.ready.length) {
|
|
84
|
+
const client = state.ready.shift();
|
|
85
|
+
if (!client || client.socket.destroyed) continue;
|
|
86
|
+
const id = client.queues[lane].shift();
|
|
87
|
+
if (id === undefined) continue;
|
|
88
|
+
const permit = client.requests.get(id);
|
|
89
|
+
if (!permit) continue;
|
|
90
|
+
permit.active = true;
|
|
91
|
+
state.active++;
|
|
92
|
+
if (client.queues[lane].length) state.ready.push(client);
|
|
93
|
+
send(client, { id, state: "granted" });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** @param {Client} client @param {string} id */
|
|
99
|
+
function release(client, id) {
|
|
100
|
+
const permit = client.requests.get(id);
|
|
101
|
+
// Idempotent cleanup allows cancellation to race a normal release.
|
|
102
|
+
if (!permit) return;
|
|
103
|
+
client.requests.delete(id);
|
|
104
|
+
requests--;
|
|
105
|
+
const state = lanes[permit.lane];
|
|
106
|
+
if (permit.active) state.active--;
|
|
107
|
+
else {
|
|
108
|
+
const queue = client.queues[permit.lane];
|
|
109
|
+
queue.splice(queue.indexOf(id), 1);
|
|
110
|
+
if (!queue.length)
|
|
111
|
+
state.ready = state.ready.filter((entry) => entry !== client);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {Client} client @param {Buffer} frame */
|
|
116
|
+
function receive(client, frame) {
|
|
117
|
+
const message = JSON.parse(
|
|
118
|
+
new TextDecoder("utf-8", { fatal: true }).decode(frame),
|
|
119
|
+
);
|
|
120
|
+
if (
|
|
121
|
+
!message ||
|
|
122
|
+
typeof message !== "object" ||
|
|
123
|
+
Array.isArray(message) ||
|
|
124
|
+
typeof message.id !== "string" ||
|
|
125
|
+
!message.id ||
|
|
126
|
+
!["acquire", "release", "cancel"].includes(message.op)
|
|
127
|
+
)
|
|
128
|
+
throw new Error("Invalid admission frame");
|
|
129
|
+
if (message.op !== "acquire") {
|
|
130
|
+
if (Object.keys(message).some((key) => key !== "id" && key !== "op"))
|
|
131
|
+
throw new Error("Invalid cleanup frame");
|
|
132
|
+
release(client, message.id);
|
|
133
|
+
drain();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (
|
|
137
|
+
(message.lane !== "bulk" && message.lane !== "launch") ||
|
|
138
|
+
Object.keys(message).some((key) => !["id", "op", "lane"].includes(key)) ||
|
|
139
|
+
client.requests.has(message.id)
|
|
140
|
+
)
|
|
141
|
+
throw new Error("Invalid acquire frame");
|
|
142
|
+
if (
|
|
143
|
+
client.requests.size >= MAX_CLIENT_REQUESTS ||
|
|
144
|
+
requests >= MAX_REQUESTS
|
|
145
|
+
) {
|
|
146
|
+
send(client, {
|
|
147
|
+
id: message.id,
|
|
148
|
+
state: "error",
|
|
149
|
+
message: "Admission queue full",
|
|
150
|
+
});
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const lane = /** @type {Lane} */ (message.lane);
|
|
154
|
+
client.requests.set(message.id, { lane, active: false });
|
|
155
|
+
requests++;
|
|
156
|
+
if (!client.queues[lane].length) lanes[lane].ready.push(client);
|
|
157
|
+
client.queues[lane].push(message.id);
|
|
158
|
+
drain();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @param {import('node:net').Socket} socket */
|
|
162
|
+
function connect(socket) {
|
|
163
|
+
if (stopping) return socket.destroy();
|
|
164
|
+
clearTimeout(idle);
|
|
165
|
+
/** @type {Client} */
|
|
166
|
+
const client = {
|
|
167
|
+
socket,
|
|
168
|
+
requests: new Map(),
|
|
169
|
+
queues: { launch: [], bulk: [] },
|
|
170
|
+
};
|
|
171
|
+
clients.add(client);
|
|
172
|
+
let buffered = Buffer.alloc(0);
|
|
173
|
+
socket.on("error", () => socket.destroy());
|
|
174
|
+
socket.on("close", () => {
|
|
175
|
+
clients.delete(client);
|
|
176
|
+
for (const id of client.requests.keys()) release(client, id);
|
|
177
|
+
drain();
|
|
178
|
+
if (!clients.size && !stopping) armIdle(2000);
|
|
179
|
+
});
|
|
180
|
+
socket.on("data", (chunk) => {
|
|
181
|
+
try {
|
|
182
|
+
if (!Buffer.isBuffer(chunk)) throw new Error("Expected raw bytes");
|
|
183
|
+
// Bound the partial frame, not the chunk: one read can hold many frames.
|
|
184
|
+
let offset = 0;
|
|
185
|
+
while (offset < chunk.length && !socket.destroyed) {
|
|
186
|
+
const newline = chunk.indexOf(10, offset);
|
|
187
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
188
|
+
if (buffered.length + end - offset + 1 > MAX_FRAME_BYTES)
|
|
189
|
+
throw new Error("Admission frame too large");
|
|
190
|
+
buffered = Buffer.concat([buffered, chunk.subarray(offset, end)]);
|
|
191
|
+
if (newline < 0) break;
|
|
192
|
+
receive(client, buffered);
|
|
193
|
+
buffered = Buffer.alloc(0);
|
|
194
|
+
offset = end + 1;
|
|
195
|
+
}
|
|
196
|
+
} catch {
|
|
197
|
+
socket.destroy();
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
server.on("error", (error) => {
|
|
203
|
+
process.exitCode = "code" in error && error.code === "EADDRINUSE" ? 0 : 1;
|
|
204
|
+
stop();
|
|
205
|
+
});
|
|
206
|
+
server.on("close", () => {
|
|
207
|
+
clearTimeout(idle);
|
|
208
|
+
process.removeListener("SIGTERM", stop);
|
|
209
|
+
process.removeListener("SIGINT", stop);
|
|
210
|
+
});
|
|
211
|
+
process.on("SIGTERM", stop);
|
|
212
|
+
process.on("SIGINT", stop);
|
|
213
|
+
try {
|
|
214
|
+
server.listen(socketPath, () => {
|
|
215
|
+
started();
|
|
216
|
+
armIdle(5000);
|
|
217
|
+
});
|
|
218
|
+
} catch {
|
|
219
|
+
process.exitCode = 1;
|
|
220
|
+
stop();
|
|
221
|
+
}
|
|
222
|
+
return server;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (
|
|
226
|
+
process.argv[1] &&
|
|
227
|
+
import.meta.url === pathToFileURL(process.argv[1]).href
|
|
228
|
+
) {
|
|
229
|
+
try {
|
|
230
|
+
const { endpoint, lease } = await readAdmissionStart();
|
|
231
|
+
startAdmissionBroker(endpoint, () => releaseAdmissionStart(lease));
|
|
232
|
+
} catch {
|
|
233
|
+
process.exitCode = 1;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
link,
|
|
5
|
+
lstat,
|
|
6
|
+
mkdir,
|
|
7
|
+
readFile,
|
|
8
|
+
realpath,
|
|
9
|
+
unlink,
|
|
10
|
+
writeFile,
|
|
11
|
+
} from "node:fs/promises";
|
|
12
|
+
import { createConnection, type Socket } from "node:net";
|
|
13
|
+
import { userInfo } from "node:os";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { lockStartup, pause } from "./admission-startup.js";
|
|
17
|
+
|
|
18
|
+
const runtimeDirectory = () =>
|
|
19
|
+
join(userInfo().homedir, ".cache", "pi-shepherdr", "admission");
|
|
20
|
+
|
|
21
|
+
async function privateDirectory(directory: string): Promise<void> {
|
|
22
|
+
await mkdir(directory, { mode: 0o700, recursive: true });
|
|
23
|
+
const metadata = await lstat(directory);
|
|
24
|
+
if (
|
|
25
|
+
!metadata.isDirectory() ||
|
|
26
|
+
metadata.isSymbolicLink() ||
|
|
27
|
+
(process.getuid && metadata.uid !== process.getuid()) ||
|
|
28
|
+
(process.platform !== "win32" && (metadata.mode & 0o077) !== 0)
|
|
29
|
+
)
|
|
30
|
+
throw new Error(
|
|
31
|
+
"Private agent runtime directory is not secure; check its ownership and permissions",
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A private, stable name; kernel-owned endpoints need no stale lock reclamation. */
|
|
36
|
+
export async function admissionEndpoint(
|
|
37
|
+
core: string,
|
|
38
|
+
destination: string,
|
|
39
|
+
): Promise<string> {
|
|
40
|
+
const directory = runtimeDirectory();
|
|
41
|
+
await privateDirectory(directory);
|
|
42
|
+
const canonical =
|
|
43
|
+
process.platform === "win32" ? core.toLowerCase() : await realpath(core);
|
|
44
|
+
const key = createHash("sha256")
|
|
45
|
+
.update(JSON.stringify([canonical, destination]))
|
|
46
|
+
.digest("hex");
|
|
47
|
+
const path = join(directory, key);
|
|
48
|
+
const candidate = `${path}.${randomBytes(8).toString("hex")}`;
|
|
49
|
+
await writeFile(candidate, randomBytes(24).toString("hex"), {
|
|
50
|
+
flag: "wx",
|
|
51
|
+
mode: 0o600,
|
|
52
|
+
});
|
|
53
|
+
try {
|
|
54
|
+
// Publish complete contents atomically, including concurrent first clients.
|
|
55
|
+
await link(candidate, path);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
|
|
58
|
+
throw error;
|
|
59
|
+
} finally {
|
|
60
|
+
await unlink(candidate);
|
|
61
|
+
}
|
|
62
|
+
const token = await readFile(path, "utf8");
|
|
63
|
+
if (!/^[a-f0-9]{48}$/.test(token))
|
|
64
|
+
throw new Error(
|
|
65
|
+
"Agent runtime endpoint is invalid; remove the invalid runtime file and reconnect",
|
|
66
|
+
);
|
|
67
|
+
if (process.platform === "linux") return `\0pi-shepherdr-${token}`;
|
|
68
|
+
if (process.platform === "win32") return `\\\\.\\pipe\\pi-shepherdr-${token}`;
|
|
69
|
+
// Core already needs a short Unix socket directory. Do not put a second
|
|
70
|
+
// socket beneath an arbitrarily long home directory on Darwin/BSD.
|
|
71
|
+
const sockets = join(
|
|
72
|
+
dirname(canonical),
|
|
73
|
+
`pi-sh-${process.getuid?.() ?? "user"}`,
|
|
74
|
+
);
|
|
75
|
+
const endpoint = join(sockets, `${token.slice(0, 24)}.sock`);
|
|
76
|
+
if (Buffer.byteLength(endpoint) > 100)
|
|
77
|
+
throw new Error(
|
|
78
|
+
"Core runtime path is too long for agent operations; restart Core with a shorter runtime directory",
|
|
79
|
+
);
|
|
80
|
+
await privateDirectory(sockets);
|
|
81
|
+
return endpoint;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function connect(path: string, signal: AbortSignal): Promise<Socket> {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const socket = createConnection({ path });
|
|
87
|
+
const abort = () => failed(signal.reason);
|
|
88
|
+
const failed = (error: Error) => {
|
|
89
|
+
signal.removeEventListener("abort", abort);
|
|
90
|
+
socket.destroy();
|
|
91
|
+
reject(error);
|
|
92
|
+
};
|
|
93
|
+
socket.once("error", failed);
|
|
94
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
95
|
+
if (signal.aborted) abort();
|
|
96
|
+
socket.once("connect", () => {
|
|
97
|
+
signal.removeEventListener("abort", abort);
|
|
98
|
+
socket.removeListener("error", failed);
|
|
99
|
+
resolve(socket);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Bind elects the owner; losing starters exit. Never retry an accepted operation. */
|
|
105
|
+
export async function connectAdmission(
|
|
106
|
+
path: string,
|
|
107
|
+
signal: AbortSignal,
|
|
108
|
+
): Promise<Socket> {
|
|
109
|
+
const attempt = async () => {
|
|
110
|
+
try {
|
|
111
|
+
return await connect(path, signal);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (
|
|
114
|
+
!(
|
|
115
|
+
error instanceof Error &&
|
|
116
|
+
"code" in error &&
|
|
117
|
+
["ENOENT", "ECONNREFUSED"].includes(String(error.code))
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
throw error;
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const existing = await attempt();
|
|
125
|
+
if (existing) return existing;
|
|
126
|
+
const filesystem =
|
|
127
|
+
!path.startsWith("\0") && !path.startsWith("\\\\.\\pipe\\");
|
|
128
|
+
const lockPath = filesystem
|
|
129
|
+
? path
|
|
130
|
+
: join(runtimeDirectory(), createHash("sha256").update(path).digest("hex"));
|
|
131
|
+
const lock = await lockStartup(lockPath, signal);
|
|
132
|
+
let transferred = false;
|
|
133
|
+
try {
|
|
134
|
+
const owner = await attempt();
|
|
135
|
+
if (owner) return owner;
|
|
136
|
+
if (filesystem) {
|
|
137
|
+
// All filesystem binders hold this lock. A refused socket is stale,
|
|
138
|
+
// but cannot be unlinked outside election without racing a new owner.
|
|
139
|
+
await unlink(path).catch((error: unknown) => {
|
|
140
|
+
if (
|
|
141
|
+
!(
|
|
142
|
+
error instanceof Error &&
|
|
143
|
+
"code" in error &&
|
|
144
|
+
error.code === "ENOENT"
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
throw error;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
signal.throwIfAborted();
|
|
151
|
+
const child = spawn(
|
|
152
|
+
process.execPath,
|
|
153
|
+
[
|
|
154
|
+
fileURLToPath(new URL("./admission-broker.mjs", import.meta.url)),
|
|
155
|
+
createHash("sha256").update(path).digest("hex"),
|
|
156
|
+
],
|
|
157
|
+
{
|
|
158
|
+
detached: true,
|
|
159
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
160
|
+
windowsHide: true,
|
|
161
|
+
},
|
|
162
|
+
);
|
|
163
|
+
// Startup failure is reported through the bounded connection attempt.
|
|
164
|
+
child.on("error", () => {});
|
|
165
|
+
child.unref();
|
|
166
|
+
if (!child.pid) throw new Error("Agent runtime did not start");
|
|
167
|
+
const lease = await lock.handoff(child.pid);
|
|
168
|
+
transferred = true;
|
|
169
|
+
child.stdin.on("error", () => {});
|
|
170
|
+
child.stdin.end(JSON.stringify({ endpoint: path, lease }));
|
|
171
|
+
for (;;) {
|
|
172
|
+
signal.throwIfAborted();
|
|
173
|
+
const socket = await attempt();
|
|
174
|
+
if (socket) return socket;
|
|
175
|
+
await pause(signal);
|
|
176
|
+
}
|
|
177
|
+
} finally {
|
|
178
|
+
if (!transferred) await lock.release();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, rmdir, unlink } from "node:fs/promises";
|
|
3
|
+
|
|
4
|
+
/** @typedef {{path:string,marker:string}} StartupLease */
|
|
5
|
+
|
|
6
|
+
/** Startup travels through stdin, not argv: endpoint names stay private to the OS user.
|
|
7
|
+
* The parent atomically transfers its directory marker before allowing the child to bind.
|
|
8
|
+
* @returns {Promise<{endpoint:string, lease:StartupLease}>}
|
|
9
|
+
*/
|
|
10
|
+
export async function readAdmissionStart() {
|
|
11
|
+
const timer = setTimeout(
|
|
12
|
+
() => process.stdin.destroy(new Error("Startup expired")),
|
|
13
|
+
5000,
|
|
14
|
+
);
|
|
15
|
+
try {
|
|
16
|
+
let frame = "";
|
|
17
|
+
for await (const chunk of process.stdin) {
|
|
18
|
+
frame += chunk;
|
|
19
|
+
if (Buffer.byteLength(frame) > 8192)
|
|
20
|
+
throw new Error("Invalid startup frame");
|
|
21
|
+
}
|
|
22
|
+
const value = JSON.parse(frame);
|
|
23
|
+
if (
|
|
24
|
+
!value ||
|
|
25
|
+
typeof value.endpoint !== "string" ||
|
|
26
|
+
!value.endpoint ||
|
|
27
|
+
!value.lease ||
|
|
28
|
+
typeof value.lease.path !== "string" ||
|
|
29
|
+
typeof value.lease.marker !== "string" ||
|
|
30
|
+
!new RegExp(`^${process.pid}-[a-zA-Z0-9]+$`).test(value.lease.marker) ||
|
|
31
|
+
createHash("sha256").update(value.endpoint).digest("hex") !==
|
|
32
|
+
process.argv[2]
|
|
33
|
+
)
|
|
34
|
+
throw new Error("Invalid startup owner");
|
|
35
|
+
const marker = await lstat(`${value.lease.path}/${value.lease.marker}`);
|
|
36
|
+
if (!marker.isFile() || (process.getuid && marker.uid !== process.getuid()))
|
|
37
|
+
throw new Error("Startup ownership changed");
|
|
38
|
+
return value;
|
|
39
|
+
} finally {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param {StartupLease} lease */
|
|
45
|
+
export async function releaseAdmissionStart(lease) {
|
|
46
|
+
await unlink(`${lease.path}/${lease.marker}`).catch((error) => {
|
|
47
|
+
if (error.code !== "ENOENT") throw error;
|
|
48
|
+
});
|
|
49
|
+
await rmdir(lease.path).catch((error) => {
|
|
50
|
+
if (!["ENOENT", "ENOTEMPTY"].includes(error.code)) throw error;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import {
|
|
2
|
+
lstat,
|
|
3
|
+
mkdtemp,
|
|
4
|
+
readdir,
|
|
5
|
+
rename,
|
|
6
|
+
rmdir,
|
|
7
|
+
unlink,
|
|
8
|
+
writeFile,
|
|
9
|
+
} from "node:fs/promises";
|
|
10
|
+
|
|
11
|
+
const missing = (error: unknown) =>
|
|
12
|
+
error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
13
|
+
|
|
14
|
+
interface StartupLock {
|
|
15
|
+
handoff(pid: number): Promise<{ path: string; marker: string }>;
|
|
16
|
+
release(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function pause(signal: AbortSignal): Promise<void> {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const abort = () => {
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
reject(signal.reason);
|
|
24
|
+
};
|
|
25
|
+
const timer = setTimeout(() => {
|
|
26
|
+
signal.removeEventListener("abort", abort);
|
|
27
|
+
resolve();
|
|
28
|
+
}, 25);
|
|
29
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
30
|
+
if (signal.aborted) abort();
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Filesystem sockets need stale recovery; a populated directory is atomic election.
|
|
35
|
+
* Never rename a stale lock: another client might already have replaced it.
|
|
36
|
+
*/
|
|
37
|
+
export async function lockStartup(
|
|
38
|
+
path: string,
|
|
39
|
+
signal: AbortSignal,
|
|
40
|
+
): Promise<StartupLock> {
|
|
41
|
+
const lock = `${path}.starting`;
|
|
42
|
+
const candidate = await mkdtemp(`${lock}-${process.pid}-`);
|
|
43
|
+
const owner = `${process.pid}-${candidate.slice(candidate.lastIndexOf("-") + 1)}`;
|
|
44
|
+
await writeFile(`${candidate}/${owner}`, "", { mode: 0o600 });
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
signal.throwIfAborted();
|
|
48
|
+
try {
|
|
49
|
+
await rename(candidate, lock);
|
|
50
|
+
break;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (
|
|
53
|
+
!(
|
|
54
|
+
error instanceof Error &&
|
|
55
|
+
"code" in error &&
|
|
56
|
+
["ENOTEMPTY", "EEXIST"].includes(String(error.code))
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const entries = await readdir(lock);
|
|
63
|
+
const previous = entries.length === 1 ? entries[0] : undefined;
|
|
64
|
+
if (previous && /^[1-9][0-9]*-[a-zA-Z0-9]+$/.test(previous)) {
|
|
65
|
+
let dead = false;
|
|
66
|
+
try {
|
|
67
|
+
process.kill(Number(previous.split("-")[0]), 0);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (
|
|
70
|
+
error instanceof Error &&
|
|
71
|
+
"code" in error &&
|
|
72
|
+
error.code === "ESRCH"
|
|
73
|
+
)
|
|
74
|
+
dead = true;
|
|
75
|
+
}
|
|
76
|
+
if (dead) await unlink(`${lock}/${previous}`);
|
|
77
|
+
}
|
|
78
|
+
// A published lock is never empty. Recover a crash during removal,
|
|
79
|
+
// without removing a concurrently published populated replacement.
|
|
80
|
+
if (!entries.length && Date.now() - (await lstat(lock)).mtimeMs > 1000)
|
|
81
|
+
await rmdir(lock);
|
|
82
|
+
if (previous) {
|
|
83
|
+
try {
|
|
84
|
+
await rmdir(lock);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (
|
|
87
|
+
!(
|
|
88
|
+
error instanceof Error &&
|
|
89
|
+
"code" in error &&
|
|
90
|
+
["ENOTEMPTY", "ENOENT"].includes(String(error.code))
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (!missing(error)) throw error;
|
|
98
|
+
}
|
|
99
|
+
await pause(signal);
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await unlink(`${candidate}/${owner}`);
|
|
103
|
+
await rmdir(candidate);
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
async handoff(pid) {
|
|
108
|
+
const marker = `${pid}-${owner.slice(owner.indexOf("-") + 1)}`;
|
|
109
|
+
// The directory stays populated throughout transfer. A child must
|
|
110
|
+
// verify this marker before binding, even if its parent has exited.
|
|
111
|
+
await rename(`${lock}/${owner}`, `${lock}/${marker}`);
|
|
112
|
+
return { path: lock, marker };
|
|
113
|
+
},
|
|
114
|
+
async release() {
|
|
115
|
+
await unlink(`${lock}/${owner}`).catch((error: unknown) => {
|
|
116
|
+
if (!missing(error)) throw error;
|
|
117
|
+
});
|
|
118
|
+
await rmdir(lock).catch((error: unknown) => {
|
|
119
|
+
if (
|
|
120
|
+
!(
|
|
121
|
+
error instanceof Error &&
|
|
122
|
+
"code" in error &&
|
|
123
|
+
["ENOTEMPTY", "ENOENT"].includes(String(error.code))
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
throw error;
|
|
127
|
+
});
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|