@kodycodes/cli 3.17.0 → 3.19.0

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.
Files changed (70) hide show
  1. package/README.md +4 -0
  2. package/dist/{auth-ECXEUH4Q.js → auth-J5AA2E2W.js} +5 -5
  3. package/dist/bin.js +7 -7
  4. package/dist/{chunk-SUR4SJXS.js → chunk-4GIMXYTU.js} +2 -2
  5. package/dist/{chunk-JS4W3PP4.js → chunk-4ZR5HTHC.js} +6 -6
  6. package/dist/{chunk-DP6CORSN.js → chunk-53ISIAMH.js} +43 -38
  7. package/dist/chunk-53ISIAMH.js.map +6 -0
  8. package/dist/{chunk-GYEVN4PD.js → chunk-6IPCLPNQ.js} +7 -1
  9. package/dist/{chunk-GYEVN4PD.js.map → chunk-6IPCLPNQ.js.map} +1 -1
  10. package/dist/{chunk-ZIHC2T5B.js → chunk-7XRBM7AU.js} +2 -2
  11. package/dist/{chunk-WAFEBRMU.js → chunk-CWMTTI6P.js} +3 -3
  12. package/dist/{chunk-DINK4SRI.js → chunk-EKOYDF24.js} +3 -3
  13. package/dist/{chunk-UHBPB4VH.js → chunk-FHLTB67D.js} +6 -3
  14. package/dist/{chunk-UHBPB4VH.js.map → chunk-FHLTB67D.js.map} +1 -1
  15. package/dist/{chunk-7GWFBB4U.js → chunk-FN5KUR6I.js} +4 -4
  16. package/dist/{chunk-EGN6A45D.js → chunk-GV5U56NK.js} +3 -3
  17. package/dist/{chunk-UTJTT7HD.js → chunk-LU2BYSFJ.js} +4 -4
  18. package/dist/{chunk-VUUVCVAG.js → chunk-RWERUUUW.js} +2 -2
  19. package/dist/{chunk-7S5EYKB4.js → chunk-SCRMD7NW.js} +5 -5
  20. package/dist/{chunk-ZXKHQFBC.js → chunk-YXGHVHEJ.js} +28 -9
  21. package/dist/chunk-YXGHVHEJ.js.map +6 -0
  22. package/dist/cli.js +7 -7
  23. package/dist/{commands-YZOAHUIH.js → commands-3KZPBDIP.js} +1447 -106
  24. package/dist/commands-3KZPBDIP.js.map +6 -0
  25. package/dist/{dev-command-5M46BX4R.js → dev-command-4NHEQ2BO.js} +8 -8
  26. package/dist/execution-context/auto-update.d.ts +247 -0
  27. package/dist/execution-context/daemon.d.ts +11 -1
  28. package/dist/execution-context/fs-access.d.ts +6 -0
  29. package/dist/execution-context/host-commands.d.ts +2 -0
  30. package/dist/execution-context/runner-lock.d.ts +58 -0
  31. package/dist/execution-context/service-commands.d.ts +16 -0
  32. package/dist/execution-context/service.d.ts +11 -0
  33. package/dist/{git-credential-G5AEGM3Z.js → git-credential-DPTBUVMO.js} +6 -6
  34. package/dist/{local-execute-2OEGROT2.js → local-execute-BEH3OVD5.js} +7 -7
  35. package/dist/{local-package-graph-M7U7DQ2N.js → local-package-graph-4VLBVUTP.js} +4 -4
  36. package/dist/{local-package-run-IYB3ZIPK.js → local-package-run-UEGYEUSE.js} +8 -8
  37. package/dist/{mock-dep-resolve-JPTW4MDR.js → mock-dep-resolve-76V75ADG.js} +6 -6
  38. package/dist/{mock-local-deps-CNFLGJSA.js → mock-local-deps-MKLQO7DK.js} +5 -5
  39. package/dist/{open-api-client-RXJHHF2O.js → open-api-client-JEQU23NL.js} +4 -4
  40. package/dist/{remote-execute-BYRIWP7N.js → remote-execute-VNUZZNMV.js} +4 -4
  41. package/dist/{run-executor-XTLAUDYY.js → run-executor-7MV5E5PX.js} +9 -9
  42. package/dist/{setup-git-7FYNA4PW.js → setup-git-EVEFEUCJ.js} +5 -5
  43. package/dist/{whoami-AYZRXRCB.js → whoami-E56UFY6Z.js} +4 -4
  44. package/package.json +1 -1
  45. package/dist/chunk-DP6CORSN.js.map +0 -6
  46. package/dist/chunk-ZXKHQFBC.js.map +0 -6
  47. package/dist/commands-YZOAHUIH.js.map +0 -6
  48. /package/dist/{auth-ECXEUH4Q.js.map → auth-J5AA2E2W.js.map} +0 -0
  49. /package/dist/{chunk-SUR4SJXS.js.map → chunk-4GIMXYTU.js.map} +0 -0
  50. /package/dist/{chunk-JS4W3PP4.js.map → chunk-4ZR5HTHC.js.map} +0 -0
  51. /package/dist/{chunk-ZIHC2T5B.js.map → chunk-7XRBM7AU.js.map} +0 -0
  52. /package/dist/{chunk-WAFEBRMU.js.map → chunk-CWMTTI6P.js.map} +0 -0
  53. /package/dist/{chunk-DINK4SRI.js.map → chunk-EKOYDF24.js.map} +0 -0
  54. /package/dist/{chunk-7GWFBB4U.js.map → chunk-FN5KUR6I.js.map} +0 -0
  55. /package/dist/{chunk-EGN6A45D.js.map → chunk-GV5U56NK.js.map} +0 -0
  56. /package/dist/{chunk-UTJTT7HD.js.map → chunk-LU2BYSFJ.js.map} +0 -0
  57. /package/dist/{chunk-VUUVCVAG.js.map → chunk-RWERUUUW.js.map} +0 -0
  58. /package/dist/{chunk-7S5EYKB4.js.map → chunk-SCRMD7NW.js.map} +0 -0
  59. /package/dist/{dev-command-5M46BX4R.js.map → dev-command-4NHEQ2BO.js.map} +0 -0
  60. /package/dist/{git-credential-G5AEGM3Z.js.map → git-credential-DPTBUVMO.js.map} +0 -0
  61. /package/dist/{local-execute-2OEGROT2.js.map → local-execute-BEH3OVD5.js.map} +0 -0
  62. /package/dist/{local-package-graph-M7U7DQ2N.js.map → local-package-graph-4VLBVUTP.js.map} +0 -0
  63. /package/dist/{local-package-run-IYB3ZIPK.js.map → local-package-run-UEGYEUSE.js.map} +0 -0
  64. /package/dist/{mock-dep-resolve-JPTW4MDR.js.map → mock-dep-resolve-76V75ADG.js.map} +0 -0
  65. /package/dist/{mock-local-deps-CNFLGJSA.js.map → mock-local-deps-MKLQO7DK.js.map} +0 -0
  66. /package/dist/{open-api-client-RXJHHF2O.js.map → open-api-client-JEQU23NL.js.map} +0 -0
  67. /package/dist/{remote-execute-BYRIWP7N.js.map → remote-execute-VNUZZNMV.js.map} +0 -0
  68. /package/dist/{run-executor-XTLAUDYY.js.map → run-executor-7MV5E5PX.js.map} +0 -0
  69. /package/dist/{setup-git-7FYNA4PW.js.map → setup-git-EVEFEUCJ.js.map} +0 -0
  70. /package/dist/{whoami-AYZRXRCB.js.map → whoami-E56UFY6Z.js.map} +0 -0
@@ -19,7 +19,7 @@ import {
19
19
  signFrame,
20
20
  verifyFrame,
21
21
  verifyServerKeySet
22
- } from "./chunk-GYEVN4PD.js";
22
+ } from "./chunk-6IPCLPNQ.js";
23
23
  import {
24
24
  allowLocalPath,
25
25
  createLocalWorkerTracker,
@@ -32,15 +32,17 @@ import {
32
32
  readLocalPolicy,
33
33
  reapLeftoverWorkers,
34
34
  removeLocalPath,
35
+ setLocalAutoUpdateEnabled,
35
36
  setLocalCommandsEnabled
36
- } from "./chunk-ZXKHQFBC.js";
37
- import "./chunk-EGN6A45D.js";
38
- import "./chunk-SUR4SJXS.js";
37
+ } from "./chunk-YXGHVHEJ.js";
38
+ import "./chunk-GV5U56NK.js";
39
+ import "./chunk-4GIMXYTU.js";
39
40
  import {
40
41
  apiTokenFileStorePath
41
- } from "./chunk-UHBPB4VH.js";
42
+ } from "./chunk-FHLTB67D.js";
42
43
  import "./chunk-NHRYNRXG.js";
43
44
  import {
45
+ cliConfigDir,
44
46
  secretServiceKeyringOptions
45
47
  } from "./chunk-D6XME4RY.js";
