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

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,454 @@
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 updateRequiredExitCode = 75;
53
+ const updateFDEnv = "CHORD_CLI_UPDATE_FD";
54
+ const updateVersionEnv = "CHORD_CLI_AUTO_UPDATE_VERSION";
55
+ const updateAttemptEnv = "CHORD_CLI_UPDATE_ATTEMPT_ID";
56
+ const updateOutcomeEnv = "CHORD_CLI_UPDATE_OUTCOME";
57
+ const updateErrorEnv = "CHORD_CLI_UPDATE_ERROR";
58
+ const updateReadyFileEnv = "CHORD_CLI_UPDATE_READY_FILE";
59
+ const updateReadyTimeoutEnv = "CHORD_CLI_UPDATE_READY_TIMEOUT_MS";
60
+ const maxUpdateInstructionBytes = 4096;
61
+ const defaultUpdateReadyTimeoutMs = 60_000;
62
+ let child = null;
63
+ let receivedSignal = null;
64
+
65
+ const forwardSignal = (signal) => {
66
+ receivedSignal = signal;
67
+ if (!child || child.killed) {
68
+ return;
69
+ }
70
+ try {
71
+ child.kill(signal);
72
+ } catch {
73
+ // Ignore failures while the child is already exiting.
74
+ }
75
+ };
76
+
77
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((signal) => {
78
+ process.on(signal, () => forwardSignal(signal));
79
+ });
80
+
81
+ function runChild(command, args, options) {
82
+ return new Promise((resolve) => {
83
+ let updateInstruction = "";
84
+ let settled = false;
85
+ let childResult = null;
86
+ let updatePipeClosed = true;
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) {
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
+ });
109
+ child.stdio[3].on("end", () => {
110
+ updatePipeClosed = true;
111
+ finishAfterUpdatePipe();
112
+ });
113
+ }
114
+ child.on("error", (error) => {
115
+ finish({ code: 1, signal: null, updateInstruction: "", error });
116
+ });
117
+ child.on("exit", (code, signal) => {
118
+ // A daemon descendant may temporarily retain the update pipe. Once the
119
+ // direct child exits after a signal, waiting for every inherited file
120
+ // descriptor would keep service shutdown stuck for that descendant's
121
+ // lifetime.
122
+ if (signal || receivedSignal) {
123
+ finish({ code: code ?? 1, signal, updateInstruction, error: null });
124
+ }
125
+ });
126
+ child.on("close", (code, signal) => {
127
+ childResult = { code: code ?? 1, signal, error: null };
128
+ finishAfterUpdatePipe();
129
+ });
130
+ });
131
+ }
132
+
133
+ function parseUpdateInstruction(raw) {
134
+ if (!raw || raw.length > maxUpdateInstructionBytes) {
135
+ return null;
136
+ }
137
+ try {
138
+ const instruction = JSON.parse(raw);
139
+ const version = instruction && instruction.cli_version;
140
+ if (typeof version !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) {
141
+ return null;
142
+ }
143
+ const reason = instruction.reason || "protocol";
144
+ if (reason === "protocol") {
145
+ return { cliVersion: version, reason };
146
+ }
147
+ const attemptID = instruction.attempt_id;
148
+ const dataDir = instruction.data_dir;
149
+ const fromVersion = instruction.from_version;
150
+ const hostID = instruction.host_id;
151
+ if (
152
+ reason !== "user" ||
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, reason, 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: {
337
+ ...managedUpdateEnvironment(instruction, snapshot, "target", ""),
338
+ [updateVersionEnv]: instruction.cliVersion,
339
+ },
340
+ });
341
+ const candidateChild = child;
342
+ const readiness = monitorReadiness(snapshot.readyFile, instruction, "target");
343
+ const outcome = await Promise.race([
344
+ candidate.then((result) => ({ kind: "exit", result })),
345
+ readiness.promise,
346
+ ]);
347
+ readiness.cancel();
348
+
349
+ if (receivedSignal) {
350
+ if (outcome.kind !== "ready") {
351
+ try {
352
+ restoreDaemonState(snapshot);
353
+ } catch (error) {
354
+ console.error("Chord could not restore daemon state during shutdown: " + error.message);
355
+ }
356
+ }
357
+ return candidate;
358
+ }
359
+ if (outcome.kind === "ready") {
360
+ removeUpdateSnapshot(snapshot);
361
+ return candidate;
362
+ }
363
+ if (outcome.kind === "timeout") {
364
+ await stopCandidate(candidate, candidateChild);
365
+ }
366
+ const failure = candidateFailure(outcome).slice(0, 1024);
367
+ console.error("Chord daemon update failed; restoring " + instruction.fromVersion + ". " + failure);
368
+ try {
369
+ restoreDaemonState(snapshot);
370
+ } catch (error) {
371
+ console.error("Chord could not restore the previous daemon state: " + error.message);
372
+ return { code: 1, signal: null, updateInstruction: "", error: null };
373
+ }
374
+
375
+ fs.rmSync(snapshot.readyFile, { force: true });
376
+ const restored = runChild(binaryPath, daemonArgs, {
377
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
378
+ env: managedUpdateEnvironment(instruction, snapshot, "rolled_back", failure),
379
+ });
380
+ const rollbackReadiness = monitorReadiness(snapshot.readyFile, instruction, "rolled_back");
381
+ const rollbackOutcome = await Promise.race([
382
+ restored.then((result) => ({ kind: "exit", result })),
383
+ rollbackReadiness.promise,
384
+ ]);
385
+ rollbackReadiness.cancel();
386
+ if (rollbackOutcome.kind === "ready") {
387
+ removeUpdateSnapshot(snapshot);
388
+ }
389
+ return restored;
390
+ }
391
+
392
+ async function main() {
393
+ const { binaryPath, platformPackage } = resolveBinaryPath();
394
+ if (!fs.existsSync(binaryPath)) {
395
+ const packageManager = detectPackageManager();
396
+ const update =
397
+ packageManager === "bun"
398
+ ? "bun add -g @sys9/chord-cli@latest"
399
+ : "npm install -g @sys9/chord-cli@latest";
400
+ throw new Error(
401
+ "Missing optional dependency " + platformPackage + ". Reinstall chord: " + update,
402
+ );
403
+ }
404
+
405
+ const daemonArgs = process.argv.slice(2);
406
+ const result = await runChild(binaryPath, daemonArgs, {
407
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
408
+ env: { ...process.env, [updateFDEnv]: "3" },
409
+ });
410
+ if (result.error) {
411
+ console.error(result.error);
412
+ return result;
413
+ }
414
+ if (result.signal || receivedSignal) {
415
+ return { ...result, signal: result.signal || receivedSignal };
416
+ }
417
+ if (result.code !== updateRequiredExitCode) {
418
+ return result;
419
+ }
420
+
421
+ const instruction = parseUpdateInstruction(result.updateInstruction);
422
+ if (!instruction) {
423
+ console.error("Chord daemon requires an update, but the server did not provide a valid CLI version.");
424
+ return result;
425
+ }
426
+ if (process.env[updateVersionEnv] === instruction.cliVersion) {
427
+ console.error("Chord daemon automatic update to " + instruction.cliVersion + " was already attempted; update @sys9/chord-cli manually.");
428
+ return result;
429
+ }
430
+
431
+ const packageManager = detectPackageManager();
432
+ if (instruction.reason === "user") {
433
+ return runManagedUpdate(binaryPath, packageManager, instruction, daemonArgs);
434
+ }
435
+ const update = updateCommand(packageManager, instruction.cliVersion, daemonArgs);
436
+ console.error("Chord daemon protocol changed; restarting with @sys9/chord-cli@" + instruction.cliVersion + ".");
437
+ const updated = await runChild(update.command, update.args, {
438
+ stdio: "inherit",
439
+ env: { ...process.env, [updateVersionEnv]: instruction.cliVersion },
440
+ });
441
+ return { ...updated, signal: updated.signal || receivedSignal };
442
+ }
443
+
444
+ main().then((result) => {
445
+ if (result.signal) {
446
+ process.removeAllListeners(result.signal);
447
+ process.kill(process.pid, result.signal);
448
+ return;
449
+ }
450
+ process.exit(result.code);
451
+ }).catch((error) => {
452
+ console.error(error);
453
+ process.exit(1);
454
+ });
@@ -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.126-linux-arm64",
3
+ "version": "0.1.126",
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.126-linux-x64",
26
+ "@sys9/chord-cli-linux-arm64": "npm:@sys9/chord-cli@0.1.126-linux-arm64",
27
+ "@sys9/chord-cli-darwin-x64": "npm:@sys9/chord-cli@0.1.126-darwin-x64",
28
+ "@sys9/chord-cli-darwin-arm64": "npm:@sys9/chord-cli@0.1.126-darwin-arm64"
21
29
  }
22
30
  }
Binary file