@sys9/chord-cli 0.1.149-linux-arm64 → 0.1.149

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/bin/chord ADDED
@@ -0,0 +1,438 @@
1
+ #!/usr/bin/env node
2
+
3
+ "use strict";
4
+
5
+ const { spawn } = require("node:child_process");
6
+ const fs = require("node:fs");
7
+ const path = require("node:path");
8
+
9
+ const packageJSON = require("../package.json");
10
+ const {
11
+ resolvePackagedBinaryPath,
12
+ resolvePlatformPackageName,
13
+ } = require("../lib/platform");
14
+
15
+ function detectPackageManager() {
16
+ const userAgent = process.env.npm_config_user_agent || "";
17
+ if (/\bbun\//.test(userAgent)) {
18
+ return "bun";
19
+ }
20
+
21
+ const execPath = process.env.npm_execpath || "";
22
+ if (execPath.includes("bun")) {
23
+ return "bun";
24
+ }
25
+
26
+ if (
27
+ __dirname.includes(".bun/install/global") ||
28
+ __dirname.includes(".bun\\install\\global")
29
+ ) {
30
+ return "bun";
31
+ }
32
+
33
+ return "npm";
34
+ }
35
+
36
+ function resolveBinaryPath() {
37
+ const platformPackage = resolvePlatformPackageName(packageJSON.name);
38
+ try {
39
+ const packageJSONPath = require.resolve(platformPackage + "/package.json");
40
+ return {
41
+ binaryPath: resolvePackagedBinaryPath(path.dirname(packageJSONPath)),
42
+ platformPackage,
43
+ };
44
+ } catch {
45
+ return {
46
+ binaryPath: resolvePackagedBinaryPath(path.join(__dirname, "..")),
47
+ platformPackage,
48
+ };
49
+ }
50
+ }
51
+
52
+ const updateRequestedExitCode = 75;
53
+ const updateFDEnv = "CHORD_CLI_UPDATE_FD";
54
+ const updateAttemptEnv = "CHORD_CLI_UPDATE_ATTEMPT_ID";
55
+ const updateOutcomeEnv = "CHORD_CLI_UPDATE_OUTCOME";
56
+ const updateErrorEnv = "CHORD_CLI_UPDATE_ERROR";
57
+ const updateReadyFileEnv = "CHORD_CLI_UPDATE_READY_FILE";
58
+ const updateReadyTimeoutEnv = "CHORD_CLI_UPDATE_READY_TIMEOUT_MS";
59
+ const maxUpdateInstructionBytes = 4096;
60
+ const defaultUpdateReadyTimeoutMs = 60_000;
61
+ let child = null;
62
+ let receivedSignal = null;
63
+
64
+ const forwardSignal = (signal) => {
65
+ receivedSignal = signal;
66
+ if (!child || child.killed) {
67
+ return;
68
+ }
69
+ try {
70
+ child.kill(signal);
71
+ } catch {
72
+ // Ignore failures while the child is already exiting.
73
+ }
74
+ };
75
+
76
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((signal) => {
77
+ process.on(signal, () => forwardSignal(signal));
78
+ });
79
+
80
+ function runChild(command, args, options) {
81
+ return new Promise((resolve) => {
82
+ let updateInstruction = "";
83
+ let settled = false;
84
+ let childResult = null;
85
+ let updatePipeClosed = true;
86
+ let updateInstructionComplete = false;
87
+ const finish = (result) => {
88
+ if (settled) {
89
+ return;
90
+ }
91
+ settled = true;
92
+ child = null;
93
+ resolve(result);
94
+ };
95
+ const finishAfterUpdatePipe = () => {
96
+ if (childResult && (updatePipeClosed || updateInstructionComplete)) {
97
+ finish({ ...childResult, updateInstruction });
98
+ }
99
+ };
100
+ child = spawn(command, args, options);
101
+ if (child.stdio[3]) {
102
+ updatePipeClosed = false;
103
+ child.stdio[3].setEncoding("utf8");
104
+ child.stdio[3].on("data", (chunk) => {
105
+ if (updateInstruction.length <= maxUpdateInstructionBytes) {
106
+ updateInstruction += chunk;
107
+ }
108
+ updateInstructionComplete = updateInstruction.includes("\n");
109
+ finishAfterUpdatePipe();
110
+ });
111
+ child.stdio[3].on("end", () => {
112
+ updatePipeClosed = true;
113
+ finishAfterUpdatePipe();
114
+ });
115
+ }
116
+ child.on("error", (error) => {
117
+ finish({ code: 1, signal: null, updateInstruction: "", error });
118
+ });
119
+ child.on("exit", (code, signal) => {
120
+ childResult = { code: code ?? 1, signal, error: null };
121
+ // A daemon descendant may temporarily retain the update pipe. Once the
122
+ // direct child supplies the complete newline-delimited update instruction,
123
+ // waiting for every inherited file descriptor would keep replacement stuck
124
+ // for that descendant's lifetime.
125
+ if (signal || receivedSignal) {
126
+ finish({ code: code ?? 1, signal, updateInstruction, error: null });
127
+ return;
128
+ }
129
+ finishAfterUpdatePipe();
130
+ });
131
+ child.on("close", (code, signal) => {
132
+ childResult = { code: code ?? 1, signal, error: null };
133
+ finishAfterUpdatePipe();
134
+ });
135
+ });
136
+ }
137
+
138
+ function parseUpdateInstruction(raw) {
139
+ if (!raw || raw.length > maxUpdateInstructionBytes) {
140
+ return null;
141
+ }
142
+ try {
143
+ const instruction = JSON.parse(raw);
144
+ const version = instruction && instruction.cli_version;
145
+ if (typeof version !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) {
146
+ return null;
147
+ }
148
+ const attemptID = instruction.attempt_id;
149
+ const dataDir = instruction.data_dir;
150
+ const fromVersion = instruction.from_version;
151
+ const hostID = instruction.host_id;
152
+ if (
153
+ typeof attemptID !== "string" ||
154
+ !/^[A-Za-z0-9_-]{1,128}$/.test(attemptID) ||
155
+ typeof dataDir !== "string" ||
156
+ !path.isAbsolute(dataDir) ||
157
+ typeof fromVersion !== "string" ||
158
+ !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(fromVersion) ||
159
+ typeof hostID !== "string" ||
160
+ !hostID ||
161
+ hostID.length > 128
162
+ ) {
163
+ return null;
164
+ }
165
+ return { cliVersion: version, attemptID, dataDir, fromVersion, hostID };
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ function updateCommand(packageManager, cliVersion, daemonArgs) {
172
+ const packageSpec = packageJSON.name + "@" + cliVersion;
173
+ if (packageManager === "bun") {
174
+ return { command: "bunx", args: [packageSpec, ...daemonArgs] };
175
+ }
176
+ return { command: "npx", args: ["--yes", packageSpec, ...daemonArgs] };
177
+ }
178
+
179
+ function updateReadyTimeoutMs() {
180
+ const configured = Number(process.env[updateReadyTimeoutEnv]);
181
+ if (Number.isInteger(configured) && configured >= 100 && configured <= 300_000) {
182
+ return configured;
183
+ }
184
+ return defaultUpdateReadyTimeoutMs;
185
+ }
186
+
187
+ function monitorReadiness(readyFile, instruction, outcome) {
188
+ let timer = null;
189
+ let interval = null;
190
+ let settled = false;
191
+ let resolvePromise;
192
+ const finish = (result) => {
193
+ if (settled) {
194
+ return;
195
+ }
196
+ settled = true;
197
+ clearTimeout(timer);
198
+ clearInterval(interval);
199
+ resolvePromise(result);
200
+ };
201
+ const promise = new Promise((resolve) => {
202
+ resolvePromise = resolve;
203
+ const inspect = () => {
204
+ let record;
205
+ try {
206
+ record = JSON.parse(fs.readFileSync(readyFile, "utf8"));
207
+ } catch {
208
+ return;
209
+ }
210
+ if (
211
+ record.attempt_id === instruction.attemptID &&
212
+ record.version === (outcome === "target" ? instruction.cliVersion : instruction.fromVersion) &&
213
+ record.outcome === outcome &&
214
+ record.host_id === instruction.hostID
215
+ ) {
216
+ finish({ kind: "ready" });
217
+ }
218
+ };
219
+ interval = setInterval(inspect, 25);
220
+ timer = setTimeout(() => finish({ kind: "timeout" }), updateReadyTimeoutMs());
221
+ inspect();
222
+ });
223
+ return { promise, cancel: () => finish({ kind: "cancelled" }) };
224
+ }
225
+
226
+ function snapshotDaemonState(instruction) {
227
+ const updatesRoot = path.join(instruction.dataDir, ".updates");
228
+ const attemptDir = path.join(updatesRoot, instruction.attemptID);
229
+ fs.mkdirSync(updatesRoot, { recursive: true, mode: 0o700 });
230
+ fs.mkdirSync(attemptDir, { mode: 0o700 });
231
+ const database = path.join(instruction.dataDir, "queue.db");
232
+ const backup = path.join(attemptDir, "queue.db");
233
+ const databaseExisted = fs.existsSync(database);
234
+ if (databaseExisted) {
235
+ fs.copyFileSync(database, backup);
236
+ const backupFile = fs.openSync(backup, "r");
237
+ try {
238
+ fs.fsyncSync(backupFile);
239
+ } finally {
240
+ fs.closeSync(backupFile);
241
+ }
242
+ }
243
+ return {
244
+ attemptDir,
245
+ readyFile: path.join(attemptDir, "ready.json"),
246
+ database,
247
+ backup,
248
+ databaseExisted,
249
+ };
250
+ }
251
+
252
+ function restoreDaemonState(snapshot) {
253
+ for (const suffix of ["-wal", "-shm"]) {
254
+ fs.rmSync(snapshot.database + suffix, { force: true });
255
+ }
256
+ if (snapshot.databaseExisted) {
257
+ const restore = snapshot.database + ".restore";
258
+ fs.copyFileSync(snapshot.backup, restore);
259
+ fs.renameSync(restore, snapshot.database);
260
+ } else {
261
+ fs.rmSync(snapshot.database, { force: true });
262
+ }
263
+ }
264
+
265
+ function managedUpdateEnvironment(instruction, snapshot, outcome, error) {
266
+ return {
267
+ ...process.env,
268
+ [updateFDEnv]: "3",
269
+ [updateAttemptEnv]: instruction.attemptID,
270
+ [updateOutcomeEnv]: outcome,
271
+ [updateErrorEnv]: error || "",
272
+ [updateReadyFileEnv]: snapshot.readyFile,
273
+ };
274
+ }
275
+
276
+ function removeUpdateSnapshot(snapshot) {
277
+ try {
278
+ fs.rmSync(snapshot.attemptDir, { recursive: true, force: true });
279
+ } catch (error) {
280
+ console.error("Chord could not remove the completed daemon update snapshot: " + error.message);
281
+ }
282
+ }
283
+
284
+ async function stopCandidate(completion, candidateChild) {
285
+ if (candidateChild && candidateChild.exitCode === null && candidateChild.signalCode === null) {
286
+ try {
287
+ candidateChild.kill("SIGTERM");
288
+ } catch {
289
+ // The child may have exited between the check and signal.
290
+ }
291
+ }
292
+ const stopped = await Promise.race([
293
+ completion.then(() => true),
294
+ new Promise((resolve) => setTimeout(() => resolve(false), 5_000)),
295
+ ]);
296
+ if (!stopped && candidateChild && candidateChild.exitCode === null && candidateChild.signalCode === null) {
297
+ try {
298
+ candidateChild.kill("SIGKILL");
299
+ } catch {
300
+ // The child may have exited between the check and signal.
301
+ }
302
+ }
303
+ return completion;
304
+ }
305
+
306
+ function candidateFailure(outcome) {
307
+ if (outcome.kind === "timeout") {
308
+ return "the updated daemon did not become ready within " + updateReadyTimeoutMs() + "ms";
309
+ }
310
+ const result = outcome.result;
311
+ if (result.error) {
312
+ return "the updated daemon could not start: " + result.error.message;
313
+ }
314
+ if (result.signal) {
315
+ return "the updated daemon exited before readiness with signal " + result.signal;
316
+ }
317
+ return "the updated daemon exited before readiness with code " + result.code;
318
+ }
319
+
320
+ async function runManagedUpdate(binaryPath, packageManager, instruction, daemonArgs) {
321
+ let snapshot;
322
+ try {
323
+ snapshot = snapshotDaemonState(instruction);
324
+ } catch (error) {
325
+ console.error("Chord could not prepare the daemon update: " + error.message);
326
+ return runChild(binaryPath, daemonArgs, {
327
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
328
+ env: { ...process.env, [updateFDEnv]: "3" },
329
+ });
330
+ }
331
+
332
+ const update = updateCommand(packageManager, instruction.cliVersion, daemonArgs);
333
+ console.error("Updating Chord daemon to @sys9/chord-cli@" + instruction.cliVersion + ".");
334
+ const candidate = runChild(update.command, update.args, {
335
+ stdio: "inherit",
336
+ env: managedUpdateEnvironment(instruction, snapshot, "target", ""),
337
+ });
338
+ const candidateChild = child;
339
+ const readiness = monitorReadiness(snapshot.readyFile, instruction, "target");
340
+ const outcome = await Promise.race([
341
+ candidate.then((result) => ({ kind: "exit", result })),
342
+ readiness.promise,
343
+ ]);
344
+ readiness.cancel();
345
+
346
+ if (receivedSignal) {
347
+ if (outcome.kind !== "ready") {
348
+ try {
349
+ restoreDaemonState(snapshot);
350
+ } catch (error) {
351
+ console.error("Chord could not restore daemon state during shutdown: " + error.message);
352
+ }
353
+ }
354
+ return candidate;
355
+ }
356
+ if (outcome.kind === "ready") {
357
+ removeUpdateSnapshot(snapshot);
358
+ return candidate;
359
+ }
360
+ if (outcome.kind === "timeout") {
361
+ await stopCandidate(candidate, candidateChild);
362
+ }
363
+ const failure = candidateFailure(outcome).slice(0, 1024);
364
+ console.error("Chord daemon update failed; restoring " + instruction.fromVersion + ". " + failure);
365
+ try {
366
+ restoreDaemonState(snapshot);
367
+ } catch (error) {
368
+ console.error("Chord could not restore the previous daemon state: " + error.message);
369
+ return { code: 1, signal: null, updateInstruction: "", error: null };
370
+ }
371
+
372
+ fs.rmSync(snapshot.readyFile, { force: true });
373
+ const restored = runChild(binaryPath, daemonArgs, {
374
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
375
+ env: managedUpdateEnvironment(instruction, snapshot, "rolled_back", failure),
376
+ });
377
+ const rollbackReadiness = monitorReadiness(snapshot.readyFile, instruction, "rolled_back");
378
+ const rollbackOutcome = await Promise.race([
379
+ restored.then((result) => ({ kind: "exit", result })),
380
+ rollbackReadiness.promise,
381
+ ]);
382
+ rollbackReadiness.cancel();
383
+ if (rollbackOutcome.kind === "ready") {
384
+ removeUpdateSnapshot(snapshot);
385
+ }
386
+ return restored;
387
+ }
388
+
389
+ async function main() {
390
+ const { binaryPath, platformPackage } = resolveBinaryPath();
391
+ if (!fs.existsSync(binaryPath)) {
392
+ const packageManager = detectPackageManager();
393
+ const update =
394
+ packageManager === "bun"
395
+ ? "bun add -g @sys9/chord-cli@latest"
396
+ : "npm install -g @sys9/chord-cli@latest";
397
+ throw new Error(
398
+ "Missing optional dependency " + platformPackage + ". Reinstall chord: " + update,
399
+ );
400
+ }
401
+
402
+ const daemonArgs = process.argv.slice(2);
403
+ const result = await runChild(binaryPath, daemonArgs, {
404
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
405
+ env: { ...process.env, [updateFDEnv]: "3" },
406
+ });
407
+ if (result.error) {
408
+ console.error(result.error);
409
+ return result;
410
+ }
411
+ if (result.signal || receivedSignal) {
412
+ return { ...result, signal: result.signal || receivedSignal };
413
+ }
414
+ if (result.code !== updateRequestedExitCode) {
415
+ return result;
416
+ }
417
+
418
+ const instruction = parseUpdateInstruction(result.updateInstruction);
419
+ if (!instruction) {
420
+ console.error("Chord daemon exited for an update, but did not provide a valid managed update instruction.");
421
+ return result;
422
+ }
423
+
424
+ const packageManager = detectPackageManager();
425
+ return runManagedUpdate(binaryPath, packageManager, instruction, daemonArgs);
426
+ }
427
+
428
+ main().then((result) => {
429
+ if (result.signal) {
430
+ process.removeAllListeners(result.signal);
431
+ process.kill(process.pid, result.signal);
432
+ return;
433
+ }
434
+ process.exit(result.code);
435
+ }).catch((error) => {
436
+ console.error(error);
437
+ process.exit(1);
438
+ });
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+
5
+ const SUPPORTED_TARGETS = [
6
+ {
7
+ slug: "linux-x64",
8
+ os: "linux",
9
+ cpu: "x64",
10
+ vendorDir: "linux_amd64",
11
+ targetTriple: "x86_64-unknown-linux-musl",
12
+ },
13
+ {
14
+ slug: "linux-arm64",
15
+ os: "linux",
16
+ cpu: "arm64",
17
+ vendorDir: "linux_arm64",
18
+ targetTriple: "aarch64-unknown-linux-musl",
19
+ },
20
+ {
21
+ slug: "darwin-x64",
22
+ os: "darwin",
23
+ cpu: "x64",
24
+ vendorDir: "darwin_amd64",
25
+ targetTriple: "x86_64-apple-darwin",
26
+ },
27
+ {
28
+ slug: "darwin-arm64",
29
+ os: "darwin",
30
+ cpu: "arm64",
31
+ vendorDir: "darwin_arm64",
32
+ targetTriple: "aarch64-apple-darwin",
33
+ }
34
+ ];
35
+
36
+ function resolveSupportedTarget(platform = process.platform, arch = process.arch) {
37
+ for (const target of SUPPORTED_TARGETS) {
38
+ if (target.os === platform && target.cpu === arch) {
39
+ return target;
40
+ }
41
+ }
42
+ throw new Error("unsupported platform: " + platform + " (" + arch + ")");
43
+ }
44
+
45
+ function resolvePackagedBinaryPath(rootDir, platform = process.platform, arch = process.arch) {
46
+ const target = resolveSupportedTarget(platform, arch);
47
+ return path.join(rootDir, "vendor", target.vendorDir, "chord");
48
+ }
49
+
50
+ function resolvePlatformPackageName(rootPackageName, platform = process.platform, arch = process.arch) {
51
+ const target = resolveSupportedTarget(platform, arch);
52
+ return rootPackageName + "-" + target.slug;
53
+ }
54
+
55
+ module.exports = {
56
+ SUPPORTED_TARGETS,
57
+ resolvePackagedBinaryPath,
58
+ resolvePlatformPackageName,
59
+ resolveSupportedTarget,
60
+ };
package/package.json CHANGED
@@ -1,22 +1,30 @@
1
1
  {
2
2
  "name": "@sys9/chord-cli",
3
- "version": "0.1.149-linux-arm64",
3
+ "version": "0.1.149",
4
4
  "description": "Chord CLI package used by @sys9/cli",
5
5
  "license": "UNLICENSED",
6
- "os": [
7
- "linux"
8
- ],
9
- "cpu": [
10
- "arm64"
11
- ],
12
- "files": [
13
- "vendor"
14
- ],
15
6
  "repository": {
16
7
  "type": "git",
17
8
  "url": "git+https://github.com/sys9-ai/chord.git"
18
9
  },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "bin": {
14
+ "chord": "bin/chord"
15
+ },
16
+ "files": [
17
+ "README.md",
18
+ "bin",
19
+ "lib"
20
+ ],
19
21
  "engines": {
20
22
  "node": ">=16"
23
+ },
24
+ "optionalDependencies": {
25
+ "@sys9/chord-cli-linux-x64": "npm:@sys9/chord-cli@0.1.149-linux-x64",
26
+ "@sys9/chord-cli-linux-arm64": "npm:@sys9/chord-cli@0.1.149-linux-arm64",
27
+ "@sys9/chord-cli-darwin-x64": "npm:@sys9/chord-cli@0.1.149-darwin-x64",
28
+ "@sys9/chord-cli-darwin-arm64": "npm:@sys9/chord-cli@0.1.149-darwin-arm64"
21
29
  }
22
30
  }
Binary file