46
48
  import {
@@ -49,7 +51,7 @@ import {
49
51
  import "./chunk-UW6AWLXX.js";
50
52
 
51
53
  // src/execution-context/commands.ts
52
- import { readFileSync as readFileSync4, rmSync as rmSync2, unwatchFile, watchFile } from "node:fs";
54
+ import { readFileSync as readFileSync6, rmSync as rmSync4, unwatchFile, watchFile } from "node:fs";
53
55
  import { cpus, platform, totalmem } from "node:os";
54
56
 
55
57
  // src/execution-context/client.ts
@@ -249,6 +251,813 @@ async function apiJson(input) {
249
251
  return await response.json();
250
252
  }
251
253
 
254
+ // src/execution-context/auto-update.ts
255
+ import { spawn } from "node:child_process";
256
+ import { createHash, randomBytes } from "node:crypto";
257
+ import {
258
+ cpSync,
259
+ existsSync,
260
+ mkdirSync,
261
+ readFileSync,
262
+ readdirSync,
263
+ renameSync,
264
+ rmSync,
265
+ statSync,
266
+ writeFileSync
267
+ } from "node:fs";
268
+ import { createRequire } from "node:module";
269
+ import { homedir } from "node:os";
270
+ import { delimiter, dirname, isAbsolute, join, normalize, sep } from "node:path";
271
+ import { gunzipSync } from "node:zlib";
272
+ var packageName = "@kodycodes/cli";
273
+ var registryUrl = "https://registry.npmjs.org";
274
+ var relaunchExitCode = 75;
275
+ var startupRefusedExitCode = 76;
276
+ var supervisedEnvVar = "KODY_DAEMON_SUPERVISED";
277
+ var autoUpdateEnvVar = "KODY_DAEMON_AUTO_UPDATE";
278
+ var checkIntervalMs = 4 * 60 * 6e4;
279
+ var checkJitterMs = 30 * 6e4;
280
+ var maxIdleWaitMs = 24 * 60 * 6e4;
281
+ var maxTarballBytes = 64 * 1024 * 1024;
282
+ var healthyAfterMs = 6e4;
283
+ var versionPattern = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/;
284
+ function parseVersion(value) {
285
+ const match = versionPattern.exec(value.trim());
286
+ if (!match) return null;
287
+ return {
288
+ parts: [Number(match[1]), Number(match[2]), Number(match[3])],
289
+ prerelease: match[4] ?? null
290
+ };
291
+ }
292
+ function compareVersions(a, b) {
293
+ const left = parseVersion(a);
294
+ const right = parseVersion(b);
295
+ if (!left || !right) return 0;
296
+ for (let index = 0; index < 3; index++) {
297
+ const diff = left.parts[index] - right.parts[index];
298
+ if (diff !== 0) return diff;
299
+ }
300
+ if (left.prerelease === right.prerelease) return 0;
301
+ if (left.prerelease === null) return 1;
302
+ if (right.prerelease === null) return -1;
303
+ return left.prerelease < right.prerelease ? -1 : 1;
304
+ }
305
+ var isNewer = (candidate, than) => compareVersions(candidate, than) > 0;
306
+ function satisfies(version, range) {
307
+ const parsed = parseVersion(version);
308
+ const trimmed = range.trim();
309
+ if (!parsed) return false;
310
+ if (trimmed === "*" || trimmed === "") return true;
311
+ const op = /^(\^|~|>=)?\s*v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(
312
+ trimmed
313
+ );
314
+ if (!op) return false;
315
+ const base = op[2];
316
+ const [major, minor] = parseVersion(base).parts;
317
+ if (compareVersions(version, base) < 0) return false;
318
+ if (parsed.prerelease && !base.includes("-")) return false;
319
+ if (!op[1]) return compareVersions(version, base) === 0;
320
+ if (op[1] === ">=") return true;
321
+ if (op[1] === "~")
322
+ return parsed.parts[0] === major && parsed.parts[1] === minor;
323
+ if (major !== 0) return parsed.parts[0] === major;
324
+ if (minor !== 0) return parsed.parts[0] === 0 && parsed.parts[1] === minor;
325
+ return compareVersions(version, base) === 0;
326
+ }
327
+ function cliStoreDir(env = process.env, home = homedir()) {
328
+ if (env.KODY_CLI_STORE_DIR) return env.KODY_CLI_STORE_DIR;
329
+ if (process.platform === "linux") {
330
+ return join(
331
+ env.XDG_DATA_HOME || join(home, ".local", "share"),
332
+ "kody",
333
+ "cli"
334
+ );
335
+ }
336
+ return join(cliConfigDir(home), "cli");
337
+ }
338
+ function readJsonFile(path) {
339
+ try {
340
+ return JSON.parse(readFileSync(path, "utf8"));
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ function writeJsonAtomic(path, value) {
346
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
347
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
348
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}
349
+ `, { mode: 384 });
350
+ renameSync(temp, path);
351
+ }
352
+ function readCurrent(store = cliStoreDir()) {
353
+ const current = readJsonFile(join(store, "current.json"));
354
+ if (!current || typeof current.version !== "string" || typeof current.entry !== "string" || !parseVersion(current.version) || !isAbsolute(current.entry) || !isWithinDir(current.entry, join(store, "versions"))) {
355
+ return null;
356
+ }
357
+ return current;
358
+ }
359
+ function readUpdateState(store = cliStoreDir()) {
360
+ return readJsonFile(join(store, "update-state.json")) ?? {};
361
+ }
362
+ function updateState(store, change) {
363
+ const next = change(readUpdateState(store));
364
+ writeJsonAtomic(join(store, "update-state.json"), next);
365
+ return next;
366
+ }
367
+ function recordEvent(store, event) {
368
+ updateState(store, (state) => ({
369
+ ...state,
370
+ history: [...state.history ?? [], event].slice(-20)
371
+ }));
372
+ }
373
+ function recordFailedStart(store, version, from, detail, now = Date.now()) {
374
+ return updateState(store, (state) => {
375
+ const count = (state.failures?.[version]?.count ?? 0) + 1;
376
+ const bad = count >= 3;
377
+ return {
378
+ ...state,
379
+ failures: {
380
+ ...state.failures,
381
+ [version]: {
382
+ count,
383
+ nextAttemptAt: new Date(now + backoffMs(count)).toISOString(),
384
+ error: detail
385
+ }
386
+ },
387
+ ...bad ? { bad: [.../* @__PURE__ */ new Set([...state.bad ?? [], version])].slice(-20) } : {},
388
+ history: [
389
+ ...state.history ?? [],
390
+ {
391
+ at: new Date(now).toISOString(),
392
+ from,
393
+ to: version,
394
+ outcome: bad ? "bad" : "failed",
395
+ detail
396
+ }
397
+ ].slice(-20)
398
+ };
399
+ });
400
+ }
401
+ function isWithinDir(child, parent) {
402
+ const normalized = normalize(child);
403
+ return normalized.startsWith(normalize(parent) + sep);
404
+ }
405
+ function newerInstalledVersion(input) {
406
+ const store = input.store ?? cliStoreDir();
407
+ const current = readCurrent(store);
408
+ if (!current || !isNewer(current.version, input.selfVersion)) return null;
409
+ const state = readUpdateState(store);
410
+ if (state.bad?.includes(current.version)) return null;
411
+ const failure = state.failures?.[current.version];
412
+ if (failure && Date.parse(failure.nextAttemptAt) > (input.now ?? Date.now())) {
413
+ return null;
414
+ }
415
+ if (!existsSync(current.entry)) return null;
416
+ return current;
417
+ }
418
+ function autoUpdateSetting(policy, env = process.env) {
419
+ const forced = env[autoUpdateEnvVar]?.trim().toLowerCase();
420
+ if (forced && ["0", "off", "false", "no"].includes(forced)) {
421
+ return { enabled: false, source: "env" };
422
+ }
423
+ if (policy?.autoUpdate) {
424
+ return {
425
+ enabled: policy.autoUpdate.enabled,
426
+ source: "policy",
427
+ ...policy.autoUpdate.changedAt ? { changedAt: policy.autoUpdate.changedAt } : {}
428
+ };
429
+ }
430
+ return { enabled: true, source: "default" };
431
+ }
432
+ async function fetchLatestVersion(input) {
433
+ const registry = (input.registry ?? registryUrl).replace(/\/$/, "");
434
+ const response = await (input.fetchFn ?? fetch)(
435
+ `${registry}/${packageName.replace("/", "%2F")}/latest`,
436
+ {
437
+ headers: { accept: "application/json" },
438
+ signal: AbortSignal.timeout(input.timeoutMs ?? 3e4)
439
+ }
440
+ );
441
+ if (!response.ok) throw new Error(`npm registry answered ${response.status}`);
442
+ const body = await response.json();
443
+ if (body.name !== packageName) throw new Error("npm returned another package");
444
+ if (typeof body.version !== "string" || !parseVersion(body.version)) {
445
+ throw new Error("npm returned no valid version");
446
+ }
447
+ const integrity = body.dist?.integrity;
448
+ const tarball = body.dist?.tarball;
449
+ if (typeof integrity !== "string" || !integrity.startsWith("sha512-")) {
450
+ throw new Error(`npm lists no sha512 integrity for ${body.version}`);
451
+ }
452
+ if (typeof tarball !== "string" || new URL(tarball).origin !== new URL(registry).origin) {
453
+ throw new Error(`npm lists an unexpected tarball URL for ${body.version}`);
454
+ }
455
+ return { version: body.version, tarball, integrity };
456
+ }
457
+ async function downloadVerified(input) {
458
+ const response = await (input.fetchFn ?? fetch)(input.published.tarball, {
459
+ signal: AbortSignal.timeout(5 * 6e4)
460
+ });
461
+ if (!response.ok)
462
+ throw new Error(`tarball download answered ${response.status}`);
463
+ const bytes = Buffer.from(await response.arrayBuffer());
464
+ if (bytes.byteLength > maxTarballBytes)
465
+ throw new Error("tarball is too large");
466
+ const actual = `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
467
+ if (actual !== input.published.integrity) {
468
+ throw new Error(
469
+ `integrity mismatch for ${input.published.version}: npm lists ${input.published.integrity}, the download is ${actual}`
470
+ );
471
+ }
472
+ return bytes;
473
+ }
474
+ function extractPackage(gzipped, dest) {
475
+ const tar = gunzipSync(gzipped);
476
+ let offset = 0;
477
+ let longName = null;
478
+ let paxPath = null;
479
+ const text = (start, length) => {
480
+ const raw = tar.subarray(start, start + length);
481
+ const end = raw.indexOf(0);
482
+ return raw.subarray(0, end === -1 ? raw.length : end).toString("utf8");
483
+ };
484
+ while (offset + 512 <= tar.length) {
485
+ const header = tar.subarray(offset, offset + 512);
486
+ if (header.every((byte) => byte === 0)) break;
487
+ const size = Number.parseInt(text(offset + 124, 12).trim() || "0", 8);
488
+ const type = String.fromCharCode(header[156]);
489
+ const prefix = text(offset + 345, 155);
490
+ const name = text(offset, 100);
491
+ const mode = Number.parseInt(text(offset + 100, 8).trim() || "644", 8);
492
+ const dataStart = offset + 512;
493
+ const data = tar.subarray(dataStart, dataStart + size);
494
+ offset = dataStart + Math.ceil(size / 512) * 512;
495
+ if (type === "L") {
496
+ longName = data.toString("utf8").replace(/\0+$/, "");
497
+ continue;
498
+ }
499
+ if (type === "x") {
500
+ const match = /\d+ path=([^\n]*)\n/.exec(data.toString("utf8"));
501
+ paxPath = match ? match[1] : null;
502
+ continue;
503
+ }
504
+ if (type === "g") continue;
505
+ const path = paxPath ?? longName ?? (prefix ? `${prefix}/${name}` : name);
506
+ paxPath = null;
507
+ longName = null;
508
+ const relative = path.replace(/^package\//, "");
509
+ if (relative === path && path !== "package") continue;
510
+ const parts = relative.split("/").filter(Boolean);
511
+ if (parts.some((part) => part === ".." || part === ".") || isAbsolute(relative)) {
512
+ throw new Error(`tarball has an unsafe path: ${path}`);
513
+ }
514
+ if (parts.length === 0) continue;
515
+ const target = join(dest, ...parts);
516
+ if (type === "5") {
517
+ mkdirSync(target, { recursive: true });
518
+ } else if (type === "0" || type === "\0" || type === "7") {
519
+ mkdirSync(dirname(target), { recursive: true });
520
+ writeFileSync(target, data, { mode: mode & 73 ? 493 : 420 });
521
+ }
522
+ }
523
+ }
524
+ function packageRootOf(entry) {
525
+ let dir = dirname(entry);
526
+ while (dir !== dirname(dir)) {
527
+ const pkg = readJsonFile(join(dir, "package.json"));
528
+ if (pkg?.name === packageName) return dir;
529
+ dir = dirname(dir);
530
+ }
531
+ return null;
532
+ }
533
+ function linkDependenciesFrom(input) {
534
+ const copied = /* @__PURE__ */ new Map();
535
+ const visit = (name, range, fromDir, optional) => {
536
+ let pkgPath;
537
+ try {
538
+ pkgPath = createRequire(join(fromDir, "package.json")).resolve(
539
+ `${name}/package.json`
540
+ );
541
+ } catch {
542
+ if (optional) return;
543
+ throw new Error(`dependency ${name} is not installed next to this CLI`);
544
+ }
545
+ const pkg = readJsonFile(pkgPath);
546
+ const version = pkg?.version ?? "";
547
+ if (!satisfies(version, range)) {
548
+ if (optional) return;
549
+ throw new Error(`dependency ${name}@${version} does not satisfy ${range}`);
550
+ }
551
+ const already = copied.get(name);
552
+ if (already !== void 0) {
553
+ if (already !== version)
554
+ throw new Error(`two versions of ${name} are needed`);
555
+ return;
556
+ }
557
+ copied.set(name, version);
558
+ const source = dirname(pkgPath);
559
+ cpSync(source, join(input.nodeModules, name), {
560
+ recursive: true,
561
+ dereference: true,
562
+ filter: (path) => !path.slice(source.length).split(/[\\/]/).includes("node_modules")
563
+ });
564
+ for (const [dep, depRange] of Object.entries(pkg?.dependencies ?? {})) {
565
+ visit(dep, depRange, source, false);
566
+ }
567
+ for (const [dep, depRange] of Object.entries(
568
+ pkg?.optionalDependencies ?? {}
569
+ )) {
570
+ visit(dep, depRange, source, true);
571
+ }
572
+ };
573
+ for (const [name, range] of Object.entries(
574
+ input.newPackage.dependencies ?? {}
575
+ )) {
576
+ visit(name, range, input.runningPackageRoot, false);
577
+ }
578
+ }
579
+ function findNpm(env = process.env) {
580
+ const bin = process.platform === "win32" ? "npm.cmd" : "npm";
581
+ const dirs = [
582
+ ...process.versions.electron ? [] : [dirname(process.execPath)],
583
+ ...(env.PATH ?? "").split(delimiter),
584
+ "/opt/homebrew/bin",
585
+ "/usr/local/bin",
586
+ "/usr/bin"
587
+ ].filter(Boolean);
588
+ for (const dir of dirs) {
589
+ const candidate = join(dir, bin);
590
+ if (existsSync(candidate)) return candidate;
591
+ }
592
+ return null;
593
+ }
594
+ function runStep(command, args, options) {
595
+ return new Promise((resolve) => {
596
+ let output = "";
597
+ let settled = false;
598
+ const finish = (code, extra = "") => {
599
+ if (settled) return;
600
+ settled = true;
601
+ clearTimeout(timer);
602
+ resolve({ code, output: `${output}${extra}` });
603
+ };
604
+ const child = spawn(command, args, {
605
+ stdio: ["ignore", "pipe", "pipe"],
606
+ ...options.env ? { env: options.env } : {},
607
+ ...options.shell ? { shell: true } : {}
608
+ });
609
+ const append = (chunk) => {
610
+ output = `${output}${chunk.toString("utf8")}`.slice(-8e3);
611
+ };
612
+ child.stdout?.on("data", append);
613
+ child.stderr?.on("data", append);
614
+ const timer = setTimeout(() => {
615
+ child.kill("SIGKILL");
616
+ finish(null, `
617
+ timed out after ${Math.round(options.timeoutMs / 1e3)}s`);
618
+ }, options.timeoutMs);
619
+ timer.unref?.();
620
+ child.once("error", (error) => finish(null, error.message));
621
+ child.once("close", (code) => finish(code));
622
+ });
623
+ }
624
+ async function defaultSmokeTest(entry) {
625
+ const result = await runStep(process.execPath, [entry, "version"], {
626
+ timeoutMs: 6e4,
627
+ env: {
628
+ ...process.env,
629
+ KODY_SKIP_SKILL_REFRESH: "1",
630
+ KODY_SKIP_GIT_HELPER_REFRESH: "1"
631
+ }
632
+ });
633
+ return { ok: result.code === 0, output: result.output };
634
+ }
635
+ async function defaultNpmInstall(input) {
636
+ const npm = findNpm();
637
+ if (!npm) {
638
+ return {
639
+ ok: false,
640
+ output: "npm was not found to install its dependencies"
641
+ };
642
+ }
643
+ const result = await runStep(
644
+ npm,
645
+ [
646
+ "install",
647
+ "--prefix",
648
+ input.prefix,
649
+ "--no-save",
650
+ "--no-package-lock",
651
+ "--no-audit",
652
+ "--no-fund",
653
+ "--omit=dev",
654
+ input.tarballPath
655
+ ],
656
+ { timeoutMs: 10 * 6e4, shell: process.platform === "win32" }
657
+ );
658
+ return { ok: result.code === 0, output: result.output.slice(-2e3) };
659
+ }
660
+ async function installVersion(input) {
661
+ const { store, published } = input;
662
+ const versionsDir = join(store, "versions");
663
+ const final = join(versionsDir, published.version);
664
+ const entryIn = (root) => join(root, "node_modules", ...packageName.split("/"), "dist", "bin.js");
665
+ const smoke = input.deps?.smokeTest ?? defaultSmokeTest;
666
+ const proven = async (root) => {
667
+ const result = await smoke(entryIn(root));
668
+ if (!result.ok || result.output.trim().split("\n").pop()?.trim() !== published.version) {
669
+ throw new Error(
670
+ `kody ${published.version} did not start (kody version printed: ${result.output.trim().slice(-300) || "nothing"})`
671
+ );
672
+ }
673
+ };
674
+ if (readJsonFile(
675
+ join(final, "node_modules", ...packageName.split("/"), "package.json")
676
+ )?.version === published.version) {
677
+ await proven(final);
678
+ } else {
679
+ mkdirSync(versionsDir, { recursive: true, mode: 448 });
680
+ const staging = join(
681
+ versionsDir,
682
+ `.staging-${published.version}-${randomBytes(4).toString("hex")}`
683
+ );
684
+ try {
685
+ const pkgDir = join(staging, "node_modules", ...packageName.split("/"));
686
+ mkdirSync(pkgDir, { recursive: true });
687
+ extractPackage(input.tarball, pkgDir);
688
+ const pkg = readJsonFile(join(pkgDir, "package.json"));
689
+ if (pkg?.name !== packageName || pkg.version !== published.version) {
690
+ throw new Error(
691
+ `the tarball holds ${pkg?.name ?? "?"}@${pkg?.version ?? "?"}, not ${published.version}`
692
+ );
693
+ }
694
+ const runningRoot = packageRootOf(
695
+ input.deps?.runningEntry ?? process.argv[1] ?? ""
696
+ );
697
+ let linked = false;
698
+ let why = "the running CLI install was not found";
699
+ if (runningRoot) {
700
+ try {
701
+ linkDependenciesFrom({
702
+ runningPackageRoot: runningRoot,
703
+ newPackage: pkg,
704
+ nodeModules: join(staging, "node_modules")
705
+ });
706
+ linked = true;
707
+ } catch (error) {
708
+ why = error instanceof Error ? error.message : String(error);
709
+ }
710
+ }
711
+ if (!linked) {
712
+ const tarballPath = join(staging, "package.tgz");
713
+ writeFileSync(tarballPath, input.tarball);
714
+ rmSync(join(staging, "node_modules"), { recursive: true, force: true });
715
+ const installed = await (input.deps?.npmInstall ?? defaultNpmInstall)({
716
+ prefix: staging,
717
+ tarballPath
718
+ });
719
+ rmSync(tarballPath, { force: true });
720
+ if (!installed.ok) {
721
+ throw new Error(
722
+ `could not install its dependencies (${why}; npm: ${installed.output.trim() || "failed"})`
723
+ );
724
+ }
725
+ }
726
+ await proven(staging);
727
+ rmSync(final, { recursive: true, force: true });
728
+ renameSync(staging, final);
729
+ } finally {
730
+ rmSync(staging, { recursive: true, force: true });
731
+ }
732
+ }
733
+ const current = {
734
+ version: published.version,
735
+ entry: entryIn(final),
736
+ integrity: published.integrity,
737
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
738
+ };
739
+ const existing = readCurrent(store);
740
+ if (!existing || !isNewer(existing.version, current.version)) {
741
+ writeJsonAtomic(join(store, "current.json"), current);
742
+ }
743
+ pruneVersions(
744
+ store,
745
+ [current.version, existing?.version].filter(Boolean)
746
+ );
747
+ return readCurrent(store) ?? current;
748
+ }
749
+ function pruneVersions(store, keep) {
750
+ const versionsDir = join(store, "versions");
751
+ let names;
752
+ try {
753
+ names = readdirSync(versionsDir);
754
+ } catch {
755
+ return;
756
+ }
757
+ const versions = names.filter((name) => parseVersion(name)).sort((a, b) => compareVersions(b, a));
758
+ for (const name of versions.slice(3)) {
759
+ if (keep.includes(name)) continue;
760
+ rmSync(join(versionsDir, name), { recursive: true, force: true });
761
+ }
762
+ for (const name of names) {
763
+ if (!name.startsWith(".staging-")) continue;
764
+ try {
765
+ if (Date.now() - statSync(join(versionsDir, name)).mtimeMs > 60 * 6e4) {
766
+ rmSync(join(versionsDir, name), { recursive: true, force: true });
767
+ }
768
+ } catch {
769
+ }
770
+ }
771
+ }
772
+ function withStoreLock(store, run) {
773
+ const lock = join(store, ".update.lock");
774
+ mkdirSync(store, { recursive: true, mode: 448 });
775
+ try {
776
+ mkdirSync(lock);
777
+ } catch {
778
+ try {
779
+ if (Date.now() - statSync(lock).mtimeMs < 15 * 6e4) return null;
780
+ rmSync(lock, { recursive: true, force: true });
781
+ mkdirSync(lock);
782
+ } catch {
783
+ return null;
784
+ }
785
+ }
786
+ return run().finally(() => rmSync(lock, { recursive: true, force: true }));
787
+ }
788
+ function backoffMs(failures) {
789
+ return Math.min(
790
+ 24 * 60 * 6e4,
791
+ 60 * 6e4 * 2 ** Math.max(0, failures - 1)
792
+ );
793
+ }
794
+ async function checkForUpdate(input) {
795
+ if (!input.enabled) return { kind: "disabled" };
796
+ const store = input.store ?? cliStoreDir();
797
+ const now = input.now ?? Date.now;
798
+ const installed = newerInstalledVersion({
799
+ selfVersion: input.selfVersion,
800
+ store
801
+ });
802
+ if (installed) return { kind: "ready", current: installed };
803
+ let published;
804
+ try {
805
+ published = await fetchLatestVersion({
806
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
807
+ ...input.registry ? { registry: input.registry } : {}
808
+ });
809
+ } catch (error) {
810
+ const message = error instanceof Error ? error.message : String(error);
811
+ updateState(store, (state2) => ({
812
+ ...state2,
813
+ lastCheckAt: new Date(now()).toISOString(),
814
+ lastError: message
815
+ }));
816
+ return { kind: "failed", version: "latest", error: message };
817
+ }
818
+ updateState(store, (state2) => ({
819
+ ...state2,
820
+ lastCheckAt: new Date(now()).toISOString(),
821
+ lastLatest: published.version,
822
+ lastError: null
823
+ }));
824
+ if (!isNewer(published.version, input.selfVersion)) {
825
+ return { kind: "up-to-date", latest: published.version };
826
+ }
827
+ const state = readUpdateState(store);
828
+ if (state.bad?.includes(published.version)) {
829
+ return { kind: "up-to-date", latest: published.version };
830
+ }
831
+ const failure = state.failures?.[published.version];
832
+ if (failure && Date.parse(failure.nextAttemptAt) > now()) {
833
+ return {
834
+ kind: "backoff",
835
+ version: published.version,
836
+ until: failure.nextAttemptAt
837
+ };
838
+ }
839
+ const result = await withStoreLock(store, async () => {
840
+ try {
841
+ const tarball = await downloadVerified({
842
+ published,
843
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
844
+ });
845
+ const current = await installVersion({
846
+ store,
847
+ published,
848
+ tarball,
849
+ ...input.deps ? { deps: input.deps } : {}
850
+ });
851
+ updateState(store, (s) => {
852
+ const { [published.version]: _, ...failures } = s.failures ?? {};
853
+ return { ...s, failures };
854
+ });
855
+ recordEvent(store, {
856
+ at: new Date(now()).toISOString(),
857
+ from: input.selfVersion,
858
+ to: published.version,
859
+ outcome: "installed"
860
+ });
861
+ return { kind: "ready", current };
862
+ } catch (error) {
863
+ const message = error instanceof Error ? error.message : String(error);
864
+ const count = (failure?.count ?? 0) + 1;
865
+ updateState(store, (s) => ({
866
+ ...s,
867
+ lastError: message,
868
+ failures: {
869
+ ...s.failures,
870
+ [published.version]: {
871
+ count,
872
+ nextAttemptAt: new Date(now() + backoffMs(count)).toISOString(),
873
+ error: message
874
+ }
875
+ }
876
+ }));
877
+ recordEvent(store, {
878
+ at: new Date(now()).toISOString(),
879
+ from: input.selfVersion,
880
+ to: published.version,
881
+ outcome: "failed",
882
+ detail: message.slice(0, 500)
883
+ });
884
+ return { kind: "failed", version: published.version, error: message };
885
+ }
886
+ });
887
+ return result ?? { kind: "busy" };
888
+ }
889
+ function nextCheckDelay(first, random = Math.random) {
890
+ if (first) return 3e4 + Math.floor(random() * 9e4);
891
+ return checkIntervalMs + Math.floor((random() * 2 - 1) * checkJitterMs);
892
+ }
893
+ async function superviseNewerVersion(input) {
894
+ const store = input.store ?? cliStoreDir();
895
+ let target = input.first;
896
+ let previous = input.selfVersion;
897
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
898
+ for (; ; ) {
899
+ input.log(`Auto-update: running kody ${target.version} (from ${previous}).`);
900
+ const startedAt = Date.now();
901
+ const child = (input.spawnFn ?? spawn)(
902
+ input.execPath ?? process.execPath,
903
+ [target.entry, ...input.args],
904
+ {
905
+ stdio: "inherit",
906
+ env: { ...input.env ?? process.env, [supervisedEnvVar]: "1" }
907
+ }
908
+ );
909
+ const forward = (signal) => () => {
910
+ try {
911
+ child.kill(signal);
912
+ } catch {
913
+ }
914
+ };
915
+ const handlers = signals.map((signal) => [signal, forward(signal)]);
916
+ for (const [signal, handler] of handlers) process.on(signal, handler);
917
+ const code = await new Promise((resolve) => {
918
+ child.once("error", (error) => {
919
+ input.log(
920
+ `Auto-update: could not start kody ${target.version}: ${error.message}`
921
+ );
922
+ resolve(1);
923
+ });
924
+ child.once(
925
+ "exit",
926
+ (exitCode, signal) => resolve(exitCode ?? (signal ? 128 + 15 : 1))
927
+ );
928
+ });
929
+ for (const [signal, handler] of handlers) process.off(signal, handler);
930
+ recordEvent(store, {
931
+ at: (/* @__PURE__ */ new Date()).toISOString(),
932
+ from: previous,
933
+ to: target.version,
934
+ outcome: "relaunched",
935
+ detail: `exited ${code}`
936
+ });
937
+ if (code === relaunchExitCode) {
938
+ const next = newerInstalledVersion({ selfVersion: target.version, store });
939
+ if (next) {
940
+ previous = target.version;
941
+ target = next;
942
+ }
943
+ continue;
944
+ }
945
+ if (code === startupRefusedExitCode) return { kind: "exit", code: 1 };
946
+ if (code !== 0 && Date.now() - startedAt < healthyAfterMs) {
947
+ const seconds = Math.round((Date.now() - startedAt) / 1e3);
948
+ recordFailedStart(
949
+ store,
950
+ target.version,
951
+ previous,
952
+ `exited ${code} after ${seconds}s`
953
+ );
954
+ input.log(
955
+ `Auto-update: kody ${target.version} exited (${code}) ${seconds}s after starting. Staying on ${input.selfVersion} and retrying it later.`
956
+ );
957
+ return { kind: "fallback" };
958
+ }
959
+ return { kind: "exit", code };
960
+ }
961
+ }
962
+ function startDaemonUpdater(input) {
963
+ let stopped = false;
964
+ let timer;
965
+ let running = null;
966
+ let lastEnabled = null;
967
+ let reported = "";
968
+ const schedule = (delay) => {
969
+ if (stopped) return;
970
+ timer = setTimeout(() => void tick(), delay);
971
+ timer.unref?.();
972
+ };
973
+ const waitForIdle = async (current) => {
974
+ const deadline = Date.now() + (input.maxIdleWaitMs ?? maxIdleWaitMs);
975
+ let said = false;
976
+ let forced = false;
977
+ while (!stopped) {
978
+ const busy = input.busy();
979
+ if (busy.runs === 0 && busy.background === 0) break;
980
+ if (Date.now() >= deadline) {
981
+ input.log(
982
+ `Auto-update: still busy after ${Math.round((input.maxIdleWaitMs ?? maxIdleWaitMs) / 36e5)}h; updating now. Runs in flight finish first; background commands stop.`
983
+ );
984
+ forced = true;
985
+ break;
986
+ }
987
+ if (!said) {
988
+ said = true;
989
+ input.log(
990
+ `Auto-update: kody ${current.version} is ready. Waiting for ${busy.runs} run(s) and ${busy.background} background command(s) to finish first.`
991
+ );
992
+ }
993
+ await new Promise((resolve) => {
994
+ const wait = setTimeout(resolve, input.idlePollMs ?? 15e3);
995
+ wait.unref?.();
996
+ });
997
+ }
998
+ if (stopped) return;
999
+ stopped = true;
1000
+ input.log(
1001
+ `Auto-update: updating kody ${input.selfVersion} to ${current.version}. New runs go to the next context in the chain until it is back.`
1002
+ );
1003
+ input.onReady(current, forced);
1004
+ };
1005
+ const check = async () => {
1006
+ const setting = await input.setting().catch(() => ({ enabled: true, source: "default" }));
1007
+ if (setting.enabled !== lastEnabled) {
1008
+ lastEnabled = setting.enabled;
1009
+ input.log(
1010
+ setting.enabled ? `Auto-update is on (kody ${input.selfVersion}; checks every ~4h). Turn it off with: kody daemon auto-update off` : `Auto-update is off${setting.source === "env" ? ` (${autoUpdateEnvVar})` : ""}. Turn it on with: kody daemon auto-update on`
1011
+ );
1012
+ }
1013
+ const result = await checkForUpdate({
1014
+ selfVersion: input.selfVersion,
1015
+ enabled: setting.enabled,
1016
+ ...input.store ? { store: input.store } : {},
1017
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
1018
+ ...input.deps ? { deps: input.deps } : {}
1019
+ });
1020
+ const line = result.kind === "failed" ? `Auto-update: could not update to ${result.version}: ${result.error}. Staying on ${input.selfVersion}; retrying later.` : result.kind === "backoff" ? `Auto-update: ${result.version} failed before; next try after ${result.until}.` : "";
1021
+ if (line && line !== reported) input.log(line);
1022
+ reported = line;
1023
+ return result;
1024
+ };
1025
+ const tick = async () => {
1026
+ if (stopped) return;
1027
+ running ??= check().finally(() => {
1028
+ running = null;
1029
+ });
1030
+ let result;
1031
+ try {
1032
+ result = await running;
1033
+ } catch (error) {
1034
+ input.log(
1035
+ `Auto-update: check failed: ${error instanceof Error ? error.message : String(error)}. Staying on ${input.selfVersion}; retrying later.`
1036
+ );
1037
+ schedule(input.intervalMs ?? nextCheckDelay(false));
1038
+ return;
1039
+ }
1040
+ if (result.kind === "ready" && !stopped) {
1041
+ await waitForIdle(result.current);
1042
+ return;
1043
+ }
1044
+ schedule(input.intervalMs ?? nextCheckDelay(false));
1045
+ };
1046
+ schedule(input.firstDelayMs ?? nextCheckDelay(true));
1047
+ return {
1048
+ stop: () => {
1049
+ stopped = true;
1050
+ clearTimeout(timer);
1051
+ },
1052
+ checkNow: async () => {
1053
+ running ??= check().finally(() => {
1054
+ running = null;
1055
+ });
1056
+ return await running;
1057
+ }
1058
+ };
1059
+ }
1060
+
252
1061
  // src/execution-context/daemon.ts
253
1062
  function runScopedFetch(input) {
254
1063
  const apiOrigin = new URL(input.apiUrl).origin;
@@ -340,6 +1149,7 @@ async function runDaemonConnection(input) {
340
1149
  const base = Array.isArray(input.capabilities.features) ? input.capabilities.features : [];
341
1150
  return {
342
1151
  ...input.capabilities,
1152
+ ...input.extraCapabilities?.(),
343
1153
  maxConcurrent,
344
1154
  features: [
345
1155
  ...base.filter((feature) => feature !== "fs"),
@@ -498,6 +1308,7 @@ async function runDaemonConnection(input) {
498
1308
  daemonMs: endedAt - committedAt
499
1309
  };
500
1310
  runs.delete(run.request.runId);
1311
+ if (input.activity) input.activity.runs = runs.size;
501
1312
  await send("run.result", {
502
1313
  runId: run.request.runId,
503
1314
  ...outcome,
@@ -557,6 +1368,7 @@ async function runDaemonConnection(input) {
557
1368
  abort: new AbortController(),
558
1369
  committed: false
559
1370
  });
1371
+ if (input.activity) input.activity.runs = runs.size;
560
1372
  await send("run.accept", { runId }, frame.seq);
561
1373
  return;
562
1374
  }
@@ -576,6 +1388,7 @@ async function runDaemonConnection(input) {
576
1388
  const run = runs.get(runId);
577
1389
  run?.abort.abort();
578
1390
  if (!run?.committed) runs.delete(runId);
1391
+ if (input.activity) input.activity.runs = runs.size;
579
1392
  if (frame.t === "run.cancel")
580
1393
  await send("run.cancel.ack", { runId }, frame.seq);
581
1394
  return;
@@ -641,6 +1454,7 @@ async function runDaemonConnection(input) {
641
1454
  clearTimeout(pongTimer);
642
1455
  clearTimeout(welcomeTimer);
643
1456
  clearTimeout(settleTimer);
1457
+ clearInterval(holdTimer);
644
1458
  unsubscribeFs?.();
645
1459
  input.signal?.removeEventListener("abort", shutdown);
646
1460
  input.drainSignal?.removeEventListener("abort", drain);
@@ -666,9 +1480,17 @@ async function runDaemonConnection(input) {
666
1480
  const shutdown = () => closeAndSettle(1e3, "shutdown");
667
1481
  if (input.signal?.aborted) shutdown();
668
1482
  input.signal?.addEventListener("abort", shutdown, { once: true });
1483
+ let holdTimer;
669
1484
  closeWhenDrained = () => {
670
1485
  if (!input.drainSignal?.aborted) return;
671
1486
  if ([...runs.values()].some((run) => run.committed)) return;
1487
+ if (input.drainHold?.()) {
1488
+ holdTimer ??= setInterval(
1489
+ () => closeWhenDrained(),
1490
+ input.drainHoldPollMs ?? 5e3
1491
+ );
1492
+ return;
1493
+ }
672
1494
  closeAndSettle(1e3, "shutdown");
673
1495
  };
674
1496
  const drain = () => {
@@ -738,6 +1560,9 @@ async function runDaemon(input) {
738
1560
  const closed = await runDaemonConnection(input);
739
1561
  if (closed.reason === "revoked") return "revoked";
740
1562
  if (stopping()) return "shutdown";
1563
+ if (closed.code === 1012 && closed.reason === "replaced") {
1564
+ return "replaced";
1565
+ }
741
1566
  input.log(
742
1567
  `Disconnected (${closed.code}${closed.reason ? ` ${closed.reason}` : ""}). Reconnecting.`
743
1568
  );
@@ -781,35 +1606,218 @@ function abortableDelay(ms, signal) {
781
1606
  });
782
1607
  }
783
1608
 
1609
+ // src/execution-context/runner-lock.ts
1610
+ import { execFileSync } from "node:child_process";
1611
+ import { randomBytes as randomBytes2 } from "node:crypto";
1612
+ import {
1613
+ linkSync,
1614
+ mkdirSync as mkdirSync2,
1615
+ readFileSync as readFileSync2,
1616
+ renameSync as renameSync2,
1617
+ rmSync as rmSync2,
1618
+ statSync as statSync2,
1619
+ writeFileSync as writeFileSync2
1620
+ } from "node:fs";
1621
+ import { uptime } from "node:os";
1622
+ import { dirname as dirname2 } from "node:path";
1623
+ import psList from "ps-list";
1624
+ var launcherEnvVar = "KODY_DAEMON_LAUNCHER";
1625
+ var unreadableGraceMs = 1e4;
1626
+ function lockPathFor(statePath) {
1627
+ return statePath.replace(/daemon\.json$/, "daemon.lock");
1628
+ }
1629
+ function isAlive(pid) {
1630
+ if (!Number.isInteger(pid) || pid <= 0) return false;
1631
+ try {
1632
+ process.kill(pid, 0);
1633
+ return true;
1634
+ } catch (error) {
1635
+ return error.code === "EPERM";
1636
+ }
1637
+ }
1638
+ function commandOf(pid) {
1639
+ if (process.platform === "win32") return null;
1640
+ try {
1641
+ return execFileSync("ps", ["-o", "command=", "-p", String(pid)], {
1642
+ encoding: "utf8",
1643
+ stdio: ["ignore", "pipe", "ignore"],
1644
+ timeout: 2e3
1645
+ }).trim();
1646
+ } catch {
1647
+ return null;
1648
+ }
1649
+ }
1650
+ function isLiveHolder(holder, check = {}) {
1651
+ if (!(check.isAlive ?? isAlive)(holder.pid)) return false;
1652
+ if (holder.pid === process.pid) return true;
1653
+ const startedAt = Date.parse(holder.startedAt);
1654
+ const bootTimeMs = check.bootTimeMs ?? Date.now() - uptime() * 1e3;
1655
+ if (Number.isFinite(startedAt) && startedAt < bootTimeMs - 6e4) {
1656
+ return false;
1657
+ }
1658
+ const command = (check.commandOf ?? commandOf)(holder.pid);
1659
+ return command === null || /\bdaemon\b/.test(command);
1660
+ }
1661
+ function readLock(path) {
1662
+ let text;
1663
+ try {
1664
+ text = readFileSync2(path, "utf8");
1665
+ } catch (error) {
1666
+ return error.code === "ENOENT" ? "missing" : "unreadable";
1667
+ }
1668
+ try {
1669
+ const holder = JSON.parse(text);
1670
+ return typeof holder?.pid === "number" ? holder : "malformed";
1671
+ } catch {
1672
+ return "malformed";
1673
+ }
1674
+ }
1675
+ function readHolder(path) {
1676
+ const read = readLock(path);
1677
+ return typeof read === "object" ? read : null;
1678
+ }
1679
+ function sameHolder(a, b) {
1680
+ return a.pid === b.pid && a.startedAt === b.startedAt;
1681
+ }
1682
+ function runnerLockHolder(path, check = {}) {
1683
+ const holder = readHolder(path);
1684
+ return holder && isLiveHolder(holder, check) ? holder : null;
1685
+ }
1686
+ function acquireRunnerLock(path, info, check = {}) {
1687
+ const mine = { ...info, pid: info.pid ?? process.pid };
1688
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
1689
+ const unique = () => `${process.pid}-${randomBytes2(4).toString("hex")}`;
1690
+ for (let attempt = 0; attempt < 3; attempt++) {
1691
+ const temp = `${path}.${unique()}.tmp`;
1692
+ writeFileSync2(temp, `${JSON.stringify(mine)}
1693
+ `, { mode: 384 });
1694
+ try {
1695
+ linkSync(temp, path);
1696
+ return {
1697
+ ok: true,
1698
+ release: () => {
1699
+ const holder3 = readHolder(path);
1700
+ if (holder3 && sameHolder(holder3, mine)) rmSync2(path, { force: true });
1701
+ }
1702
+ };
1703
+ } catch (error) {
1704
+ if (error.code !== "EEXIST") throw error;
1705
+ } finally {
1706
+ rmSync2(temp, { force: true });
1707
+ }
1708
+ const read = readLock(path);
1709
+ if (read === "missing") continue;
1710
+ const holder2 = typeof read === "object" ? read : null;
1711
+ if (read === "unreadable") {
1712
+ return {
1713
+ ok: false,
1714
+ holder: {
1715
+ pid: 0,
1716
+ version: "unknown",
1717
+ launcher: "terminal",
1718
+ startedAt: "unreadable"
1719
+ }
1720
+ };
1721
+ }
1722
+ if (!holder2) {
1723
+ let ageMs = Infinity;
1724
+ try {
1725
+ ageMs = Date.now() - statSync2(path).mtimeMs;
1726
+ } catch {
1727
+ continue;
1728
+ }
1729
+ if (ageMs < unreadableGraceMs) {
1730
+ return {
1731
+ ok: false,
1732
+ holder: {
1733
+ pid: 0,
1734
+ version: "unknown",
1735
+ launcher: "terminal",
1736
+ startedAt: new Date(Date.now() - ageMs).toISOString()
1737
+ }
1738
+ };
1739
+ }
1740
+ } else if (holder2.pid !== mine.pid && isLiveHolder(holder2, check)) {
1741
+ return { ok: false, holder: holder2 };
1742
+ }
1743
+ const aside = `${path}.${unique()}.stale`;
1744
+ try {
1745
+ renameSync2(path, aside);
1746
+ } catch {
1747
+ continue;
1748
+ }
1749
+ const moved = readHolder(aside);
1750
+ if (moved && (!holder2 || !sameHolder(moved, holder2)) && moved.pid !== mine.pid && isLiveHolder(moved, check)) {
1751
+ try {
1752
+ linkSync(aside, path);
1753
+ } catch {
1754
+ }
1755
+ rmSync2(aside, { force: true });
1756
+ return { ok: false, holder: moved };
1757
+ }
1758
+ rmSync2(aside, { force: true });
1759
+ }
1760
+ const holder = readHolder(path);
1761
+ if (holder) return { ok: false, holder };
1762
+ throw new Error(`Could not take the runner lock ${path}.`);
1763
+ }
1764
+ function describeLauncher(launcher) {
1765
+ if (launcher === "systemd") return "the systemd service";
1766
+ if (launcher === "launchd") return "the launchd service";
1767
+ if (launcher === "desktop") return "the Kody desktop app";
1768
+ return "a terminal";
1769
+ }
1770
+ function describeHolder(holder) {
1771
+ if (holder.pid === 0 && holder.startedAt === "unreadable") {
1772
+ return "a daemon of another user holds the lock (this user cannot read it)";
1773
+ }
1774
+ if (holder.pid === 0) {
1775
+ return `another daemon is taking the lock right now (since ${holder.startedAt})`;
1776
+ }
1777
+ return `pid ${holder.pid}, kody ${holder.version}, started by ${describeLauncher(holder.launcher)} at ${holder.startedAt}`;
1778
+ }
1779
+ async function otherLocalDaemons(input) {
1780
+ let processes;
1781
+ try {
1782
+ processes = await (input.listProcesses ?? psList)();
1783
+ } catch {
1784
+ return [];
1785
+ }
1786
+ const skip = /* @__PURE__ */ new Set([process.pid, process.ppid, ...input.exclude ?? []]);
1787
+ return processes.filter(
1788
+ (entry) => !skip.has(entry.pid) && typeof entry.cmd === "string" && /\bdaemon\b/.test(entry.cmd) && entry.cmd.includes(input.ecid) && /kody|@kodycodes/.test(entry.cmd)
1789
+ );
1790
+ }
1791
+
784
1792
  // src/execution-context/keystore.ts
785
1793
  import {
786
1794
  createCipheriv,
787
1795
  createDecipheriv,
788
- randomBytes,
1796
+ randomBytes as randomBytes3,
789
1797
  scryptSync
790
1798
  } from "node:crypto";
791
1799
  import {
792
1800
  chmodSync,
793
- existsSync,
794
- mkdirSync,
795
- readFileSync,
796
- renameSync,
797
- writeFileSync
1801
+ existsSync as existsSync2,
1802
+ mkdirSync as mkdirSync3,
1803
+ readFileSync as readFileSync3,
1804
+ renameSync as renameSync3,
1805
+ writeFileSync as writeFileSync3
798
1806
  } from "node:fs";
799
- import { dirname, join } from "node:path";
1807
+ import { dirname as dirname3, join as join2 } from "node:path";
800
1808
  import { Entry } from "@napi-rs/keyring";
801
1809
  var contextKeyPassphraseEnvVar = "KODY_CONTEXT_KEY_PASSPHRASE";
802
1810
  function contextsDir(apiUrl) {
803
- return join(dirname(apiTokenFileStorePath(apiUrl)), "contexts");
1811
+ return join2(dirname3(apiTokenFileStorePath(apiUrl)), "contexts");
804
1812
  }
805
1813
  function contextDir(apiUrl, ecid) {
806
1814
  if (!/^ec_[A-Za-z0-9_-]+$/.test(ecid)) {
807
1815
  throw new Error(`Not an execution context id: ${ecid}`);
808
1816
  }
809
- return join(contextsDir(apiUrl), ecid);
1817
+ return join2(contextsDir(apiUrl), ecid);
810
1818
  }
811
1819
  function contextWorkersDir(apiUrl, ecid) {
812
- return join(contextDir(apiUrl, ecid), "workers");
1820
+ return join2(contextDir(apiUrl, ecid), "workers");
813
1821
  }
814
1822
  function resolveWrappingKey(input) {
815
1823
  const env = input.env ?? process.env;
@@ -847,7 +1855,7 @@ function resolveWrappingKey(input) {
847
1855
  "The key for this execution context is missing from the OS keyring. Re-register the machine with `kody context register`."
848
1856
  );
849
1857
  }
850
- const fresh = randomBytes(32);
1858
+ const fresh = randomBytes3(32);
851
1859
  try {
852
1860
  entry.setPassword(fresh.toString("base64url"));
853
1861
  } catch {
@@ -858,24 +1866,24 @@ function resolveWrappingKey(input) {
858
1866
  };
859
1867
  }
860
1868
  function fileWrappingKeyPath(apiUrl, ecid) {
861
- return join(contextDir(apiUrl, ecid), "wrapping-key");
1869
+ return join2(contextDir(apiUrl, ecid), "wrapping-key");
862
1870
  }
863
1871
  function fileWrappingKey(input) {
864
1872
  const path = fileWrappingKeyPath(input.apiUrl, input.ecid);
865
1873
  return {
866
1874
  kind: "file",
867
1875
  key: () => {
868
- if (existsSync(path)) {
869
- return Buffer.from(readFileSync(path, "utf8").trim(), "base64url");
1876
+ if (existsSync2(path)) {
1877
+ return Buffer.from(readFileSync3(path, "utf8").trim(), "base64url");
870
1878
  }
871
1879
  if (!input.create) {
872
1880
  throw new Error(
873
1881
  `The file key for this execution context is missing (${path}). Re-register the machine with \`kody connect\`.`
874
1882
  );
875
1883
  }
876
- const fresh = randomBytes(32);
877
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
878
- writeFileSync(path, `${fresh.toString("base64url")}
1884
+ const fresh = randomBytes3(32);
1885
+ mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1886
+ writeFileSync3(path, `${fresh.toString("base64url")}
879
1887
  `, { mode: 384 });
880
1888
  chmodSync(path, 384);
881
1889
  return fresh;
@@ -885,7 +1893,7 @@ function fileWrappingKey(input) {
885
1893
  function storedKeyWrap(apiUrl, ecid) {
886
1894
  try {
887
1895
  const file = JSON.parse(
888
- readFileSync(join(contextDir(apiUrl, ecid), "key.enc"), "utf8")
1896
+ readFileSync3(join2(contextDir(apiUrl, ecid), "key.enc"), "utf8")
889
1897
  );
890
1898
  return file.wrap;
891
1899
  } catch {
@@ -901,15 +1909,15 @@ function wrappingKeyForStoredContext(input) {
901
1909
  }
902
1910
  function rewrapContextKey(input) {
903
1911
  const dir = contextDir(input.apiUrl, input.ecid);
904
- const keyPath = join(dir, "key.enc");
905
- const file = JSON.parse(readFileSync(keyPath, "utf8"));
1912
+ const keyPath = join2(dir, "key.enc");
1913
+ const file = JSON.parse(readFileSync3(keyPath, "utf8"));
906
1914
  const privateJwk = decryptPrivateKey(file, input.from);
907
1915
  const next = `${keyPath}.next`;
908
- writeFileSync(next, JSON.stringify(encryptPrivateKey(privateJwk, input.to)), {
1916
+ writeFileSync3(next, JSON.stringify(encryptPrivateKey(privateJwk, input.to)), {
909
1917
  mode: 384
910
1918
  });
911
1919
  chmodSync(next, 384);
912
- renameSync(next, keyPath);
1920
+ renameSync3(next, keyPath);
913
1921
  }
914
1922
  function noWrappingKeyError() {
915
1923
  return new Error(
@@ -917,9 +1925,9 @@ function noWrappingKeyError() {
917
1925
  );
918
1926
  }
919
1927
  function encryptPrivateKey(privateJwk, wrapping) {
920
- const salt = wrapping.kind === "passphrase" ? randomBytes(16) : null;
1928
+ const salt = wrapping.kind === "passphrase" ? randomBytes3(16) : null;
921
1929
  const key = wrapping.key(salt);
922
- const iv = randomBytes(12);
1930
+ const iv = randomBytes3(12);
923
1931
  const cipher = createCipheriv("aes-256-gcm", key, iv);
924
1932
  const data = Buffer.concat([
925
1933
  cipher.update(JSON.stringify(privateJwk), "utf8"),
@@ -963,16 +1971,16 @@ function decryptPrivateKey(file, wrapping) {
963
1971
  }
964
1972
  function saveContext(input) {
965
1973
  const dir = contextDir(input.context.apiUrl, input.context.ecid);
966
- mkdirSync(dir, { recursive: true, mode: 448 });
967
- const keyPath = join(dir, "key.enc");
968
- writeFileSync(
1974
+ mkdirSync3(dir, { recursive: true, mode: 448 });
1975
+ const keyPath = join2(dir, "key.enc");
1976
+ writeFileSync3(
969
1977
  keyPath,
970
1978
  JSON.stringify(encryptPrivateKey(input.privateJwk, input.wrapping)),
971
1979
  { mode: 384 }
972
1980
  );
973
1981
  chmodSync(keyPath, 384);
974
- writeFileSync(
975
- join(dir, "context.json"),
1982
+ writeFileSync3(
1983
+ join2(dir, "context.json"),
976
1984
  `${JSON.stringify(input.context, null, 2)}
977
1985
  `,
978
1986
  { mode: 384 }
@@ -981,7 +1989,7 @@ function saveContext(input) {
981
1989
  function readStoredContext(apiUrl, ecid) {
982
1990
  try {
983
1991
  return JSON.parse(
984
- readFileSync(join(contextDir(apiUrl, ecid), "context.json"), "utf8")
1992
+ readFileSync3(join2(contextDir(apiUrl, ecid), "context.json"), "utf8")
985
1993
  );
986
1994
  } catch {
987
1995
  return null;
@@ -990,30 +1998,30 @@ function readStoredContext(apiUrl, ecid) {
990
1998
  function loadContext(input) {
991
1999
  const dir = contextDir(input.apiUrl, input.ecid);
992
2000
  const context = JSON.parse(
993
- readFileSync(join(dir, "context.json"), "utf8")
2001
+ readFileSync3(join2(dir, "context.json"), "utf8")
994
2002
  );
995
- const file = JSON.parse(readFileSync(join(dir, "key.enc"), "utf8"));
2003
+ const file = JSON.parse(readFileSync3(join2(dir, "key.enc"), "utf8"));
996
2004
  return { context, privateJwk: decryptPrivateKey(file, input.wrapping) };
997
2005
  }
998
2006
 
999
2007
  // src/execution-context/service-commands.ts
1000
- import { spawn, spawnSync } from "node:child_process";
1001
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "node:fs";
2008
+ import { spawn as spawn2, spawnSync } from "node:child_process";
2009
+ import { existsSync as existsSync4, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "node:fs";
1002
2010
  import { createInterface } from "node:readline";
1003
2011
  import { setTimeout as sleep } from "node:timers/promises";
1004
2012
 
1005
2013
  // src/execution-context/service.ts
1006
- import { execFileSync } from "node:child_process";
2014
+ import { execFileSync as execFileSync2 } from "node:child_process";
1007
2015
  import {
1008
- existsSync as existsSync2,
1009
- mkdirSync as mkdirSync2,
1010
- readFileSync as readFileSync2,
2016
+ existsSync as existsSync3,
2017
+ mkdirSync as mkdirSync4,
2018
+ readFileSync as readFileSync4,
1011
2019
  realpathSync,
1012
- rmSync,
1013
- writeFileSync as writeFileSync2
2020
+ rmSync as rmSync3,
2021
+ writeFileSync as writeFileSync4
1014
2022
  } from "node:fs";
1015
- import { homedir, tmpdir, userInfo } from "node:os";
1016
- import { delimiter, dirname as dirname2, join as join2, sep } from "node:path";
2023
+ import { homedir as homedir2, tmpdir, userInfo } from "node:os";
2024
+ import { delimiter as delimiter2, dirname as dirname4, join as join3, sep as sep2 } from "node:path";
1017
2025
  var serviceEnvVar = "KODY_DAEMON_SERVICE";
1018
2026
  var stayStoppedExitCode = 0;
1019
2027
  function serviceManagerFor(platform2 = process.platform) {
@@ -1029,25 +2037,25 @@ function launchdLabel(ecid) {
1029
2037
  return `codes.kody.daemon.${ecid}`;
1030
2038
  }
1031
2039
  function servicePaths(input) {
1032
- const home = input.home ?? homedir();
2040
+ const home = input.home ?? homedir2();
1033
2041
  const env = input.env ?? process.env;
1034
2042
  const dir = contextDir(input.apiUrl, input.ecid);
1035
2043
  return {
1036
2044
  manager: input.manager,
1037
- unitPath: input.manager === "systemd" ? join2(
1038
- env.XDG_CONFIG_HOME || join2(home, ".config"),
2045
+ unitPath: input.manager === "systemd" ? join3(
2046
+ env.XDG_CONFIG_HOME || join3(home, ".config"),
1039
2047
  "systemd",
1040
2048
  "user",
1041
2049
  `${serviceName(input.ecid)}.service`
1042
- ) : join2(
2050
+ ) : join3(
1043
2051
  home,
1044
2052
  "Library",
1045
2053
  "LaunchAgents",
1046
2054
  `${launchdLabel(input.ecid)}.plist`
1047
2055
  ),
1048
- logPath: join2(dir, "daemon.log"),
1049
- statePath: join2(dir, "daemon.json"),
1050
- stoppedPath: join2(dir, "stopped.json"),
2056
+ logPath: join3(dir, "daemon.log"),
2057
+ statePath: join3(dir, "daemon.json"),
2058
+ stoppedPath: join3(dir, "stopped.json"),
1051
2059
  workingDir: dir
1052
2060
  };
1053
2061
  }
@@ -1058,7 +2066,7 @@ function ephemeralRuntimeReason(entryPath, tmp = tmpdir()) {
1058
2066
  return "pnpm dlx";
1059
2067
  }
1060
2068
  if (parts.some((part) => part.startsWith("bunx-"))) return "bunx";
1061
- if (tmp && entryPath.startsWith(tmp + sep)) return "a temporary directory";
2069
+ if (tmp && entryPath.startsWith(tmp + sep2)) return "a temporary directory";
1062
2070
  return null;
1063
2071
  }
1064
2072
  var npxRefusal = (how) => `This kody CLI is running from ${how}, which is deleted after the command ends, so a background service could not start it again. Install the CLI globally first:
@@ -1088,7 +2096,7 @@ function daemonArgs(input) {
1088
2096
  function servicePath(input) {
1089
2097
  const platform2 = input.platform ?? process.platform;
1090
2098
  const dirs = [
1091
- dirname2(input.node),
2099
+ dirname4(input.node),
1092
2100
  ...platform2 === "darwin" ? ["/opt/homebrew/bin"] : [],
1093
2101
  "/usr/local/bin",
1094
2102
  "/usr/bin",
@@ -1096,7 +2104,7 @@ function servicePath(input) {
1096
2104
  "/usr/sbin",
1097
2105
  "/sbin"
1098
2106
  ];
1099
- return [...new Set(dirs)].join(platform2 === "win32" ? ";" : delimiter);
2107
+ return [...new Set(dirs)].join(platform2 === "win32" ? ";" : delimiter2);
1100
2108
  }
1101
2109
  function serviceEnvironment(input) {
1102
2110
  const env = input.env ?? process.env;
@@ -1214,7 +2222,7 @@ function programInUnit(text, manager) {
1214
2222
  }
1215
2223
  var runCommand = (command, args) => {
1216
2224
  try {
1217
- const stdout = execFileSync(command, args, {
2225
+ const stdout = execFileSync2(command, args, {
1218
2226
  encoding: "utf8",
1219
2227
  stdio: ["ignore", "pipe", "pipe"],
1220
2228
  timeout: 3e4
@@ -1237,14 +2245,14 @@ function launchdTarget(ecid) {
1237
2245
  }
1238
2246
  function readJson(path) {
1239
2247
  try {
1240
- return JSON.parse(readFileSync2(path, "utf8"));
2248
+ return JSON.parse(readFileSync4(path, "utf8"));
1241
2249
  } catch {
1242
2250
  return null;
1243
2251
  }
1244
2252
  }
1245
2253
  function writeJson(path, value) {
1246
- mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
1247
- writeFileSync2(path, `${JSON.stringify(value, null, 2)}
2254
+ mkdirSync4(dirname4(path), { recursive: true, mode: 448 });
2255
+ writeFileSync4(path, `${JSON.stringify(value, null, 2)}
1248
2256
  `, { mode: 384 });
1249
2257
  }
1250
2258
  function lingerCommand(user = userInfo().username) {
@@ -1287,10 +2295,10 @@ function managerState(input) {
1287
2295
  }
1288
2296
  function serviceStatus(input) {
1289
2297
  const run = input.run ?? runCommand;
1290
- const exists = input.fileExists ?? existsSync2;
2298
+ const exists = input.fileExists ?? existsSync3;
1291
2299
  const readText2 = input.readText ?? ((path) => {
1292
2300
  try {
1293
- return readFileSync2(path, "utf8");
2301
+ return readFileSync4(path, "utf8");
1294
2302
  } catch {
1295
2303
  return null;
1296
2304
  }
@@ -1442,7 +2450,7 @@ function serviceStatus(input) {
1442
2450
  const runtime = readJson(paths.statePath);
1443
2451
  if (state.running && runtime && (state.pid === null || runtime.pid === state.pid)) {
1444
2452
  base.runningVersion = runtime.version;
1445
- if (runtime.version !== input.cliVersion) {
2453
+ if (compareVersions(runtime.version, input.cliVersion) < 0) {
1446
2454
  base.problems.push({
1447
2455
  code: "restart-pending",
1448
2456
  message: `The service runs kody ${runtime.version}; this CLI is ${input.cliVersion}.`,
@@ -1482,14 +2490,14 @@ function installService(input) {
1482
2490
  const warnings = [];
1483
2491
  let previous = null;
1484
2492
  try {
1485
- previous = readFileSync2(input.paths.unitPath, "utf8");
2493
+ previous = readFileSync4(input.paths.unitPath, "utf8");
1486
2494
  } catch {
1487
2495
  }
1488
2496
  const changed = previous !== input.unit;
1489
- mkdirSync2(dirname2(input.paths.unitPath), { recursive: true });
1490
- mkdirSync2(input.paths.workingDir, { recursive: true, mode: 448 });
1491
- if (changed) writeFileSync2(input.paths.unitPath, input.unit, { mode: 420 });
1492
- rmSync(input.paths.stoppedPath, { force: true });
2497
+ mkdirSync4(dirname4(input.paths.unitPath), { recursive: true });
2498
+ mkdirSync4(input.paths.workingDir, { recursive: true, mode: 448 });
2499
+ if (changed) writeFileSync4(input.paths.unitPath, input.unit, { mode: 420 });
2500
+ rmSync3(input.paths.stoppedPath, { force: true });
1493
2501
  const must = (command, args, what) => {
1494
2502
  const result = run(command, args);
1495
2503
  if (!result.ok) {
@@ -1550,17 +2558,34 @@ function restartService(input) {
1550
2558
  if (!result.ok)
1551
2559
  throw new Error(`Could not restart the service: ${result.stderr.trim()}`);
1552
2560
  }
2561
+ function startService(input) {
2562
+ const run = input.run ?? runCommand;
2563
+ const unit = `${serviceName(input.ecid)}.service`;
2564
+ const result = input.manager === "systemd" ? (run("systemctl", ["--user", "reset-failed", unit]), run("systemctl", ["--user", "start", unit])) : (run("launchctl", ["enable", launchdTarget(input.ecid)]), run("launchctl", ["kickstart", launchdTarget(input.ecid)]));
2565
+ if (!result.ok)
2566
+ throw new Error(`Could not start the service: ${result.stderr.trim()}`);
2567
+ }
2568
+ function stopService(input) {
2569
+ const run = input.run ?? runCommand;
2570
+ const result = input.manager === "systemd" ? run("systemctl", [
2571
+ "--user",
2572
+ "stop",
2573
+ `${serviceName(input.ecid)}.service`
2574
+ ]) : run("launchctl", ["kill", "SIGTERM", launchdTarget(input.ecid)]);
2575
+ if (!result.ok)
2576
+ throw new Error(`Could not stop the service: ${result.stderr.trim()}`);
2577
+ }
1553
2578
  function uninstallService(input) {
1554
2579
  const run = input.run ?? runCommand;
1555
2580
  if (input.paths.manager === "systemd") {
1556
2581
  const unit = `${serviceName(input.ecid)}.service`;
1557
2582
  run("systemctl", ["--user", "disable", "--now", unit]);
1558
- rmSync(input.paths.unitPath, { force: true });
2583
+ rmSync3(input.paths.unitPath, { force: true });
1559
2584
  run("systemctl", ["--user", "daemon-reload"]);
1560
2585
  run("systemctl", ["--user", "reset-failed", unit]);
1561
2586
  } else {
1562
2587
  run("launchctl", ["bootout", launchdTarget(input.ecid)]);
1563
- rmSync(input.paths.unitPath, { force: true });
2588
+ rmSync3(input.paths.unitPath, { force: true });
1564
2589
  }
1565
2590
  }
1566
2591
  function disableOwnService(input) {
@@ -1577,10 +2602,10 @@ function disableOwnService(input) {
1577
2602
  }
1578
2603
  function rotateLog(path, maxBytes = 10 * 1024 * 1024) {
1579
2604
  try {
1580
- const text = readFileSync2(path);
2605
+ const text = readFileSync4(path);
1581
2606
  if (text.byteLength <= maxBytes) return;
1582
- writeFileSync2(`${path}.1`, text, { mode: 384 });
1583
- writeFileSync2(path, "", { mode: 384 });
2607
+ writeFileSync4(`${path}.1`, text, { mode: 384 });
2608
+ writeFileSync4(path, "", { mode: 384 });
1584
2609
  } catch {
1585
2610
  }
1586
2611
  }
@@ -1606,7 +2631,7 @@ function terminalConfirm() {
1606
2631
  }
1607
2632
  function storedContextIds(apiUrl) {
1608
2633
  try {
1609
- return readdirSync(contextsDir(apiUrl)).filter((entry) => entry.startsWith("ec_")).sort();
2634
+ return readdirSync2(contextsDir(apiUrl)).filter((entry) => entry.startsWith("ec_")).sort();
1610
2635
  } catch {
1611
2636
  return [];
1612
2637
  }
@@ -1642,7 +2667,7 @@ function maxConcurrentInUnit(text) {
1642
2667
  }
1643
2668
  function readText(path) {
1644
2669
  try {
1645
- return readFileSync3(path, "utf8");
2670
+ return readFileSync5(path, "utf8");
1646
2671
  } catch {
1647
2672
  return null;
1648
2673
  }
@@ -1668,7 +2693,7 @@ function expectedUnit(env, ecid, manager, maxConcurrent) {
1668
2693
  }
1669
2694
  function runtimeState(path) {
1670
2695
  try {
1671
- return JSON.parse(readFileSync3(path, "utf8"));
2696
+ return JSON.parse(readFileSync5(path, "utf8"));
1672
2697
  } catch {
1673
2698
  return null;
1674
2699
  }
@@ -1749,7 +2774,7 @@ async function installDaemonService(env, input) {
1749
2774
  unit,
1750
2775
  paths,
1751
2776
  ecid: input.ecid,
1752
- restart: before !== null && before.version !== env.clientVersion,
2777
+ restart: before !== null && compareVersions(before.version, env.clientVersion) < 0,
1753
2778
  ...env.run ? { run: env.run } : {}
1754
2779
  });
1755
2780
  for (const warning of result.warnings) env.write(`${warning}
@@ -1786,7 +2811,7 @@ async function waitForStart(env, statePath, before) {
1786
2811
  const deadline = Date.now() + (env.startupWaitMs ?? 1e4);
1787
2812
  while (Date.now() < deadline) {
1788
2813
  const state = runtimeState(statePath);
1789
- if (state && state.version === env.clientVersion && (!before || state.pid !== before.pid || state.startedAt !== before.startedAt)) {
2814
+ if (state && compareVersions(state.version, env.clientVersion) >= 0 && (!before || state.pid !== before.pid || state.startedAt !== before.startedAt)) {
1790
2815
  return true;
1791
2816
  }
1792
2817
  await sleep(250);
@@ -1798,6 +2823,138 @@ function tail(path, lines) {
1798
2823
  if (!text) return "";
1799
2824
  return text.trimEnd().split("\n").slice(-lines).join("\n");
1800
2825
  }
2826
+ async function autoUpdateStatus(clientVersion) {
2827
+ const setting = autoUpdateSetting(await readLocalPolicy().catch(() => null));
2828
+ const store = cliStoreDir();
2829
+ const state = readUpdateState(store);
2830
+ const current = readCurrent(store);
2831
+ return {
2832
+ enabled: setting.enabled,
2833
+ source: setting.source,
2834
+ cliVersion: clientVersion,
2835
+ installedVersion: current?.version ?? null,
2836
+ latestVersion: state.lastLatest ?? null,
2837
+ lastCheckAt: state.lastCheckAt ?? null,
2838
+ lastError: state.lastError ?? null,
2839
+ store,
2840
+ recent: (state.history ?? []).slice(-5)
2841
+ };
2842
+ }
2843
+ function formatAutoUpdateLine(status) {
2844
+ const lines = [
2845
+ status.enabled ? ` Auto-update: on. The daemon checks npm every ~4h and moves onto new versions after runs finish (off: kody daemon auto-update off).` : ` Auto-update: off${status.source === "env" ? " (KODY_DAEMON_AUTO_UPDATE)" : ""}. Turn it on with: kody daemon auto-update on`
2846
+ ];
2847
+ if (status.lastCheckAt) {
2848
+ lines.push(
2849
+ ` Last check: ${status.lastCheckAt}${status.latestVersion ? `, latest ${status.latestVersion}` : ""}${status.installedVersion ? `, installed ${status.installedVersion}` : ""}`
2850
+ );
2851
+ }
2852
+ if (status.lastError) lines.push(` Last error: ${status.lastError}`);
2853
+ return lines.join("\n");
2854
+ }
2855
+ function runnerFor(apiUrl, ecid) {
2856
+ const statePath = servicePaths({
2857
+ apiUrl,
2858
+ ecid,
2859
+ manager: serviceManagerFor() ?? "systemd"
2860
+ }).statePath;
2861
+ return runnerLockHolder(lockPathFor(statePath));
2862
+ }
2863
+ async function startOrStopRunner(env, input) {
2864
+ const installed = input.manager !== null && existsSync4(
2865
+ servicePaths({
2866
+ apiUrl: env.apiUrl,
2867
+ ecid: input.ecid,
2868
+ manager: input.manager
2869
+ }).unitPath
2870
+ );
2871
+ const runner = runnerFor(env.apiUrl, input.ecid);
2872
+ const say = (text, extra = {}) => env.write(
2873
+ env.json ? `${JSON.stringify({ ok: true, ecid: input.ecid, message: text, ...extra })}
2874
+ ` : `${text}
2875
+ `
2876
+ );
2877
+ if (input.start) {
2878
+ if (installed && input.manager) {
2879
+ startService({
2880
+ manager: input.manager,
2881
+ ecid: input.ecid,
2882
+ ...env.run ? { run: env.run } : {}
2883
+ });
2884
+ say("Started the kody daemon service.", { service: input.manager });
2885
+ return 0;
2886
+ }
2887
+ if (runner) {
2888
+ say(`Already running (${describeHolder(runner)}).`, { runner });
2889
+ return 0;
2890
+ }
2891
+ throw new Error(
2892
+ "No kody daemon service is installed for this context. Install one with `kody daemon install`, or run `kody daemon` in a terminal."
2893
+ );
2894
+ }
2895
+ if (installed && input.manager) {
2896
+ stopService({
2897
+ manager: input.manager,
2898
+ ecid: input.ecid,
2899
+ ...env.run ? { run: env.run } : {}
2900
+ });
2901
+ const other = runner && runner.pid > 0 && runner.launcher !== input.manager ? runner : null;
2902
+ if (other) process.kill(other.pid, "SIGTERM");
2903
+ say(
2904
+ `Stopped the kody daemon service after runs in flight finish.${other ? ` Also stopping the kody daemon that held this context (${describeHolder(other)}).` : ""} It starts again at the next login or boot, or with \`kody daemon start\`.`,
2905
+ { service: input.manager, ...other ? { runner: other } : {} }
2906
+ );
2907
+ return 0;
2908
+ }
2909
+ if (!runner || runner.pid <= 0) {
2910
+ say("No kody daemon is running this context.");
2911
+ return 0;
2912
+ }
2913
+ process.kill(runner.pid, "SIGTERM");
2914
+ say(
2915
+ `Stopping the kody daemon (${describeHolder(runner)}) after runs in flight finish.`,
2916
+ { runner }
2917
+ );
2918
+ return 0;
2919
+ }
2920
+ async function runAutoUpdateCommand(env, action) {
2921
+ if (action === "on" || action === "off") {
2922
+ await setLocalAutoUpdateEnabled({ enabled: action === "on" });
2923
+ } else if (action !== void 0 && action !== "status") {
2924
+ throw new Error(
2925
+ "Usage: kody daemon auto-update [on | off | status] [--json]"
2926
+ );
2927
+ }
2928
+ const status = await autoUpdateStatus(env.clientVersion);
2929
+ if (env.json) {
2930
+ env.write(`${JSON.stringify(status, null, 2)}
2931
+ `);
2932
+ return 0;
2933
+ }
2934
+ if (action === "on" || action === "off") {
2935
+ env.write(
2936
+ action === "on" ? "Auto-update is on for every kody daemon on this machine. Running daemons pick it up at their next check.\n" : "Auto-update is off for every kody daemon on this machine. Update by hand with: kody update\n"
2937
+ );
2938
+ if (status.source === "env" && action === "on") {
2939
+ env.write(
2940
+ "KODY_DAEMON_AUTO_UPDATE still turns it off for daemons started with it.\n"
2941
+ );
2942
+ }
2943
+ return 0;
2944
+ }
2945
+ env.write(`${formatAutoUpdateLine(status)}
2946
+ `);
2947
+ if (status.recent.length > 0) {
2948
+ env.write(" Recent updates:\n");
2949
+ for (const event of status.recent) {
2950
+ env.write(
2951
+ ` ${event.at} ${event.from} -> ${event.to}: ${event.outcome}${event.detail ? ` (${event.detail})` : ""}
2952
+ `
2953
+ );
2954
+ }
2955
+ }
2956
+ return 0;
2957
+ }
1801
2958
  async function runDaemonServiceCommand(env, input) {
1802
2959
  const ecid = localContextId(env.apiUrl, input.context);
1803
2960
  const manager = serviceManagerFor(env.platform);
@@ -1814,13 +2971,39 @@ async function runDaemonServiceCommand(env, input) {
1814
2971
  ...env.tmpDir === void 0 ? {} : { tmpDir: env.tmpDir }
1815
2972
  });
1816
2973
  const name = ecid ? readStoredContext(env.apiUrl, ecid)?.name : void 0;
2974
+ const autoUpdate = await autoUpdateStatus(env.clientVersion);
2975
+ const runner = ecid ? runnerFor(env.apiUrl, ecid) : null;
1817
2976
  env.write(
1818
- env.json ? `${JSON.stringify({ ...status, contextName: name ?? null }, null, 2)}
2977
+ env.json ? `${JSON.stringify(
2978
+ {
2979
+ ...status,
2980
+ contextName: name ?? null,
2981
+ contexts: storedContextIds(env.apiUrl).map((id) => ({
2982
+ ecid: id,
2983
+ name: readStoredContext(env.apiUrl, id)?.name ?? null
2984
+ })),
2985
+ runner,
2986
+ autoUpdate
2987
+ },
2988
+ null,
2989
+ 2
2990
+ )}
1819
2991
  ` : `${formatServiceStatus(status, name)}
2992
+ ${runner ? ` Runner: ${describeHolder(runner)}
2993
+ ` : ""}${formatAutoUpdateLine(autoUpdate)}
1820
2994
  `
1821
2995
  );
1822
2996
  return status.problems.length === 0 ? 0 : 1;
1823
2997
  }
2998
+ if (input.sub === "stop" || input.sub === "start") {
2999
+ if (!ecid)
3000
+ throw new Error("This machine has no registered execution context.");
3001
+ return await startOrStopRunner(env, {
3002
+ ecid,
3003
+ manager,
3004
+ start: input.sub === "start"
3005
+ });
3006
+ }
1824
3007
  if (!manager) throw new Error(unsupportedPlatformMessage);
1825
3008
  if (!ecid) {
1826
3009
  throw new Error(
@@ -1837,7 +3020,7 @@ async function runDaemonServiceCommand(env, input) {
1837
3020
  return status.ok ? 0 : 1;
1838
3021
  }
1839
3022
  if (input.sub === "logs") {
1840
- if (!existsSync3(paths.logPath)) {
3023
+ if (!existsSync4(paths.logPath)) {
1841
3024
  env.write(
1842
3025
  `No service log yet at ${paths.logPath}. Install the service with: kody daemon install
1843
3026
  `
@@ -1848,7 +3031,7 @@ async function runDaemonServiceCommand(env, input) {
1848
3031
  if (!Number.isInteger(lines) || lines < 1)
1849
3032
  throw new Error("--lines must be a positive whole number.");
1850
3033
  if (input.follow) {
1851
- const child = spawn("tail", ["-n", String(lines), "-F", paths.logPath], {
3034
+ const child = spawn2("tail", ["-n", String(lines), "-F", paths.logPath], {
1852
3035
  stdio: "inherit"
1853
3036
  });
1854
3037
  return await new Promise((resolve) => {
@@ -1861,7 +3044,7 @@ async function runDaemonServiceCommand(env, input) {
1861
3044
  `);
1862
3045
  return 0;
1863
3046
  }
1864
- if (!existsSync3(paths.unitPath)) {
3047
+ if (!existsSync4(paths.unitPath)) {
1865
3048
  throw new Error(
1866
3049
  "The kody daemon service is not installed. Install it with: kody daemon install"
1867
3050
  );
@@ -1906,7 +3089,7 @@ async function runDaemonServiceCommand(env, input) {
1906
3089
  return 0;
1907
3090
  }
1908
3091
  throw new Error(
1909
- "Usage: kody daemon [install | status [--json] | logs [--lines <n>] [--follow] | restart | uninstall [--unregister]]"
3092
+ "Usage: kody daemon [install | status [--json] | logs [--lines <n>] [--follow] | restart | start | stop | uninstall [--unregister] | auto-update [on | off | status]]"
1910
3093
  );
1911
3094
  }
1912
3095
  async function offerInstall(env, input) {
@@ -1951,7 +3134,7 @@ async function offerUninstallAfterRevoke(env, input) {
1951
3134
  const ecid = input.ecid ?? localContextId(env.apiUrl, input.ref);
1952
3135
  if (!ecid) return;
1953
3136
  const paths = servicePaths({ apiUrl: env.apiUrl, ecid, manager });
1954
- if (!existsSync3(paths.unitPath)) return;
3137
+ if (!existsSync4(paths.unitPath)) return;
1955
3138
  const yes = env.yes ? true : env.confirm ? await env.confirm(
1956
3139
  "This machine runs it as a background service. Remove the service?",
1957
3140
  true
@@ -1989,7 +3172,7 @@ async function runUpdate(env) {
1989
3172
  }
1990
3173
  const manager = serviceManagerFor(env.platform);
1991
3174
  const services = manager ? storedContextIds(env.apiUrl).filter(
1992
- (ecid) => existsSync3(
3175
+ (ecid) => existsSync4(
1993
3176
  servicePaths({ apiUrl: env.apiUrl, ecid, manager }).unitPath
1994
3177
  )
1995
3178
  ) : [];
@@ -2093,6 +3276,9 @@ async function runCommand2(input) {
2093
3276
  return input.values.maxConcurrent === void 0 ? void 0 : maxConcurrentRuns(input.values.maxConcurrent);
2094
3277
  };
2095
3278
  if (input.command === "update") return await runUpdate(serviceEnv);
3279
+ if (input.command === "daemon" && sub === "auto-update") {
3280
+ return await runAutoUpdateCommand(serviceEnv, rest[0]);
3281
+ }
2096
3282
  if (input.command === "daemon" && sub !== void 0) {
2097
3283
  const maxConcurrent = maxConcurrentFlag();
2098
3284
  return await runDaemonServiceCommand(serviceEnv, {
@@ -2373,15 +3559,53 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2373
3559
  const asService = process.env[serviceEnvVar];
2374
3560
  const manager = asService === "systemd" || asService === "launchd" ? asService : null;
2375
3561
  const paths = manager ? servicePaths({ apiUrl: input.apiUrl, ecid, manager }) : null;
2376
- if (paths) rotateLog(paths.logPath);
2377
- const { context, privateJwk } = loadContext({
2378
- apiUrl: input.apiUrl,
3562
+ const supervised = process.env[supervisedEnvVar] === "1";
3563
+ if (paths && !supervised) rotateLog(paths.logPath);
3564
+ const readAutoUpdate = async () => autoUpdateSetting(await readLocalPolicy().catch(() => null));
3565
+ const relaunchArgs = [
3566
+ "daemon",
3567
+ "--context",
2379
3568
  ecid,
2380
- wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
2381
- });
2382
- const privateKey = await importContextKey(privateJwk);
2383
- const serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
2384
- const { runContextRun } = await import("./run-executor-XTLAUDYY.js");
3569
+ "--api-url",
3570
+ input.apiUrl,
3571
+ ...input.values.maxConcurrent === void 0 ? [] : ["--max-concurrent", input.values.maxConcurrent]
3572
+ ];
3573
+ const log = (line) => input.write(`${line}
3574
+ `);
3575
+ if (!supervised && (await readAutoUpdate()).enabled) {
3576
+ const newer = newerInstalledVersion({ selfVersion: input.clientVersion });
3577
+ if (newer) {
3578
+ const outcome = await superviseNewerVersion({
3579
+ first: newer,
3580
+ selfVersion: input.clientVersion,
3581
+ args: relaunchArgs,
3582
+ log
3583
+ });
3584
+ if (outcome.kind === "exit") return outcome.code;
3585
+ }
3586
+ }
3587
+ let started;
3588
+ try {
3589
+ const { context: context2, privateJwk } = loadContext({
3590
+ apiUrl: input.apiUrl,
3591
+ ecid,
3592
+ wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
3593
+ });
3594
+ started = {
3595
+ context: context2,
3596
+ privateKey: await importContextKey(privateJwk),
3597
+ serverKeys: await fetchServerKeys({ apiUrl: input.apiUrl })
3598
+ };
3599
+ } catch (error) {
3600
+ if (!supervised) throw error;
3601
+ log(
3602
+ `Could not start: ${error instanceof Error ? error.message : String(error)}`
3603
+ );
3604
+ return startupRefusedExitCode;
3605
+ }
3606
+ const { context, privateKey } = started;
3607
+ let { serverKeys } = started;
3608
+ const { runContextRun } = await import("./run-executor-7MV5E5PX.js");
2385
3609
  const hostCommands = new HostCommands({
2386
3610
  localEnabled: await readLocalCommandsEnabled().catch(() => false)
2387
3611
  });
@@ -2390,12 +3614,75 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2390
3614
  void readLocalCommandsEnabled().catch(() => false).then((enabled) => hostCommands.setLocalEnabled(enabled));
2391
3615
  };
2392
3616
  watchFile(commandsPolicyPath, { interval: 2e3 }, onCommandsPolicyChange);
3617
+ const lockStatePath = servicePaths({
3618
+ apiUrl: input.apiUrl,
3619
+ ecid,
3620
+ manager: serviceManagerFor() ?? "systemd"
3621
+ }).statePath;
3622
+ const launcher = manager ?? (process.env[launcherEnvVar] === "desktop" ? "desktop" : "terminal");
3623
+ const lockInfo = {
3624
+ version: input.clientVersion,
3625
+ launcher,
3626
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
3627
+ };
3628
+ let lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
3629
+ if (!lock.ok && manager) {
3630
+ let holder = lock.holder;
3631
+ log(
3632
+ `Another kody daemon already runs ${context.name} (${describeHolder(holder)}). One runner per context: this service waits for it to stop instead of replacing it.`
3633
+ );
3634
+ let stopWaiting = false;
3635
+ const onWaitSignal = () => {
3636
+ stopWaiting = true;
3637
+ };
3638
+ process.on("SIGINT", onWaitSignal);
3639
+ process.on("SIGTERM", onWaitSignal);
3640
+ try {
3641
+ while (!lock.ok && !stopWaiting) {
3642
+ await new Promise((resolve) => setTimeout(resolve, 15e3));
3643
+ lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
3644
+ if (!lock.ok && lock.holder.pid !== holder.pid) {
3645
+ holder = lock.holder;
3646
+ log(
3647
+ `The runner for ${context.name} is now ${describeHolder(holder)}. Still waiting.`
3648
+ );
3649
+ }
3650
+ }
3651
+ } finally {
3652
+ process.off("SIGINT", onWaitSignal);
3653
+ process.off("SIGTERM", onWaitSignal);
3654
+ }
3655
+ if (!lock.ok) {
3656
+ unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
3657
+ return stayStoppedExitCode;
3658
+ }
3659
+ log(`The other daemon stopped. Starting ${context.name}.`);
3660
+ serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
3661
+ }
3662
+ if (!lock.ok) {
3663
+ unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
3664
+ const message = `Another kody daemon already runs ${context.name} (${describeHolder(lock.holder)}). One runner per context on a machine: use that one, or stop it first (\`kody daemon stop\`, or Machine > Stop runner in the desktop app).`;
3665
+ if (!supervised) throw new Error(message);
3666
+ log(message);
3667
+ return startupRefusedExitCode;
3668
+ }
3669
+ const releaseLock = lock.release;
2393
3670
  const abort = new AbortController();
2394
3671
  const drain = new AbortController();
2395
3672
  let hardStop;
3673
+ let signalled = false;
3674
+ let signalledAt = 0;
3675
+ let updateTo = null;
3676
+ let forcedUpdate = false;
2396
3677
  const onSignal = () => {
2397
- if (drain.signal.aborted) return abort.abort();
2398
- drain.abort();
3678
+ if (signalled) {
3679
+ if (Date.now() - signalledAt < 2e3) return;
3680
+ return abort.abort();
3681
+ }
3682
+ signalled = true;
3683
+ signalledAt = Date.now();
3684
+ updateTo = null;
3685
+ if (!drain.signal.aborted) drain.abort();
2399
3686
  hardStop = setTimeout(() => abort.abort(), 8e4);
2400
3687
  hardStop.unref();
2401
3688
  };
@@ -2419,7 +3706,8 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2419
3706
  pid: process.pid,
2420
3707
  version: input.clientVersion,
2421
3708
  service: manager,
2422
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
3709
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
3710
+ ...supervised ? { supervisorPid: process.ppid } : {}
2423
3711
  });
2424
3712
  const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
2425
3713
  const reaped = reapLeftoverWorkers(workersDir);
@@ -2432,6 +3720,27 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2432
3720
  const workerTracker = createLocalWorkerTracker(workersDir);
2433
3721
  const packageGraphCache = createPackageGraphCache();
2434
3722
  let stop = "shutdown";
3723
+ let autoUpdateEnabled = (await readAutoUpdate()).enabled;
3724
+ const activity = { runs: 0 };
3725
+ const updater = startDaemonUpdater({
3726
+ selfVersion: input.clientVersion,
3727
+ setting: async () => {
3728
+ const setting = await readAutoUpdate();
3729
+ autoUpdateEnabled = setting.enabled;
3730
+ return setting;
3731
+ },
3732
+ busy: () => ({
3733
+ runs: activity.runs,
3734
+ background: hostCommands.runningBackground()
3735
+ }),
3736
+ log,
3737
+ onReady: (current, forced) => {
3738
+ if (signalled) return;
3739
+ updateTo = current;
3740
+ forcedUpdate = forced;
3741
+ if (!drain.signal.aborted) drain.abort();
3742
+ }
3743
+ });
2435
3744
  try {
2436
3745
  stop = await runDaemon({
2437
3746
  apiUrl: input.apiUrl,
@@ -2444,6 +3753,12 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2444
3753
  ...localCapabilities(maxConcurrent),
2445
3754
  ...manager ? { service: manager } : {}
2446
3755
  },
3756
+ extraCapabilities: () => ({
3757
+ autoUpdate: autoUpdateEnabled ? "on" : "off"
3758
+ }),
3759
+ activity,
3760
+ // An update drain also waits for background host commands.
3761
+ drainHold: () => updateTo !== null && !signalled && !forcedUpdate && hostCommands.runningBackground() > 0,
2447
3762
  hostCommands,
2448
3763
  execute: (run) => runContextRun({
2449
3764
  ...run,
@@ -2452,19 +3767,23 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2452
3767
  packageGraphCache
2453
3768
  }),
2454
3769
  fs: {
2455
- effective: async (grantFs) => await effectiveFs(grantFs, (await readLocalPolicy()).fs),
3770
+ effective: async (grantFs) => {
3771
+ const policy = await readLocalPolicy();
3772
+ autoUpdateEnabled = autoUpdateSetting(policy).enabled;
3773
+ return await effectiveFs(grantFs, policy.fs);
3774
+ },
2456
3775
  onChange: (listener) => {
2457
3776
  const path = localPolicyPath();
2458
3777
  watchFile(path, { interval: 2e3 }, listener);
2459
3778
  return () => unwatchFile(path, listener);
2460
3779
  }
2461
3780
  },
2462
- log: (line) => input.write(`${line}
2463
- `),
3781
+ log,
2464
3782
  signal: abort.signal,
2465
3783
  drainSignal: drain.signal
2466
3784
  });
2467
3785
  } finally {
3786
+ updater.stop();
2468
3787
  unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
2469
3788
  hostCommands.killAll("shutdown");
2470
3789
  workerTracker.killAll();
@@ -2472,9 +3791,31 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2472
3791
  if (hardStop) clearTimeout(hardStop);
2473
3792
  process.off("SIGINT", onSignal);
2474
3793
  process.off("SIGTERM", onSignal);
2475
- rmSync2(statePath, { force: true });
3794
+ rmSync4(statePath, { force: true });
3795
+ releaseLock();
3796
+ }
3797
+ if (stop === "replaced") {
3798
+ const others = await otherLocalDaemons({ ecid: context.ecid });
3799
+ log(
3800
+ others.length > 0 ? `Another kody daemon for ${context.name} connected and replaced this one: ${others.map((other) => `pid ${other.pid} (${other.cmd})`).join("; ")}. It predates the one-runner lock. Stopping this daemon instead of reconnecting, so they do not keep replacing each other. Keep one: stop the other, or run \`kody update\` so both use the lock.` : `Another kody daemon for ${context.name} connected and replaced this one (not on this machine as far as kody can tell: is the same context key copied to another machine?). Stopping this daemon instead of reconnecting, so they do not keep replacing each other. Restart it with \`kody daemon restart\` once the other is gone.`
3801
+ );
3802
+ if (manager) return stayStoppedExitCode;
3803
+ return supervised ? startupRefusedExitCode : 1;
3804
+ }
3805
+ const target = updateTo;
3806
+ if (stop === "shutdown" && target && !signalled) {
3807
+ if (manager || supervised) return relaunchExitCode;
3808
+ const outcome = await superviseNewerVersion({
3809
+ first: target,
3810
+ selfVersion: input.clientVersion,
3811
+ args: relaunchArgs,
3812
+ log
3813
+ });
3814
+ if (outcome.kind === "exit") return outcome.code;
3815
+ log(`Auto-update: back on kody ${input.clientVersion}.`);
3816
+ return await runExecutionContextCommand(input);
2476
3817
  }
2477
- if (stop !== "shutdown") {
3818
+ if (stop === "revoked" || stop === "unknown_context") {
2478
3819
  const reason = stop === "revoked" ? "Kody revoked this context" : "Kody no longer knows this context (deleted)";
2479
3820
  writeJson(
2480
3821
  servicePaths({
@@ -2493,7 +3834,7 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2493
3834
  return stayStoppedExitCode;
2494
3835
  }
2495
3836
  throw new Error(
2496
- "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context cancel-run <name> <run id> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody context commands [status | on | off] [--context <name>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | logs | restart | uninstall | kody update"
3837
+ "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context cancel-run <name> <run id> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody context commands [status | on | off] [--context <name>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | logs | restart | start | stop | uninstall | auto-update [on | off | status] | kody update"
2497
3838
  );
2498
3839
  }
2499
3840
  async function resolveContextId(input) {
@@ -2530,7 +3871,7 @@ function describeChain(chain, contexts = /* @__PURE__ */ new Map()) {
2530
3871
  return lines.join("\n") || "Empty chain.";
2531
3872
  }
2532
3873
  function readCodeFile(path) {
2533
- return readFileSync4(path, "utf8");
3874
+ return readFileSync6(path, "utf8");
2534
3875
  }
2535
3876
  var policyUsage = "Usage: kody context policy [show] | kody context policy allow <path> [--mode ro|rw] | kody context policy remove <path>";
2536
3877
  var commandsUsage = "Usage: kody context commands [status | on | off] [--context <name>] [--json]";
@@ -2669,4 +4010,4 @@ export {
2669
4010
  readCodeFile,
2670
4011
  runExecutionContextCommand
2671
4012
  };
2672
- //# sourceMappingURL=commands-YZOAHUIH.js.map
4013
+ //# sourceMappingURL=commands-3KZPBDIP.js.map