@anhlp/alp-client 0.0.1-beta.4 → 0.0.1-beta.5
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 +16 -0
- package/dist/antigravity-probe.d.ts +1 -2
- package/dist/antigravity-probe.js +11 -5
- package/dist/command.js +3 -1
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +105 -11
- package/dist/index.d.ts +55 -4
- package/dist/index.js +153 -17
- package/dist/integration-lock.d.ts +3 -1
- package/dist/integration-lock.js +48 -28
- package/dist/mcp-probe.js +1 -1
- package/dist/portable.d.ts +2 -1
- package/dist/portable.js +4 -1
- package/dist/rpc/handshake.d.ts +6 -1
- package/dist/rpc/handshake.js +4 -2
- package/dist/rpc/registry.d.ts +10 -3
- package/dist/rpc/registry.js +97 -24
- package/dist/rpc/terminal-directory.d.ts +24 -0
- package/dist/rpc/terminal-directory.js +70 -0
- package/dist/service.d.ts +1 -1
- package/dist/service.js +3 -1
- package/dist/setup.js +6 -5
- package/dist/supervise.d.ts +1 -1
- package/dist/supervise.js +10 -6
- package/package.json +3 -3
- package/src/antigravity-probe.js +12 -5
- package/src/command.js +3 -1
- package/src/doctor.d.ts +1 -0
- package/src/doctor.js +106 -1
- package/src/index.js +198 -20
- package/src/integration-lock.js +44 -20
- package/src/mcp-probe.js +1 -1
- package/src/portable.js +3 -1
- package/src/rpc/handshake.js +7 -2
- package/src/rpc/registry.js +83 -20
- package/src/rpc/terminal-directory.js +61 -0
- package/src/service.js +5 -2
- package/src/setup.js +7 -5
- package/src/supervise.d.ts +1 -1
- package/src/supervise.js +10 -6
package/dist/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
// packages/client/src/index.js
|
|
2
|
-
import {
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
3
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
4
6
|
import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
|
|
5
7
|
import net from "node:net";
|
|
6
8
|
import os from "node:os";
|
|
7
9
|
import path from "node:path";
|
|
8
10
|
import { scrubText } from "@anhlp/alp-core/log";
|
|
11
|
+
import { EXECUTABLE_MARKER, entryCommand, executablePath, isExecutableName, isScript } from "@anhlp/alp-core/packaged";
|
|
9
12
|
import { createSocketTransport } from "./ipc.js";
|
|
10
13
|
import { AlpRpcClient } from "./rpc/client.js";
|
|
11
14
|
import { hello } from "./rpc/handshake.js";
|
|
@@ -76,23 +79,65 @@ async function assertPrivateSocket(socketPath) {
|
|
|
76
79
|
return info;
|
|
77
80
|
}
|
|
78
81
|
var isFile = (file) => stat(file).then((info) => info.isFile(), () => false);
|
|
79
|
-
|
|
82
|
+
async function isAlpExecutable(file) {
|
|
83
|
+
if (isScript(file) || !isExecutableName(file) || !await isFile(file)) return false;
|
|
84
|
+
const handle = await open(file, "r").catch(() => void 0);
|
|
85
|
+
if (!handle) return false;
|
|
86
|
+
try {
|
|
87
|
+
const { buffer, bytesRead } = await handle.read(Buffer.alloc(4), 0, 4, 0);
|
|
88
|
+
if (bytesRead < 4) return false;
|
|
89
|
+
const magic = buffer.readUInt32BE(0);
|
|
90
|
+
const native = buffer.toString("latin1") === "\x7FELF" || buffer.subarray(0, 2).toString("latin1") === "MZ" || [4277009102, 4277009103, 3472551422, 3489328638, 3405691582].includes(magic);
|
|
91
|
+
if (!native) return false;
|
|
92
|
+
const marker = Buffer.from(EXECUTABLE_MARKER, "latin1");
|
|
93
|
+
const chunk = Buffer.alloc(1 << 20);
|
|
94
|
+
let tail2 = Buffer.alloc(0);
|
|
95
|
+
for (let position = 0; ; ) {
|
|
96
|
+
const { bytesRead: read } = await handle.read(chunk, 0, chunk.length, position);
|
|
97
|
+
if (!read) return false;
|
|
98
|
+
const window = Buffer.concat([tail2, chunk.subarray(0, read)]);
|
|
99
|
+
if (window.includes(marker)) return true;
|
|
100
|
+
tail2 = window.subarray(Math.max(0, window.length - marker.length + 1));
|
|
101
|
+
position += read;
|
|
102
|
+
}
|
|
103
|
+
} finally {
|
|
104
|
+
await handle.close();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
var BIN_DIRECTORIES = [path.join(os.homedir(), ".alp", "bin"), path.join(os.homedir(), ".npm-global", "bin"), path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"];
|
|
80
108
|
var CLI_PACKAGES = ["@anhlp/alp", "@anhlp/alp-cli"];
|
|
109
|
+
async function npmWrapperExecutable(launcher, platform = process.platform, arch = process.arch) {
|
|
110
|
+
if (path.basename(launcher) !== "alp.js") return void 0;
|
|
111
|
+
const root = path.resolve(path.dirname(launcher), "..");
|
|
112
|
+
const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
|
|
113
|
+
if (name !== "@anhlp/alp") return void 0;
|
|
114
|
+
const id = `alp-${platform}-${arch}`;
|
|
115
|
+
const file = path.join("bin", platform === "win32" ? "alp.exe" : "alp");
|
|
116
|
+
for (const candidate of [path.join(root, "node_modules", "@anhlp", id, file), path.join(root, "..", id, file)]) {
|
|
117
|
+
if (await isAlpExecutable(candidate)) return candidate;
|
|
118
|
+
}
|
|
119
|
+
return void 0;
|
|
120
|
+
}
|
|
81
121
|
async function findDaemonEntry({ home = alpHome(), env = process.env, candidates = (
|
|
82
122
|
/** @type {Array<string | undefined>} */
|
|
83
123
|
[]
|
|
84
124
|
) } = {}) {
|
|
85
125
|
for (const candidate of candidates) if (candidate && await isFile(candidate)) return candidate;
|
|
126
|
+
const own = executablePath();
|
|
127
|
+
if (own) return own;
|
|
86
128
|
try {
|
|
87
129
|
const { entry } = JSON.parse(await readFile(daemonPaths(home).install, "utf8"));
|
|
88
130
|
if (typeof entry === "string" && await isFile(entry)) return entry;
|
|
89
131
|
} catch {
|
|
90
132
|
}
|
|
91
133
|
for (const directory of [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...BIN_DIRECTORIES]) {
|
|
92
|
-
const cli = await realpath(path.join(directory, "alp")).catch(() => void 0);
|
|
134
|
+
const cli = await realpath(path.join(directory, process.platform === "win32" ? "alp.exe" : "alp")).catch(() => void 0);
|
|
135
|
+
if (cli && await isAlpExecutable(cli)) return cli;
|
|
136
|
+
const npmExecutable = cli && await npmWrapperExecutable(cli);
|
|
137
|
+
if (npmExecutable) return npmExecutable;
|
|
93
138
|
if (!cli || path.basename(cli) !== "cli.js") continue;
|
|
94
139
|
const root = path.resolve(path.dirname(cli), "..");
|
|
95
|
-
const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text).
|
|
140
|
+
const name = await readFile(path.join(root, "package.json"), "utf8").then((text) => JSON.parse(text)?.name).catch(() => void 0);
|
|
96
141
|
const entry = path.join(root, "dist", "alpd.js");
|
|
97
142
|
if (CLI_PACKAGES.includes(name) && await isFile(entry)) return entry;
|
|
98
143
|
}
|
|
@@ -102,9 +147,48 @@ function assertIntegrationName(name) {
|
|
|
102
147
|
if (typeof name !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new TypeError(`Invalid integration name: ${JSON.stringify(name)}`);
|
|
103
148
|
return name;
|
|
104
149
|
}
|
|
150
|
+
var cachedBootId = null;
|
|
151
|
+
function bootId() {
|
|
152
|
+
if (cachedBootId !== null) return cachedBootId;
|
|
153
|
+
try {
|
|
154
|
+
if (process.platform === "linux") {
|
|
155
|
+
const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
156
|
+
if (id.length > 0) {
|
|
157
|
+
cachedBootId = id;
|
|
158
|
+
return cachedBootId;
|
|
159
|
+
}
|
|
160
|
+
} else if (process.platform === "darwin") {
|
|
161
|
+
const id = execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
|
|
162
|
+
encoding: "utf8",
|
|
163
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
164
|
+
timeout: 2e3
|
|
165
|
+
}).trim();
|
|
166
|
+
if (id.length > 0) {
|
|
167
|
+
cachedBootId = id;
|
|
168
|
+
return cachedBootId;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} catch {
|
|
172
|
+
}
|
|
173
|
+
cachedBootId = void 0;
|
|
174
|
+
return cachedBootId;
|
|
175
|
+
}
|
|
176
|
+
function _setBootIdForTest(id = null) {
|
|
177
|
+
cachedBootId = id;
|
|
178
|
+
}
|
|
105
179
|
function bootTime() {
|
|
106
180
|
return Math.round((Date.now() - os.uptime() * 1e3) / 1e3);
|
|
107
181
|
}
|
|
182
|
+
function isSameBoot(lock, { bootId: curBootId = bootId(), bootTime: curBootTime = bootTime() } = {}) {
|
|
183
|
+
if (!lock) return false;
|
|
184
|
+
if (typeof lock.bootId === "string" && lock.bootId.length > 0 && typeof curBootId === "string" && curBootId.length > 0) {
|
|
185
|
+
return lock.bootId === curBootId;
|
|
186
|
+
}
|
|
187
|
+
if (typeof lock.bootTime === "number" && Number.isFinite(lock.bootTime) && Number.isFinite(curBootTime)) {
|
|
188
|
+
return Math.abs(lock.bootTime - curBootTime) <= 30;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
108
192
|
async function readLock(home) {
|
|
109
193
|
try {
|
|
110
194
|
return JSON.parse(await readFile(daemonPaths(home).lock, "utf8"));
|
|
@@ -114,7 +198,7 @@ async function readLock(home) {
|
|
|
114
198
|
}
|
|
115
199
|
}
|
|
116
200
|
function lockAlive(lock) {
|
|
117
|
-
if (!lock || !Number.isSafeInteger(lock.pid) ||
|
|
201
|
+
if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
|
|
118
202
|
try {
|
|
119
203
|
process.kill(lock.pid, 0);
|
|
120
204
|
return true;
|
|
@@ -124,7 +208,17 @@ function lockAlive(lock) {
|
|
|
124
208
|
}
|
|
125
209
|
async function acquireDaemonLock(home, contents) {
|
|
126
210
|
const file = daemonPaths(home).lock;
|
|
127
|
-
const
|
|
211
|
+
const currentBootId = bootId();
|
|
212
|
+
const lock = {
|
|
213
|
+
pid: process.pid,
|
|
214
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
215
|
+
startedUptime: Math.floor(os.uptime()),
|
|
216
|
+
bootTime: bootTime(),
|
|
217
|
+
...currentBootId ? { bootId: currentBootId } : {},
|
|
218
|
+
uid: process.getuid?.() ?? -1,
|
|
219
|
+
ready: false,
|
|
220
|
+
...contents
|
|
221
|
+
};
|
|
128
222
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
129
223
|
try {
|
|
130
224
|
const handle = await open(file, "wx", 384);
|
|
@@ -150,6 +244,12 @@ async function releaseDaemonLock(home) {
|
|
|
150
244
|
var AlpClient = class extends AlpRpcClient {
|
|
151
245
|
/** Host features captured by connect's handshake. @type {readonly string[]} */
|
|
152
246
|
capabilities = [];
|
|
247
|
+
/** Limits captured by connect's handshake. @type {import('@anhlp/alp-protocol').AttachmentLimits | undefined} */
|
|
248
|
+
attachmentLimits;
|
|
249
|
+
/** @type {{ readonly maxCount: number; readonly maxBytes: number; readonly maxTotalBytes: number } | undefined} */
|
|
250
|
+
promptImageLimits;
|
|
251
|
+
/** @type {import('@anhlp/alp-protocol').TerminalLimits | undefined} */
|
|
252
|
+
terminalLimits;
|
|
153
253
|
/**
|
|
154
254
|
* @param {import('node:net').Socket} socket a connected or connecting socket; the client owns it
|
|
155
255
|
* @param {import('./rpc/client.js').AlpRpcClientOptions & import('./ipc.js').SocketTransportOptions} [options]
|
|
@@ -178,8 +278,17 @@ async function connectSocket(socketPath, options) {
|
|
|
178
278
|
async function connect(socketPath, client = { name: "alp", version: "0" }, options = {}) {
|
|
179
279
|
const connection = new AlpClient(await openSocket(socketPath), options);
|
|
180
280
|
try {
|
|
181
|
-
const greeting = await hello(connection, client);
|
|
281
|
+
const greeting = await hello(connection, client, void 0, { agent: typeof process.env.ALP_AGENT_SESSION === "string" && process.env.ALP_AGENT_SESSION !== "" });
|
|
182
282
|
connection.capabilities = Object.freeze(Array.isArray(greeting.capabilities) ? greeting.capabilities.filter((value) => typeof value === "string") : []);
|
|
283
|
+
if (greeting.attachmentLimits && typeof greeting.attachmentLimits === "object") {
|
|
284
|
+
connection.attachmentLimits = Object.freeze({ ...greeting.attachmentLimits });
|
|
285
|
+
}
|
|
286
|
+
if (greeting.promptImageLimits && typeof greeting.promptImageLimits === "object") {
|
|
287
|
+
connection.promptImageLimits = Object.freeze({ ...greeting.promptImageLimits });
|
|
288
|
+
}
|
|
289
|
+
if (greeting.terminalLimits && typeof greeting.terminalLimits === "object") {
|
|
290
|
+
connection.terminalLimits = Object.freeze({ ...greeting.terminalLimits });
|
|
291
|
+
}
|
|
183
292
|
} catch (error) {
|
|
184
293
|
connection.close();
|
|
185
294
|
throw error;
|
|
@@ -219,7 +328,11 @@ async function lifecycleOwners(home) {
|
|
|
219
328
|
async function readDaemonLifecycle(home) {
|
|
220
329
|
return (await lifecycleOwners(home)).find((owner) => lockAlive(owner));
|
|
221
330
|
}
|
|
222
|
-
async function withDaemonLifecycle(home, action, run, { joinStart = false
|
|
331
|
+
async function withDaemonLifecycle(home, action, run, { joinStart = false, signal = (
|
|
332
|
+
/** @type {AbortSignal | undefined} */
|
|
333
|
+
void 0
|
|
334
|
+
) } = {}) {
|
|
335
|
+
signal?.throwIfAborted();
|
|
223
336
|
try {
|
|
224
337
|
await assertPrivateDirectory(home, { create: true });
|
|
225
338
|
} catch (cause) {
|
|
@@ -228,10 +341,17 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
|
|
|
228
341
|
const state = path.join(home, "state");
|
|
229
342
|
await assertPrivateDirectory(state, { create: true });
|
|
230
343
|
const directory = path.join(state, "alpd.starting");
|
|
344
|
+
const currentBootId = bootId();
|
|
231
345
|
const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
|
|
232
346
|
const candidate = path.join(state, `alpd.starting-${token}`);
|
|
233
347
|
await mkdir(candidate, { mode: 448 });
|
|
234
|
-
await writeFile(path.join(candidate, token), JSON.stringify({
|
|
348
|
+
await writeFile(path.join(candidate, token), JSON.stringify({
|
|
349
|
+
pid: process.pid,
|
|
350
|
+
bootTime: bootTime(),
|
|
351
|
+
...currentBootId ? { bootId: currentBootId } : {},
|
|
352
|
+
startedUptime: Math.floor(os.uptime()),
|
|
353
|
+
action
|
|
354
|
+
}), { mode: 384 });
|
|
235
355
|
try {
|
|
236
356
|
let joined = false;
|
|
237
357
|
if (joinStart) {
|
|
@@ -246,6 +366,7 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
|
|
|
246
366
|
}
|
|
247
367
|
}
|
|
248
368
|
while (!joined) {
|
|
369
|
+
signal?.throwIfAborted();
|
|
249
370
|
try {
|
|
250
371
|
await rename(candidate, directory);
|
|
251
372
|
break;
|
|
@@ -259,10 +380,11 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
|
|
|
259
380
|
await rmdir(directory).catch((error2) => {
|
|
260
381
|
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error2.code)) throw error2;
|
|
261
382
|
});
|
|
262
|
-
await
|
|
383
|
+
await delay(25, void 0, { signal });
|
|
263
384
|
}
|
|
264
385
|
}
|
|
265
386
|
try {
|
|
387
|
+
signal?.throwIfAborted();
|
|
266
388
|
return await run();
|
|
267
389
|
} finally {
|
|
268
390
|
await unlink(path.join(directory, token));
|
|
@@ -282,8 +404,12 @@ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}
|
|
|
282
404
|
async function ensureDaemon({ home = alpHome(), entry = (
|
|
283
405
|
/** @type {string | undefined} */
|
|
284
406
|
void 0
|
|
285
|
-
), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false
|
|
286
|
-
|
|
407
|
+
), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false, signal = (
|
|
408
|
+
/** @type {AbortSignal | undefined} */
|
|
409
|
+
void 0
|
|
410
|
+
) } = {}) {
|
|
411
|
+
signal?.throwIfAborted();
|
|
412
|
+
if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true, signal }), { signal });
|
|
287
413
|
const ready = async () => {
|
|
288
414
|
const lock = await readLock(home);
|
|
289
415
|
return lockAlive(lock) && lock.ready ? lock.socket : void 0;
|
|
@@ -295,8 +421,10 @@ async function ensureDaemon({ home = alpHome(), entry = (
|
|
|
295
421
|
if (!lockAlive(held)) {
|
|
296
422
|
entry ??= await findDaemonEntry({ home, env });
|
|
297
423
|
if (!entry) throw new Error("ALP daemon is not running and alpd.js was not found. Install the ALP CLI and run `alp daemon start`, or set ALP_DAEMON_ENTRY to alpd.js");
|
|
424
|
+
signal?.throwIfAborted();
|
|
298
425
|
await new Promise((resolve, reject) => {
|
|
299
|
-
const
|
|
426
|
+
const launch = entryCommand(entry, "daemon", ["--detach", `--startup-timeout=${timeoutMs}`], execPath);
|
|
427
|
+
const launcher = spawn(launch.command, launch.args, {
|
|
300
428
|
env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
|
|
301
429
|
stdio: ["ignore", "ignore", "pipe"],
|
|
302
430
|
windowsHide: true
|
|
@@ -311,6 +439,7 @@ async function ensureDaemon({ home = alpHome(), entry = (
|
|
|
311
439
|
}
|
|
312
440
|
const deadline = Date.now() + timeoutMs;
|
|
313
441
|
while (Date.now() < deadline) {
|
|
442
|
+
signal?.throwIfAborted();
|
|
314
443
|
const socket = await ready();
|
|
315
444
|
if (socket) return socket;
|
|
316
445
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
@@ -398,14 +527,13 @@ async function discoverIntegration(name = "web", options = {}) {
|
|
|
398
527
|
return void 0;
|
|
399
528
|
}
|
|
400
529
|
function integrationAlive(lock) {
|
|
401
|
-
if (!lock || !Number.isSafeInteger(lock.pid)) return false;
|
|
530
|
+
if (!lock || !Number.isSafeInteger(lock.pid) || !isSameBoot(lock)) return false;
|
|
402
531
|
try {
|
|
403
532
|
process.kill(lock.pid, 0);
|
|
533
|
+
return true;
|
|
404
534
|
} catch (error) {
|
|
405
535
|
return error?.code === "EPERM";
|
|
406
536
|
}
|
|
407
|
-
if (typeof lock.bootTime === "number" && Math.abs(lock.bootTime - bootTime()) > 30) return false;
|
|
408
|
-
return true;
|
|
409
537
|
}
|
|
410
538
|
function integrationText(name, home) {
|
|
411
539
|
const logs = path.join(home, "logs", "integrations");
|
|
@@ -471,6 +599,7 @@ async function startIntegration(nameOrOptions = "web") {
|
|
|
471
599
|
const info = await readWeb();
|
|
472
600
|
if (info && info.pid === lock2.pid) return lock2;
|
|
473
601
|
}
|
|
602
|
+
if (name === "web" && webStartupFailed()) throw new Error(`${text.what}${started} failed to start; see ${text.log}`);
|
|
474
603
|
await sleep(100);
|
|
475
604
|
}
|
|
476
605
|
const lock = await readLock2();
|
|
@@ -478,6 +607,7 @@ async function startIntegration(nameOrOptions = "web") {
|
|
|
478
607
|
if (!lock) throw new Error(explicit ? `${text.what}${started} did not start; see ${text.log}` : text.missing);
|
|
479
608
|
throw new Error(`${text.what}${started} did not publish a ${name}.json matching its lock; see ${text.log}`);
|
|
480
609
|
}
|
|
610
|
+
let webStartupFailed = () => false;
|
|
481
611
|
const existing = await readLock2();
|
|
482
612
|
if (existing && integrationAlive(existing)) {
|
|
483
613
|
return waitForReady();
|
|
@@ -485,7 +615,8 @@ async function startIntegration(nameOrOptions = "web") {
|
|
|
485
615
|
const entry = explicit ?? await discoverIntegration(name, { home });
|
|
486
616
|
if (!entry) throw new Error(text.missing);
|
|
487
617
|
const { spawn: spawn2 } = await import("node:child_process");
|
|
488
|
-
const
|
|
618
|
+
const launch = name === "web" ? entryCommand(entry, "web", ["--service", ...args]) : entryCommand(entry, "web", ["--service", ...args], void 0, { scriptOnly: true });
|
|
619
|
+
const child = spawn2(launch.command, launch.args, { stdio: "ignore", detached: true, env: { ...process.env, ALP_HOME: home } });
|
|
489
620
|
let spawnError = null;
|
|
490
621
|
child.on("error", (error) => {
|
|
491
622
|
spawnError = error;
|
|
@@ -495,6 +626,7 @@ async function startIntegration(nameOrOptions = "web") {
|
|
|
495
626
|
if (code !== 0 && code !== null) exited = true;
|
|
496
627
|
});
|
|
497
628
|
child.unref();
|
|
629
|
+
webStartupFailed = () => exited;
|
|
498
630
|
if (spawnError) throw spawnError;
|
|
499
631
|
await sleep(150);
|
|
500
632
|
if (spawnError) throw spawnError;
|
|
@@ -507,11 +639,13 @@ export {
|
|
|
507
639
|
CLOSE_CODE,
|
|
508
640
|
MAX_FRAME,
|
|
509
641
|
PROTOCOL_VERSION,
|
|
642
|
+
_setBootIdForTest,
|
|
510
643
|
acquireDaemonLock,
|
|
511
644
|
alpHome,
|
|
512
645
|
assertIntegrationName,
|
|
513
646
|
assertPrivateDirectory,
|
|
514
647
|
assertPrivateSocket,
|
|
648
|
+
bootId,
|
|
515
649
|
bootTime,
|
|
516
650
|
connect,
|
|
517
651
|
connectSocket,
|
|
@@ -523,6 +657,8 @@ export {
|
|
|
523
657
|
encodeFrame,
|
|
524
658
|
ensureDaemon,
|
|
525
659
|
findDaemonEntry,
|
|
660
|
+
integrationAlive,
|
|
661
|
+
isSameBoot,
|
|
526
662
|
lockAlive,
|
|
527
663
|
readDaemonLifecycle,
|
|
528
664
|
readLock,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @typedef {{ pid: number, bootTime: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
|
|
2
|
+
* @typedef {{ pid: number, bootTime: number, bootId?: string, startedUptime?: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
|
|
3
3
|
* @typedef {{
|
|
4
4
|
* acquire(): Promise<{ acquired: boolean, lock: IntegrationLockRecord }>,
|
|
5
5
|
* setReady(ready: boolean): Promise<boolean>,
|
|
@@ -20,6 +20,8 @@ export function createIntegrationLock(home: string, name: string): IntegrationLo
|
|
|
20
20
|
export type IntegrationLockRecord = {
|
|
21
21
|
pid: number;
|
|
22
22
|
bootTime: number;
|
|
23
|
+
bootId?: string;
|
|
24
|
+
startedUptime?: number;
|
|
23
25
|
startedAt: string;
|
|
24
26
|
ready: boolean;
|
|
25
27
|
lockVersion?: number;
|
package/dist/integration-lock.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// packages/client/src/integration-lock.js
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { mkdir, open,
|
|
3
|
+
import { mkdir, open, rmdir, unlink } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
5
|
-
import {
|
|
6
|
+
import { moveFile } from "@anhlp/alp-core/atomic";
|
|
7
|
+
import { assertIntegrationName, bootId, bootTime, isSameBoot } from "./index.js";
|
|
6
8
|
function createIntegrationLock(home, name) {
|
|
7
9
|
const file = path.join(home, "integrations", `${assertIntegrationName(name)}.lock`);
|
|
8
10
|
const guard = `${file}.reclaim`;
|
|
9
11
|
let phase = "new";
|
|
10
12
|
let owned;
|
|
13
|
+
let readyQueue = Promise.resolve();
|
|
11
14
|
const recovery = (reason) => new Error(`${reason}. Stop ALL integration processes using this ALP_HOME before manual lock-only recovery of ${file} and ${guard}; see docs/modular-monorepo.md`);
|
|
12
15
|
async function guarded(run) {
|
|
13
16
|
await mkdir(path.dirname(file), { recursive: true, mode: 448 });
|
|
@@ -76,7 +79,7 @@ function createIntegrationLock(home, name) {
|
|
|
76
79
|
}
|
|
77
80
|
}
|
|
78
81
|
function complete(value) {
|
|
79
|
-
return value && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.bootTime === "number" && Number.isFinite(value.bootTime) && value.bootTime > 0 && typeof value.startedAt === "string" && Number.isFinite(Date.parse(value.startedAt)) && typeof value.ready === "boolean" && (value.lockVersion === void 0 && value.owner === void 0 || value.lockVersion === 1 && typeof value.owner === "string" && /^[a-f0-9-]{36}$/.test(value.owner));
|
|
82
|
+
return value && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.bootTime === "number" && Number.isFinite(value.bootTime) && value.bootTime > 0 && (value.bootId === void 0 || typeof value.bootId === "string" && value.bootId.length > 0) && (value.startedUptime === void 0 || typeof value.startedUptime === "number" && Number.isFinite(value.startedUptime)) && typeof value.startedAt === "string" && Number.isFinite(Date.parse(value.startedAt)) && typeof value.ready === "boolean" && (value.lockVersion === void 0 && value.owner === void 0 || value.lockVersion === 1 && typeof value.owner === "string" && /^[a-f0-9-]{36}$/.test(value.owner));
|
|
80
83
|
}
|
|
81
84
|
function dead(value) {
|
|
82
85
|
try {
|
|
@@ -87,7 +90,7 @@ function createIntegrationLock(home, name) {
|
|
|
87
90
|
/** @type {any} */
|
|
88
91
|
error?.code !== "ESRCH"
|
|
89
92
|
) return false;
|
|
90
|
-
if (
|
|
93
|
+
if (!isSameBoot(value)) throw recovery("Integration owner boot context is uncertain");
|
|
91
94
|
return true;
|
|
92
95
|
}
|
|
93
96
|
}
|
|
@@ -109,7 +112,17 @@ function createIntegrationLock(home, name) {
|
|
|
109
112
|
}
|
|
110
113
|
await unlink(file);
|
|
111
114
|
}
|
|
112
|
-
const
|
|
115
|
+
const currentBootId = bootId();
|
|
116
|
+
const value = {
|
|
117
|
+
pid: process.pid,
|
|
118
|
+
bootTime: bootTime(),
|
|
119
|
+
...currentBootId ? { bootId: currentBootId } : {},
|
|
120
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
121
|
+
startedUptime: Math.floor(os.uptime()),
|
|
122
|
+
ready: false,
|
|
123
|
+
lockVersion: 1,
|
|
124
|
+
owner: randomUUID()
|
|
125
|
+
};
|
|
113
126
|
const handle = await open(file, "wx", 384);
|
|
114
127
|
let info;
|
|
115
128
|
try {
|
|
@@ -130,34 +143,41 @@ function createIntegrationLock(home, name) {
|
|
|
130
143
|
},
|
|
131
144
|
async setReady(ready) {
|
|
132
145
|
if (phase !== "owned") return false;
|
|
133
|
-
|
|
146
|
+
const execute = async () => {
|
|
134
147
|
if (phase !== "owned") return false;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
148
|
+
return guarded(async () => {
|
|
149
|
+
if (phase !== "owned") return false;
|
|
150
|
+
const current = await snapshot();
|
|
151
|
+
if (!current || !matches(current)) {
|
|
152
|
+
phase = "retired";
|
|
153
|
+
owned = void 0;
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
const value = { ...current.value, ready };
|
|
157
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
158
|
+
const handle = await open(tmp, "wx", 384);
|
|
159
|
+
let info;
|
|
146
160
|
try {
|
|
147
|
-
|
|
148
|
-
|
|
161
|
+
try {
|
|
162
|
+
await handle.writeFile(JSON.stringify(value));
|
|
163
|
+
info = await handle.stat();
|
|
164
|
+
} finally {
|
|
165
|
+
await handle.close();
|
|
166
|
+
}
|
|
167
|
+
await moveFile(tmp, file);
|
|
168
|
+
owned = { owner: value.owner, dev: info.dev, ino: info.ino };
|
|
169
|
+
return true;
|
|
149
170
|
} finally {
|
|
150
|
-
await
|
|
171
|
+
await unlink(tmp).catch((error) => {
|
|
172
|
+
if (error?.code !== "ENOENT") throw error;
|
|
173
|
+
});
|
|
151
174
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
await unlink(tmp).catch((error) => {
|
|
157
|
-
if (error?.code !== "ENOENT") throw error;
|
|
158
|
-
});
|
|
159
|
-
}
|
|
175
|
+
});
|
|
176
|
+
};
|
|
177
|
+
const chained = readyQueue.then(execute, execute);
|
|
178
|
+
readyQueue = chained.catch(() => {
|
|
160
179
|
});
|
|
180
|
+
return chained;
|
|
161
181
|
},
|
|
162
182
|
async release() {
|
|
163
183
|
if (phase !== "owned") return false;
|
package/dist/mcp-probe.js
CHANGED
|
@@ -25,7 +25,7 @@ async function probeMcp(server, { cwd, timeoutMs = 15e3 } = {}) {
|
|
|
25
25
|
function stdioSession(server, cwd, timeoutMs) {
|
|
26
26
|
const env = { ...process.env, ...server.env ?? {} };
|
|
27
27
|
const launch = launchCommand(server.command, server.args ?? [], env);
|
|
28
|
-
const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
28
|
+
const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env: launch.env ? { ...env, ...launch.env } : env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
29
29
|
const signal = (name) => {
|
|
30
30
|
try {
|
|
31
31
|
process.kill(-child.pid, name);
|
package/dist/portable.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { watchTerminals } from "./rpc/terminal-directory.js";
|
|
2
2
|
export type AlpTransport = import("./rpc/client.js").AlpTransport;
|
|
3
3
|
export type TransportClose = import("./rpc/client.js").TransportClose;
|
|
4
4
|
export type TransportState = import("./rpc/client.js").TransportState;
|
|
@@ -15,5 +15,6 @@ export { AlpRpcClient, DEFAULT_MAX_PENDING } from "./rpc/client.js";
|
|
|
15
15
|
export { AlpClientError, CLIENT_ERROR, isAlpClientError } from "./rpc/errors.js";
|
|
16
16
|
export { createLineDecoder, utf8Length } from "./rpc/framing.js";
|
|
17
17
|
export { MAX_TIMER_MS, timerDelay } from "./rpc/timers.js";
|
|
18
|
+
export { AGENT_CAPABILITY, hello } from "./rpc/handshake.js";
|
|
18
19
|
export { backoffDelay, createReconnectingClient, retryable } from "./rpc/reconnect.js";
|
|
19
20
|
export { attachments, base64Encode, conversation, sha256Hex, workspaceRegistry } from "./rpc/registry.js";
|
package/dist/portable.js
CHANGED
|
@@ -4,10 +4,12 @@ import { AlpRpcClient, DEFAULT_MAX_PENDING } from "./rpc/client.js";
|
|
|
4
4
|
import { AlpClientError, CLIENT_ERROR, isAlpClientError } from "./rpc/errors.js";
|
|
5
5
|
import { createLineDecoder, utf8Length } from "./rpc/framing.js";
|
|
6
6
|
import { MAX_TIMER_MS, timerDelay } from "./rpc/timers.js";
|
|
7
|
-
import { hello } from "./rpc/handshake.js";
|
|
7
|
+
import { AGENT_CAPABILITY, hello } from "./rpc/handshake.js";
|
|
8
8
|
import { backoffDelay, createReconnectingClient, retryable } from "./rpc/reconnect.js";
|
|
9
9
|
import { attachments, base64Encode, conversation, sha256Hex, workspaceRegistry } from "./rpc/registry.js";
|
|
10
|
+
import { watchTerminals } from "./rpc/terminal-directory.js";
|
|
10
11
|
export {
|
|
12
|
+
AGENT_CAPABILITY,
|
|
11
13
|
AlpClientError,
|
|
12
14
|
AlpRpcClient,
|
|
13
15
|
AlpRpcError,
|
|
@@ -29,5 +31,6 @@ export {
|
|
|
29
31
|
sha256Hex,
|
|
30
32
|
timerDelay,
|
|
31
33
|
utf8Length,
|
|
34
|
+
watchTerminals,
|
|
32
35
|
workspaceRegistry
|
|
33
36
|
};
|
package/dist/rpc/handshake.d.ts
CHANGED
|
@@ -6,13 +6,18 @@
|
|
|
6
6
|
* @param {{ request(method: string, params?: unknown, options?: import('./client.js').RequestOptions): Promise<any> }} client
|
|
7
7
|
* @param {ClientInfo} [info]
|
|
8
8
|
* @param {import('./client.js').RequestOptions} [options]
|
|
9
|
+
* @param {{ agent?: boolean }} [principal] `agent`: an ALP agent started this process (the Node entry reads ALP_AGENT_SESSION).
|
|
9
10
|
* @returns {Promise<{ protocolVersion: number } & Record<string, unknown>>}
|
|
10
11
|
*/
|
|
11
12
|
export function hello(client: {
|
|
12
13
|
request(method: string, params?: unknown, options?: import("./client.js").RequestOptions): Promise<any>;
|
|
13
|
-
}, info?: ClientInfo, options?: import("./client.js").RequestOptions
|
|
14
|
+
}, info?: ClientInfo, options?: import("./client.js").RequestOptions, { agent }?: {
|
|
15
|
+
agent?: boolean;
|
|
16
|
+
}): Promise<{
|
|
14
17
|
protocolVersion: number;
|
|
15
18
|
} & Record<string, unknown>>;
|
|
19
|
+
/** The daemon.hello capability a process an ALP agent started announces. */
|
|
20
|
+
export const AGENT_CAPABILITY: "principal.agent";
|
|
16
21
|
export type ClientInfo = {
|
|
17
22
|
name: string;
|
|
18
23
|
version: string;
|
package/dist/rpc/handshake.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// packages/client/src/rpc/handshake.js
|
|
2
2
|
import { PROTOCOL_VERSION } from "@anhlp/alp-protocol";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
var AGENT_CAPABILITY = "principal.agent";
|
|
4
|
+
function hello(client, info = { name: "alp", version: "0" }, options, { agent = false } = {}) {
|
|
5
|
+
return client.request("daemon.hello", { protocolVersion: PROTOCOL_VERSION, client: info, ...agent ? { capabilities: [AGENT_CAPABILITY] } : {} }, options);
|
|
5
6
|
}
|
|
6
7
|
export {
|
|
8
|
+
AGENT_CAPABILITY,
|
|
7
9
|
hello
|
|
8
10
|
};
|
package/dist/rpc/registry.d.ts
CHANGED
|
@@ -89,9 +89,11 @@ export function attachments(client: {
|
|
|
89
89
|
* Uploads `data` and commits it: begin (or resume, with the same requestId), chunks of at most
|
|
90
90
|
* the smaller of `maxChunkBytes` and what begin answered, commit with its SHA-256. A chunk
|
|
91
91
|
* refused `offset_mismatch` continues from the daemon's `received`. Returns the attachment.
|
|
92
|
-
*
|
|
92
|
+
* The returned promise exposes `.uploadId` once begun and `.abort(reason?: any)` to abort on alpd.
|
|
93
|
+
* @param {{ sessionId: string, name: string, mimeType: string, data: Uint8Array, requestId: string, sha256?: string, maxChunkBytes?: number, signal?: AbortSignal, onBegun?: (uploadId: string) => void, onProgress?: (received: number, size: number) => void }} options
|
|
94
|
+
* @returns {Promise<Map['attachment.commit']['result']['attachment']> & { readonly uploadId?: string, abort(reason?: any): Promise<void> }}
|
|
93
95
|
*/
|
|
94
|
-
upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, onProgress }: {
|
|
96
|
+
upload({ sessionId, name, mimeType, data, requestId, sha256, maxChunkBytes, signal, onBegun, onProgress }: {
|
|
95
97
|
sessionId: string;
|
|
96
98
|
name: string;
|
|
97
99
|
mimeType: string;
|
|
@@ -99,8 +101,13 @@ export function attachments(client: {
|
|
|
99
101
|
requestId: string;
|
|
100
102
|
sha256?: string;
|
|
101
103
|
maxChunkBytes?: number;
|
|
104
|
+
signal?: AbortSignal;
|
|
105
|
+
onBegun?: (uploadId: string) => void;
|
|
102
106
|
onProgress?: (received: number, size: number) => void;
|
|
103
|
-
}): Promise<import("@anhlp/alp-protocol").AttachmentInfo
|
|
107
|
+
}): Promise<import("@anhlp/alp-protocol").AttachmentInfo> & {
|
|
108
|
+
readonly uploadId?: string;
|
|
109
|
+
abort(reason?: any): Promise<void>;
|
|
110
|
+
};
|
|
104
111
|
};
|
|
105
112
|
/**
|
|
106
113
|
* Typed conversation methods (capabilities `session.fork` and `session.rewind`, docs/protocol/
|