@kodycodes/cli 3.31.1 → 3.31.3

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 (68) hide show
  1. package/dist/api-token.d.ts +4 -5
  2. package/dist/{auth-WLRCNZ2R.js → auth-PVW2LO2U.js} +6 -6
  3. package/dist/bin.js +9 -7
  4. package/dist/bin.js.map +1 -1
  5. package/dist/{chunk-B5DE7Z4Z.js → chunk-327OT6ZP.js} +20 -4
  6. package/dist/{chunk-B5DE7Z4Z.js.map → chunk-327OT6ZP.js.map} +1 -1
  7. package/dist/{chunk-TULCECSL.js → chunk-3G4MV7KG.js} +2 -2
  8. package/dist/{chunk-LTSHHKSM.js → chunk-6UTLL4CZ.js} +4 -4
  9. package/dist/{chunk-7OVUYX6A.js → chunk-CQHQFF7B.js} +13 -4
  10. package/dist/chunk-CQHQFF7B.js.map +6 -0
  11. package/dist/{chunk-RPUHFAMS.js → chunk-H7CJBJFA.js} +2 -2
  12. package/dist/{chunk-DNNA7ZIR.js → chunk-HPRHOM5U.js} +3 -3
  13. package/dist/{chunk-Z2JA4IVD.js → chunk-LVUVBXXK.js} +6 -6
  14. package/dist/{chunk-QGABG53Q.js → chunk-MN5PENPF.js} +3 -3
  15. package/dist/{chunk-5W34SXJW.js → chunk-MW3RLRTO.js} +30 -2
  16. package/dist/{chunk-5W34SXJW.js.map → chunk-MW3RLRTO.js.map} +1 -1
  17. package/dist/{chunk-H2YNRTLJ.js → chunk-OJT47JLR.js} +96 -42
  18. package/dist/chunk-OJT47JLR.js.map +6 -0
  19. package/dist/{chunk-5TDORXTY.js → chunk-PMFY674W.js} +4 -4
  20. package/dist/{chunk-ERH37XEJ.js → chunk-SS2SUBIJ.js} +3 -3
  21. package/dist/{commands-FNEOMNRD.js → chunk-Z2NJN47S.js} +94 -2739
  22. package/dist/chunk-Z2NJN47S.js.map +6 -0
  23. package/dist/cli-credential.d.ts +9 -0
  24. package/dist/cli.js +9 -7
  25. package/dist/commands-3CZ5DOQA.js +2788 -0
  26. package/dist/commands-3CZ5DOQA.js.map +6 -0
  27. package/dist/{dev-command-FHNDDC7N.js → dev-command-VBAIG6EU.js} +9 -9
  28. package/dist/{git-credential-TZIWXKU5.js → git-credential-FNVWEKWB.js} +7 -7
  29. package/dist/{local-execute-7Z7DOD3W.js → local-execute-SNWFJZVF.js} +11 -11
  30. package/dist/{local-package-graph-JZTRUXX6.js → local-package-graph-QAKOKW2R.js} +5 -5
  31. package/dist/{local-package-run-Y5UZZ72V.js → local-package-run-RFAIV4MZ.js} +9 -9
  32. package/dist/{local-secrets-EYYWBNJR.js → local-secrets-KZUJ2LE2.js} +5 -5
  33. package/dist/{mock-dep-resolve-HSEGGULX.js → mock-dep-resolve-IGS3ZKEO.js} +4 -4
  34. package/dist/{mock-local-deps-JM7WEOC6.js → mock-local-deps-Q6GG4HKA.js} +6 -6
  35. package/dist/{open-api-client-XV523Z26.js → open-api-client-NRPF5SUW.js} +5 -5
  36. package/dist/open-api-client.d.ts +6 -0
  37. package/dist/publish-builder.js +137 -70
  38. package/dist/{remote-execute-FUMYJS2B.js → remote-execute-MQLJCXD7.js} +5 -5
  39. package/dist/{run-executor-NMZGN2MG.js → run-executor-J3MF4RCT.js} +2 -2
  40. package/dist/{setup-git-GW3PNDG4.js → setup-git-6NZQISC4.js} +6 -6
  41. package/dist/{whoami-LISXTMTO.js → whoami-D2WGWIBE.js} +37 -7
  42. package/dist/whoami-D2WGWIBE.js.map +6 -0
  43. package/package.json +1 -1
  44. package/dist/chunk-7OVUYX6A.js.map +0 -6
  45. package/dist/chunk-H2YNRTLJ.js.map +0 -6
  46. package/dist/commands-FNEOMNRD.js.map +0 -6
  47. package/dist/whoami-LISXTMTO.js.map +0 -6
  48. /package/dist/{auth-WLRCNZ2R.js.map → auth-PVW2LO2U.js.map} +0 -0
  49. /package/dist/{chunk-TULCECSL.js.map → chunk-3G4MV7KG.js.map} +0 -0
  50. /package/dist/{chunk-LTSHHKSM.js.map → chunk-6UTLL4CZ.js.map} +0 -0
  51. /package/dist/{chunk-RPUHFAMS.js.map → chunk-H7CJBJFA.js.map} +0 -0
  52. /package/dist/{chunk-DNNA7ZIR.js.map → chunk-HPRHOM5U.js.map} +0 -0
  53. /package/dist/{chunk-Z2JA4IVD.js.map → chunk-LVUVBXXK.js.map} +0 -0
  54. /package/dist/{chunk-QGABG53Q.js.map → chunk-MN5PENPF.js.map} +0 -0
  55. /package/dist/{chunk-5TDORXTY.js.map → chunk-PMFY674W.js.map} +0 -0
  56. /package/dist/{chunk-ERH37XEJ.js.map → chunk-SS2SUBIJ.js.map} +0 -0
  57. /package/dist/{dev-command-FHNDDC7N.js.map → dev-command-VBAIG6EU.js.map} +0 -0
  58. /package/dist/{git-credential-TZIWXKU5.js.map → git-credential-FNVWEKWB.js.map} +0 -0
  59. /package/dist/{local-execute-7Z7DOD3W.js.map → local-execute-SNWFJZVF.js.map} +0 -0
  60. /package/dist/{local-package-graph-JZTRUXX6.js.map → local-package-graph-QAKOKW2R.js.map} +0 -0
  61. /package/dist/{local-package-run-Y5UZZ72V.js.map → local-package-run-RFAIV4MZ.js.map} +0 -0
  62. /package/dist/{local-secrets-EYYWBNJR.js.map → local-secrets-KZUJ2LE2.js.map} +0 -0
  63. /package/dist/{mock-dep-resolve-HSEGGULX.js.map → mock-dep-resolve-IGS3ZKEO.js.map} +0 -0
  64. /package/dist/{mock-local-deps-JM7WEOC6.js.map → mock-local-deps-Q6GG4HKA.js.map} +0 -0
  65. /package/dist/{open-api-client-XV523Z26.js.map → open-api-client-NRPF5SUW.js.map} +0 -0
  66. /package/dist/{remote-execute-FUMYJS2B.js.map → remote-execute-MQLJCXD7.js.map} +0 -0
  67. /package/dist/{run-executor-NMZGN2MG.js.map → run-executor-J3MF4RCT.js.map} +0 -0
  68. /package/dist/{setup-git-GW3PNDG4.js.map → setup-git-6NZQISC4.js.map} +0 -0
@@ -1,34 +1,15 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
2
  import {
3
- allowLocalPath,
4
- canonicalHostPath,
5
- credentialDenylist,
6
- effectiveFs,
7
- emptyEffectiveFs,
8
- fsFeatures,
9
- isAbsolute,
10
- isDeniedPath,
11
- isWithin,
12
3
  killProcessTree,
13
4
  localPolicyPath,
14
5
  normalizeServiceEnv,
15
- plainPath,
16
- readLocalCommandsEnabled,
17
6
  readLocalPolicy,
18
- removeLocalPath,
19
7
  reservedServiceEnvKeys,
20
- samePath,
21
8
  setLocalAutoUpdateEnabled,
22
- setLocalCommandsEnabled,
23
9
  validateServiceEnvKey,
24
10
  windowsCommandLine,
25
11
  writeLocalPolicy
26
12
  } from "./chunk-ATZXCAZA.js";
27
- import {
28
- killWindowsTree,
29
- windowsFileLaunch,
30
- windowsShellLaunch
31
- } from "./chunk-LQNGII7U.js";
32
13
  import {
33
14
  apiTokenFileStorePath
34
15
  } from "./chunk-YFNQZPEP.js";
@@ -43,18 +24,6 @@ import {
43
24
  formatUnreachableApiMessage,
44
25
  requestSentStatus
45
26
  } from "./chunk-YVWOK4LV.js";
46
- import "./chunk-UW6AWLXX.js";
47
-
48
- // src/execution-context/commands.ts
49
- import {
50
- appendFileSync,
51
- existsSync as existsSync5,
52
- readFileSync as readFileSync8,
53
- rmSync as rmSync6,
54
- unwatchFile,
55
- watchFile
56
- } from "node:fs";
57
- import { cpus, platform, totalmem } from "node:os";
58
27
 
59
28
  // ../shared/src/base64.ts
60
29
  function bytesToBase64(bytes) {
@@ -670,7 +639,7 @@ import {
670
639
  } from "node:fs";
671
640
  import { createRequire } from "node:module";
672
641
  import { homedir } from "node:os";
673
- import { delimiter, dirname, isAbsolute as isAbsolute2, join, normalize, sep } from "node:path";
642
+ import { delimiter, dirname, isAbsolute, join, normalize, sep } from "node:path";
674
643
  import { gunzipSync } from "node:zlib";
675
644
  var packageName = "@kodycodes/cli";
676
645
  var registryUrl = "https://registry.npmjs.org";
@@ -754,7 +723,7 @@ function writeJsonAtomic(path, value) {
754
723
  }
755
724
  function readCurrent(store = cliStoreDir()) {
756
725
  const current = readJsonFile(join(store, "current.json"));
757
- if (!current || typeof current.version !== "string" || typeof current.entry !== "string" || !parseVersion(current.version) || !isAbsolute2(current.entry) || !isWithinDir(current.entry, join(store, "versions"))) {
726
+ if (!current || typeof current.version !== "string" || typeof current.entry !== "string" || !parseVersion(current.version) || !isAbsolute(current.entry) || !isWithinDir(current.entry, join(store, "versions"))) {
758
727
  return null;
759
728
  }
760
729
  return current;
@@ -911,7 +880,7 @@ function extractPackage(gzipped, dest) {
911
880
  const relative = path.replace(/^package\//, "");
912
881
  if (relative === path && path !== "package") continue;
913
882
  const parts = relative.split("/").filter(Boolean);
914
- if (parts.some((part) => part === ".." || part === ".") || isAbsolute2(relative)) {
883
+ if (parts.some((part) => part === ".." || part === ".") || isAbsolute(relative)) {
915
884
  throw new Error(`tarball has an unsafe path: ${path}`);
916
885
  }
917
886
  if (parts.length === 0) continue;
@@ -1646,12 +1615,6 @@ async function otherLocalDaemons(input) {
1646
1615
  );
1647
1616
  }
1648
1617
 
1649
- // src/execution-context/service-commands.ts
1650
- import { spawn as spawn2, spawnSync } from "node:child_process";
1651
- import { existsSync as existsSync4, readFileSync as readFileSync6, readdirSync as readdirSync2, rmSync as rmSync4 } from "node:fs";
1652
- import { createInterface } from "node:readline";
1653
- import { setTimeout as sleep } from "node:timers/promises";
1654
-
1655
1618
  // src/execution-context/keystore.ts
1656
1619
  import {
1657
1620
  createCipheriv,
@@ -1867,19 +1830,6 @@ function loadContext(input) {
1867
1830
  return { context, privateJwk: decryptPrivateKey(file, input.wrapping) };
1868
1831
  }
1869
1832
 
1870
- // src/execution-context/service.ts
1871
- import { execFileSync as execFileSync2 } from "node:child_process";
1872
- import {
1873
- existsSync as existsSync3,
1874
- mkdirSync as mkdirSync4,
1875
- readFileSync as readFileSync5,
1876
- realpathSync,
1877
- rmSync as rmSync3,
1878
- writeFileSync as writeFileSync4
1879
- } from "node:fs";
1880
- import { homedir as homedir2, tmpdir, userInfo } from "node:os";
1881
- import { dirname as dirname4, join as join3, sep as sep2 } from "node:path";
1882
-
1883
1833
  // src/execution-context/service-env.ts
1884
1834
  import { readFileSync as readFileSync4 } from "node:fs";
1885
1835
  var secretLooking = /(TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)/i;
@@ -1912,8 +1862,8 @@ function readServiceEnvSync(path = localPolicyPath()) {
1912
1862
  }
1913
1863
  async function saveServiceEnvAssignments(args, policyPath) {
1914
1864
  const set = Object.fromEntries(
1915
- args.map((arg2) => {
1916
- const { key, value } = parseServiceEnvAssignment(arg2);
1865
+ args.map((arg) => {
1866
+ const { key, value } = parseServiceEnvAssignment(arg);
1917
1867
  return [key, value];
1918
1868
  })
1919
1869
  );
@@ -2019,12 +1969,23 @@ function handAddedWarning(keys) {
2019
1969
  }
2020
1970
 
2021
1971
  // src/execution-context/service.ts
1972
+ import { execFileSync as execFileSync2 } from "node:child_process";
1973
+ import {
1974
+ existsSync as existsSync3,
1975
+ mkdirSync as mkdirSync4,
1976
+ readFileSync as readFileSync5,
1977
+ realpathSync,
1978
+ rmSync as rmSync3,
1979
+ writeFileSync as writeFileSync4
1980
+ } from "node:fs";
1981
+ import { homedir as homedir2, tmpdir, userInfo } from "node:os";
1982
+ import { dirname as dirname4, join as join3, sep as sep2 } from "node:path";
2022
1983
  var serviceEnvVar = "KODY_DAEMON_SERVICE";
2023
1984
  var stayStoppedExitCode = 0;
2024
- function serviceManagerFor(platform2 = process.platform) {
2025
- if (platform2 === "linux") return "systemd";
2026
- if (platform2 === "darwin") return "launchd";
2027
- if (platform2 === "win32") return "taskscheduler";
1985
+ function serviceManagerFor(platform = process.platform) {
1986
+ if (platform === "linux") return "systemd";
1987
+ if (platform === "darwin") return "launchd";
1988
+ if (platform === "win32") return "taskscheduler";
2028
1989
  return null;
2029
1990
  }
2030
1991
  function isServiceManager(value) {
@@ -2099,17 +2060,17 @@ function daemonArgs(input) {
2099
2060
  ];
2100
2061
  }
2101
2062
  function servicePath(input) {
2102
- const platform2 = input.platform ?? process.platform;
2063
+ const platform = input.platform ?? process.platform;
2103
2064
  const dirs = [
2104
2065
  dirname4(input.node),
2105
- ...platform2 === "darwin" ? ["/opt/homebrew/bin"] : [],
2066
+ ...platform === "darwin" ? ["/opt/homebrew/bin"] : [],
2106
2067
  "/usr/local/bin",
2107
2068
  "/usr/bin",
2108
2069
  "/bin",
2109
2070
  "/usr/sbin",
2110
2071
  "/sbin"
2111
2072
  ];
2112
- return [...new Set(dirs)].join(platform2 === "win32" ? ";" : ":");
2073
+ return [...new Set(dirs)].join(platform === "win32" ? ";" : ":");
2113
2074
  }
2114
2075
  function serviceEnvironment(input) {
2115
2076
  const base = kodyServiceEnvironment(input);
@@ -2832,6 +2793,10 @@ function rotateLog(path, maxBytes = 10 * 1024 * 1024) {
2832
2793
  }
2833
2794
 
2834
2795
  // src/execution-context/service-commands.ts
2796
+ import { spawn as spawn2, spawnSync } from "node:child_process";
2797
+ import { existsSync as existsSync4, readFileSync as readFileSync6, readdirSync as readdirSync2, rmSync as rmSync4 } from "node:fs";
2798
+ import { createInterface } from "node:readline";
2799
+ import { setTimeout as sleep } from "node:timers/promises";
2835
2800
  function terminalConfirm() {
2836
2801
  if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
2837
2802
  return async (question, defaultYes) => {
@@ -3187,7 +3152,7 @@ async function runDaemonEnvCommand(env, input) {
3187
3152
  const applied = applyServiceEnv(env, input.context);
3188
3153
  if (!env.json) {
3189
3154
  env.write(
3190
- `${action === "set" ? "Saved" : "Removed"} ${input.args.map((arg2) => arg2.split("=")[0]).join(", ")} for the kody daemon service. ${applied}
3155
+ `${action === "set" ? "Saved" : "Removed"} ${input.args.map((arg) => arg.split("=")[0]).join(", ")} for the kody daemon service. ${applied}
3191
3156
  `
3192
3157
  );
3193
3158
  }
@@ -3676,2681 +3641,71 @@ function formatRemoteStatus(result) {
3676
3641
  return lines.join("\n");
3677
3642
  }
3678
3643
 
3679
- // src/execution-context/daemon.ts
3680
- function runScopedFetch(input) {
3681
- const apiOrigin = new URL(input.apiUrl).origin;
3682
- const base = input.fetchFn ?? fetch;
3683
- return async (resource, init) => {
3684
- const request = new Request(resource, init);
3685
- const url = new URL(request.url);
3686
- if (url.origin !== apiOrigin) return base(request);
3687
- const body = new Uint8Array(await request.arrayBuffer());
3688
- const headers = {};
3689
- request.headers.forEach((value, name) => {
3690
- if (name !== "authorization") headers[name] = value;
3691
- });
3692
- return signedFetch({
3693
- apiUrl: input.apiUrl,
3694
- ecid: input.ecid,
3695
- privateKey: input.privateKey,
3696
- method: request.method,
3697
- pathAndQuery: `${url.pathname}${url.search}`,
3698
- body,
3699
- runId: input.runId,
3700
- headers,
3701
- fetchFn: base
3702
- });
3703
- };
3704
- }
3705
- function originOf(url) {
3706
- try {
3707
- return new URL(url).origin;
3708
- } catch {
3709
- return null;
3710
- }
3711
- }
3712
- function runRequestRefusal(request, apiUrl, now = Date.now()) {
3713
- const origin = originOf(request.apiUrl);
3714
- if (!origin || origin !== originOf(apiUrl)) return "grant_mismatch";
3715
- if (now > request.acceptBy) return "deadline_passed";
3716
- return null;
3717
- }
3718
- var daemonControlFeature = "daemon-control";
3719
- var DaemonControlError = class extends Error {
3720
- constructor(code, message) {
3721
- super(message);
3722
- this.code = code;
3723
- this.name = "DaemonControlError";
3724
- }
3725
- code;
3726
- };
3727
- function pauseOf(value) {
3728
- const pause = value;
3729
- return pause && typeof pause.at === "string" ? {
3730
- at: pause.at,
3731
- by: typeof pause.by === "string" ? pause.by : null,
3732
- reason: typeof pause.reason === "string" ? pause.reason : null
3733
- } : null;
3734
- }
3735
- function grantFsOf(grant) {
3736
- const fs = grant?.fs;
3737
- if (!Array.isArray(fs)) return [];
3738
- return fs.filter(
3739
- (entry) => typeof entry?.path === "string" && typeof entry?.mode === "string"
3740
- );
3741
- }
3742
- var layerLabel = {
3743
- server_grant: "server grant",
3744
- credential_denylist: "credential denylist",
3745
- local_policy: "local policy"
3746
- };
3747
- var welcomeTimeoutMs = 15e3;
3748
- var welcomeTimeoutCloseCode = 4e3;
3749
- var closeSettleMs = 5e3;
3750
- var defaultPingMs = 3e4;
3751
- var defaultPongTimeoutMs = 1e4;
3752
- var heartbeatTimeoutCloseCode = 4001;
3753
- var frameRejectedCloseCode = 4008;
3754
- function heartbeatSetting(value, fallback) {
3755
- return typeof value === "number" && Number.isFinite(value) && value >= 1e3 && value <= 3e5 ? value : fallback;
3756
- }
3757
- async function runDaemonConnection(input) {
3758
- const Socket = input.WebSocketImpl ?? globalThis.WebSocket;
3759
- if (!Socket) {
3760
- throw new Error(
3761
- "This Node.js has no global WebSocket. Use Node 22 or newer."
3762
- );
3763
- }
3764
- const { ticket } = await requestConnectTicket(input);
3765
- if (input.signal?.aborted) return { code: 1e3, reason: "shutdown" };
3766
- const url = new URL(`${executionContextsPath}/connect`, input.apiUrl);
3767
- url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
3768
- url.searchParams.set("ticket", ticket);
3769
- const ws = new Socket(url.toString());
3770
- let welcomed = false;
3771
- let grantFs = [];
3772
- let hostFs = emptyEffectiveFs;
3773
- const effectiveFsNow = async () => {
3774
- if (!input.fs) return emptyEffectiveFs;
3775
- try {
3776
- return await input.fs.effective(grantFs);
3777
- } catch (error) {
3778
- input.log(
3779
- `Host folders are off: ${error instanceof Error ? error.message : String(error)}`
3780
- );
3781
- return emptyEffectiveFs;
3782
- }
3783
- };
3784
- const capabilities = () => {
3785
- const base = Array.isArray(input.capabilities.features) ? input.capabilities.features : [];
3786
- return {
3787
- ...input.capabilities,
3788
- ...input.extraCapabilities?.(),
3789
- maxConcurrent,
3790
- features: [
3791
- ...base.filter(
3792
- (feature) => feature !== "fs" && feature !== ecpHostOperatorOnlyFeature
3793
- ),
3794
- ecpHostOperatorOnlyFeature,
3795
- ...input.control ? [daemonControlFeature] : [],
3796
- ...fsFeatures(hostFs)
3797
- ]
3798
- };
3799
- };
3800
- const applyFs = async () => {
3801
- if (!input.fs) return;
3802
- hostFs = await effectiveFsNow();
3803
- for (const mount of hostFs.mounts) {
3804
- input.log(
3805
- `Host folder ${mount.path} is available to runs (${mount.mode}).`
3806
- );
3807
- }
3808
- for (const refusal of hostFs.refused) {
3809
- input.log(
3810
- `Host folder ${refusal.path} is not available: ${refusal.reason} (${layerLabel[refusal.layer]}).`
3811
- );
3812
- }
3813
- };
3814
- const refreshFs = async (before = JSON.stringify(capabilities())) => {
3815
- await applyFs();
3816
- const next = capabilities();
3817
- if (welcomed && JSON.stringify(next) !== before) {
3818
- await send("capabilities.update", { capabilities: next });
3819
- }
3820
- };
3821
- const unsubscribeFs = input.fs?.onChange?.(() => {
3822
- if (welcomed) void refreshFs().catch(() => {
3823
- });
3824
- });
3825
- const serverKeys = new Map(input.serverKeys.map((key) => [key.kid, key]));
3826
- let sid = "";
3827
- let inSeq = 0;
3828
- let outSeq = 0;
3829
- const runs = /* @__PURE__ */ new Map();
3830
- let maxConcurrent = input.maxConcurrent;
3831
- const applyLimits = (grant) => {
3832
- const limit = grant?.limits?.maxConcurrent;
3833
- const previous = maxConcurrent;
3834
- maxConcurrent = typeof limit === "number" && limit >= 1 ? Math.min(input.maxConcurrent, Math.floor(limit)) : input.maxConcurrent;
3835
- return maxConcurrent !== previous;
3836
- };
3837
- let outbound = Promise.resolve();
3838
- let outboundFailed = false;
3839
- const send = (t, body, re) => {
3840
- const sent = outbound.then(async () => {
3841
- if (outboundFailed) throw new Error("This connection already failed.");
3842
- if (ws.readyState !== ws.OPEN)
3843
- throw new Error("This connection is not open.");
3844
- outSeq += 1;
3845
- const payload = {
3846
- v: 1,
3847
- t,
3848
- ec: input.ecid,
3849
- sid,
3850
- seq: outSeq,
3851
- ts: Date.now(),
3852
- ...re === void 0 ? {} : { re },
3853
- body
3854
- };
3855
- ws.send(
3856
- await signFrame({
3857
- privateKey: input.privateKey,
3858
- kid: ecpContextKeyId,
3859
- payload
3860
- })
3861
- );
3862
- });
3863
- outbound = sent.catch(() => {
3864
- if (outboundFailed) return;
3865
- outboundFailed = true;
3866
- try {
3867
- ws.close(4e3, "send failed");
3868
- } catch {
3869
- }
3870
- });
3871
- return sent;
3872
- };
3873
- let grantEgress = ecpDefaultGrant.egress;
3874
- const applyGrant = (grant) => {
3875
- const egress = grant?.egress;
3876
- if (egress && typeof egress.mode === "string") grantEgress = egress;
3877
- input.hostCommands?.setGrantEnabled(
3878
- grant?.commands?.enabled === true
3879
- );
3880
- };
3881
- const reporter = async (finished) => {
3882
- await send("command.finished", finished);
3883
- };
3884
- let connectionEnded = false;
3885
- let rearmHeartbeat = null;
3886
- const status = () => ({
3887
- running: runs.size,
3888
- maxConcurrent,
3889
- acceptingRuns: !input.drainSignal?.aborted && runs.size < maxConcurrent
3890
- });
3891
- let closeWhenDrained = () => {
3892
- };
3893
- const startRun = async (run) => {
3894
- const startedAt = Date.now();
3895
- const committedAt = run.committedAt ?? startedAt;
3896
- let deadlineHit = false;
3897
- const timer = setTimeout(
3898
- () => {
3899
- deadlineHit = true;
3900
- run.abort.abort();
3901
- },
3902
- Math.max(0, run.request.deadline - Date.now())
3903
- );
3904
- let result;
3905
- try {
3906
- if (input.fs) hostFs = await effectiveFsNow();
3907
- const operatorRun = run.request.sharedRun !== true;
3908
- result = await input.execute({
3909
- request: run.request,
3910
- // A getter, so a grant.update or policy change narrows runs already in flight.
3911
- ...input.fs && operatorRun ? { hostFs: () => hostFs } : {},
3912
- signal: run.abort.signal,
3913
- ...input.hostCommands && operatorRun ? { hostCommands: input.hostCommands } : {},
3914
- egress: grantEgress,
3915
- fetchFn: runScopedFetch({
3916
- apiUrl: input.apiUrl,
3917
- ecid: input.ecid,
3918
- runId: run.request.runId,
3919
- privateKey: input.privateKey,
3920
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
3921
- })
3922
- });
3923
- } catch (error) {
3924
- result = {
3925
- isError: true,
3926
- content: [
3927
- {
3928
- type: "text",
3929
- text: error instanceof Error ? error.message : String(error)
3930
- }
3931
- ]
3932
- };
3933
- } finally {
3934
- clearTimeout(timer);
3935
- }
3936
- const endedAt = Date.now();
3937
- const { timing: executorTiming, ...outcome } = result;
3938
- const resultBytes = new TextEncoder().encode(
3939
- JSON.stringify(outcome)
3940
- ).byteLength;
3941
- const timing = {
3942
- queueMs: startedAt - committedAt,
3943
- setupMs: executorTiming?.setupMs ?? 0,
3944
- ...executorTiming?.packageGraphMs !== void 0 ? {
3945
- packageGraphMs: executorTiming.packageGraphMs,
3946
- packageGraphCached: executorTiming.packageGraphCached === true
3947
- } : {},
3948
- executeMs: executorTiming?.executeMs ?? endedAt - startedAt,
3949
- daemonMs: endedAt - committedAt
3950
- };
3951
- runs.delete(run.request.runId);
3952
- if (input.activity) input.activity.runs = runs.size;
3953
- await send("run.result", {
3954
- runId: run.request.runId,
3955
- ...outcome,
3956
- // The local deadline stopped it: a cancel, not a code error.
3957
- ...deadlineHit && result.isError ? { cancelReason: "deadline" } : {},
3958
- startedAt,
3959
- endedAt,
3960
- resultBytes,
3961
- timing
3962
- });
3963
- await send("status", status());
3964
- closeWhenDrained();
3965
- };
3966
- const handle = async (frame) => {
3967
- const body = frame.body;
3968
- const runId = typeof body.runId === "string" ? body.runId : "";
3969
- switch (frame.t) {
3970
- case "welcome":
3971
- clearTimeout(welcomeTimer);
3972
- applyGrant(body.grant);
3973
- applyLimits(body.grant);
3974
- if (input.pingMs === void 0 && input.pongTimeoutMs === void 0) {
3975
- rearmHeartbeat?.(
3976
- heartbeatSetting(body.pingMs, defaultPingMs),
3977
- heartbeatSetting(body.pongTimeoutMs, defaultPongTimeoutMs)
3978
- );
3979
- }
3980
- grantFs = grantFsOf(body.grant);
3981
- await applyFs();
3982
- input.onPaused?.(pauseOf(body.paused));
3983
- welcomed = true;
3984
- await send("hello", {
3985
- protocol: { min: ecpProtocolVersion, max: ecpProtocolVersion },
3986
- client: input.client,
3987
- capabilities: capabilities(),
3988
- grantVersion: body.grantVersion,
3989
- status: status(),
3990
- // Kody ends committed runs this daemon no longer holds right away.
3991
- heldRuns: [...runs.values()].filter((run) => run.committed).map((run) => run.request.runId),
3992
- pendingResults: []
3993
- });
3994
- if (!connectionEnded) input.hostCommands?.setReporter(reporter);
3995
- input.log("Connected. Waiting for runs.");
3996
- return;
3997
- case "run.request": {
3998
- const request = body;
3999
- if (input.drainSignal?.aborted || runs.size >= maxConcurrent) {
4000
- await send("run.reject", { runId, code: "busy" }, frame.seq);
4001
- return;
4002
- }
4003
- const refusal = runRequestRefusal(request, input.apiUrl);
4004
- if (refusal) {
4005
- await send("run.reject", { runId, code: refusal }, frame.seq);
4006
- return;
4007
- }
4008
- runs.set(runId, {
4009
- request,
4010
- abort: new AbortController(),
4011
- committed: false
4012
- });
4013
- if (input.activity) input.activity.runs = runs.size;
4014
- await send("run.accept", { runId }, frame.seq);
4015
- return;
4016
- }
4017
- case "run.commit": {
4018
- const run = runs.get(runId);
4019
- if (!run || run.committed) return;
4020
- run.committed = true;
4021
- run.committedAt = Date.now();
4022
- input.log(
4023
- `Running ${runId} for ${run.request.requestedBy.handle ?? run.request.requestedBy.userId}.`
4024
- );
4025
- void startRun(run);
4026
- return;
4027
- }
4028
- case "run.abort":
4029
- case "run.cancel": {
4030
- const run = runs.get(runId);
4031
- run?.abort.abort();
4032
- if (!run?.committed) runs.delete(runId);
4033
- if (input.activity) input.activity.runs = runs.size;
4034
- if (frame.t === "run.cancel")
4035
- await send("run.cancel.ack", { runId }, frame.seq);
4036
- return;
4037
- }
4038
- case "grant.update": {
4039
- applyGrant(body.grant);
4040
- grantFs = grantFsOf(body.grant);
4041
- const before = JSON.stringify(capabilities());
4042
- const limitsChanged = applyLimits(body.grant);
4043
- await refreshFs(before);
4044
- await send("grant.ack", { grantVersion: body.grantVersion }, frame.seq);
4045
- if (limitsChanged) await send("status", status());
4046
- return;
4047
- }
4048
- case "state.update":
4049
- input.onPaused?.(pauseOf(body.paused));
4050
- return;
4051
- case "control.request": {
4052
- const id = typeof body.id === "string" ? body.id : "";
4053
- const op = typeof body.op === "string" ? body.op : "";
4054
- const args = body.args && typeof body.args === "object" ? body.args : {};
4055
- const control = input.control;
4056
- const re = frame.seq;
4057
- void (async () => {
4058
- try {
4059
- if (!control) {
4060
- throw new DaemonControlError(
4061
- "daemon_outdated",
4062
- "This daemon does not take remote control requests."
4063
- );
4064
- }
4065
- const data = await control(op, args);
4066
- await send("control.result", { id, ok: true, data }, re);
4067
- } catch (error) {
4068
- await send(
4069
- "control.result",
4070
- {
4071
- id,
4072
- ok: false,
4073
- code: error instanceof DaemonControlError ? error.code : "daemon_control_failed",
4074
- message: error instanceof Error ? error.message : String(error)
4075
- },
4076
- re
4077
- ).catch(() => {
4078
- });
4079
- }
4080
- })();
4081
- return;
4082
- }
4083
- case "revoke":
4084
- input.log(
4085
- `This context was revoked (${String(body.reason ?? "revoked")}).`
4086
- );
4087
- ws.close(1e3, "revoked");
4088
- return;
4089
- case "error":
4090
- input.log(`Kody: ${String(body.code)} ${String(body.message ?? "")}`);
4091
- return;
4092
- default:
4093
- return;
4094
- }
4095
- };
4096
- const timeoutMs = input.welcomeTimeoutMs ?? welcomeTimeoutMs;
4097
- let welcomeTimer;
4098
- return await new Promise((resolve) => {
4099
- let lastInboundAt = Date.now();
4100
- let ping;
4101
- let pongTimer;
4102
- const armHeartbeat = (pingMs, pongTimeoutMs) => {
4103
- clearInterval(ping);
4104
- ping = setInterval(() => {
4105
- if (ws.readyState !== ws.OPEN || pongTimer) return;
4106
- const sentAt = Date.now();
4107
- ws.send(ecpPingFrame);
4108
- pongTimer = setTimeout(() => {
4109
- pongTimer = void 0;
4110
- if (lastInboundAt >= sentAt) return;
4111
- input.log(
4112
- `Kody did not answer a ping within ${Math.round(pongTimeoutMs / 1e3)}s, so the connection is dead. Closing and reconnecting.`
4113
- );
4114
- closeAndSettle(heartbeatTimeoutCloseCode, "heartbeat timeout");
4115
- }, pongTimeoutMs);
4116
- }, pingMs);
4117
- };
4118
- rearmHeartbeat = armHeartbeat;
4119
- armHeartbeat(
4120
- input.pingMs ?? defaultPingMs,
4121
- input.pongTimeoutMs ?? defaultPongTimeoutMs
4122
- );
4123
- let settled = false;
4124
- let settleTimer;
4125
- const finish = (code, reason) => {
4126
- if (settled) return;
4127
- settled = true;
4128
- connectionEnded = true;
4129
- input.hostCommands?.clearReporter(reporter);
4130
- clearInterval(ping);
4131
- clearTimeout(pongTimer);
4132
- clearTimeout(welcomeTimer);
4133
- clearTimeout(settleTimer);
4134
- clearInterval(holdTimer);
4135
- unsubscribeFs?.();
4136
- input.signal?.removeEventListener("abort", shutdown);
4137
- input.drainSignal?.removeEventListener("abort", drain);
4138
- for (const run of runs.values()) run.abort.abort();
4139
- resolve({ code, reason });
4140
- };
4141
- const closeAndSettle = (code, reason) => {
4142
- try {
4143
- ws.close(code, reason);
4144
- } catch {
4145
- }
4146
- settleTimer ??= setTimeout(
4147
- () => finish(code, reason),
4148
- input.closeSettleMs ?? closeSettleMs
4149
- );
4150
- };
4151
- welcomeTimer = setTimeout(() => {
4152
- input.log(
4153
- `Kody did not send a welcome frame within ${Math.round(timeoutMs / 1e3)}s, so this context cannot come online. Closing and retrying.`
4154
- );
4155
- closeAndSettle(welcomeTimeoutCloseCode, "welcome timeout");
4156
- }, timeoutMs);
4157
- const shutdown = () => closeAndSettle(1e3, "shutdown");
4158
- if (input.signal?.aborted) shutdown();
4159
- input.signal?.addEventListener("abort", shutdown, { once: true });
4160
- let holdTimer;
4161
- closeWhenDrained = () => {
4162
- if (!input.drainSignal?.aborted) return;
4163
- if ([...runs.values()].some((run) => run.committed)) return;
4164
- if (input.drainHold?.()) {
4165
- holdTimer ??= setInterval(
4166
- () => closeWhenDrained(),
4167
- input.drainHoldPollMs ?? 5e3
4168
- );
4169
- return;
4170
- }
4171
- closeAndSettle(1e3, "shutdown");
4172
- };
4173
- const drain = () => {
4174
- input.log(
4175
- runs.size > 0 ? `Stopping after ${runs.size} run(s) in flight finish. New runs go to the next context in the chain.` : "Stopping."
4176
- );
4177
- if (welcomed) void send("status", status()).catch(() => {
4178
- });
4179
- closeWhenDrained();
4180
- };
4181
- if (input.drainSignal?.aborted) drain();
4182
- else input.drainSignal?.addEventListener("abort", drain, { once: true });
4183
- const rejectFrame = (code) => {
4184
- input.log(
4185
- `Kody sent a frame that failed verification (${code}). Closing and reconnecting.`
4186
- );
4187
- closeAndSettle(frameRejectedCloseCode, code);
4188
- };
4189
- let inbound = Promise.resolve();
4190
- ws.addEventListener("message", (event) => {
4191
- lastInboundAt = Date.now();
4192
- const text = typeof event.data === "string" ? event.data : "";
4193
- inbound = inbound.then(() => onMessage(text)).catch((error) => input.log(`Frame error: ${String(error)}`));
4194
- });
4195
- const onMessage = async (text) => {
4196
- if (settled || settleTimer) return;
4197
- const classified = classifyFrameText(text);
4198
- if (classified.kind !== "frame") return;
4199
- const key = serverKeys.get(classified.envelope.k);
4200
- if (!key) {
4201
- rejectFrame("unknown_server_key");
4202
- return;
4203
- }
4204
- if (!sid) {
4205
- sid = peekSid(classified.envelope.p);
4206
- }
4207
- const verified = await verifyFrame({
4208
- envelope: classified.envelope,
4209
- publicKey: await importEd25519PublicKey(publishedKeyJwk(key)),
4210
- expect: { ec: input.ecid, sid, lastSeq: inSeq },
4211
- now: Date.now()
4212
- });
4213
- if (!verified.ok) {
4214
- rejectFrame(verified.code);
4215
- return;
4216
- }
4217
- inSeq = verified.frame.seq;
4218
- await handle(verified.frame);
4219
- };
4220
- ws.addEventListener("close", (event) => finish(event.code, event.reason));
4221
- });
4222
- }
4223
- function peekSid(p) {
4224
- try {
4225
- const decoded = decodeEnvelopePayload(p);
4226
- return decoded?.t === "welcome" && typeof decoded.body?.sid === "string" ? decoded.body.sid : "";
4227
- } catch {
4228
- return "";
4229
- }
4230
- }
4231
- async function runDaemon(input) {
4232
- let attempt = 0;
4233
- const stopping = () => input.signal?.aborted || input.drainSignal?.aborted;
4234
- while (!stopping()) {
4235
- const startedAt = Date.now();
4236
- try {
4237
- const closed = await runDaemonConnection(input);
4238
- if (closed.reason === "revoked") return "revoked";
4239
- if (stopping()) return "shutdown";
4240
- if (closed.code === 1012 && closed.reason === "replaced") {
4241
- return "replaced";
4242
- }
4243
- input.log(
4244
- `Disconnected (${closed.code}${closed.reason ? ` ${closed.reason}` : ""}). Reconnecting.`
4245
- );
4246
- } catch (error) {
4247
- if (stopping()) return "shutdown";
4248
- if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
4249
- if (isPermanentContextRefusal(error)) {
4250
- input.log(
4251
- `Kody refused this context: ${error instanceof Error ? error.message : String(error)} Stopping for good.`
4252
- );
4253
- return error.reason === "revoked" ? "revoked" : "unknown_context";
4254
- }
4255
- input.log(
4256
- `Connect failed: ${error instanceof Error ? error.message : String(error)}`
4257
- );
4258
- }
4259
- if (Date.now() - startedAt > 6e4) attempt = 0;
4260
- attempt += 1;
4261
- const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6));
4262
- await abortableDelay(
4263
- delay * (0.5 + Math.random() / 2),
4264
- input.drainSignal ? AbortSignal.any(
4265
- [input.signal, input.drainSignal].filter(
4266
- (signal) => signal !== void 0
4267
- )
4268
- ) : input.signal
4269
- );
4270
- }
4271
- return "shutdown";
4272
- }
4273
- function abortableDelay(ms, signal) {
4274
- return new Promise((resolve) => {
4275
- if (signal?.aborted) return resolve();
4276
- const done = () => {
4277
- clearTimeout(timer);
4278
- signal?.removeEventListener("abort", done);
4279
- resolve();
4280
- };
4281
- const timer = setTimeout(done, ms);
4282
- signal?.addEventListener("abort", done, { once: true });
4283
- });
4284
- }
4285
-
4286
- // src/execution-context/host-commands.ts
4287
- import { spawn as spawn3 } from "node:child_process";
4288
- import { randomBytes as randomBytes4 } from "node:crypto";
4289
- import { realpath, stat } from "node:fs/promises";
4290
- import { homedir as homedir3 } from "node:os";
4291
- import { isAbsolute as isAbsolute3 } from "node:path";
4292
- var HostCommandError = class extends Error {
4293
- constructor(code, message) {
4294
- super(`${message} (${code})`);
4295
- this.code = code;
4296
- this.name = "HostCommandError";
4297
- }
4298
- code;
4299
- };
4300
- var hostCommandLimits = {
4301
- foregroundDefaultTimeoutMs: 6e4,
4302
- foregroundMaxTimeoutMs: 15 * 6e4,
4303
- backgroundDefaultTimeoutMs: 2 * 60 * 6e4,
4304
- backgroundMaxTimeoutMs: 24 * 60 * 6e4,
4305
- defaultOutputBytes: 256 * 1024,
4306
- maxOutputBytes: 4 * 1024 * 1024,
4307
- backgroundBufferBytes: 4 * 1024 * 1024,
4308
- maxOutputReadBytes: 1024 * 1024,
4309
- maxBackgroundJobs: 16,
4310
- keepFinishedJobsMs: 60 * 6e4,
4311
- maxCommandChars: 64 * 1024,
4312
- maxStdinBytes: 5 * 1024 * 1024
4313
- };
4314
- var OutputBuffer = class {
4315
- constructor(capacity) {
4316
- this.capacity = capacity;
4317
- }
4318
- capacity;
4319
- #chunks = [];
4320
- #size = 0;
4321
- /** Bytes ever written. */
4322
- total = 0;
4323
- get dropped() {
4324
- return this.total - this.#size;
4325
- }
4326
- write(chunk) {
4327
- this.total += chunk.length;
4328
- this.#chunks.push(chunk);
4329
- this.#size += chunk.length;
4330
- while (this.#size > this.capacity && this.#chunks.length > 0) {
4331
- const head = this.#chunks[0];
4332
- const over = this.#size - this.capacity;
4333
- if (head.length <= over) {
4334
- this.#chunks.shift();
4335
- this.#size -= head.length;
4336
- } else {
4337
- this.#chunks[0] = head.subarray(over);
4338
- this.#size -= over;
4339
- }
4340
- }
4341
- }
4342
- /** Bytes from absolute `offset` (clamped to what is still kept). */
4343
- read(offset, maxBytes) {
4344
- const all = Buffer.concat(this.#chunks);
4345
- let start = Math.max(offset, this.dropped);
4346
- while (start - this.dropped < all.length && start > offset && isUtf8Continuation(all[start - this.dropped]))
4347
- start++;
4348
- let end = Math.min(start - this.dropped + maxBytes, all.length);
4349
- if (end < all.length && isUtf8Continuation(all[end])) {
4350
- let back = end;
4351
- while (back > start - this.dropped && isUtf8Continuation(all[back]))
4352
- back--;
4353
- if (back > start - this.dropped) end = back;
4354
- else {
4355
- while (end < all.length && isUtf8Continuation(all[end])) end++;
4356
- }
4357
- }
4358
- const slice = all.subarray(start - this.dropped, end);
4359
- return {
4360
- text: slice.toString("utf8"),
4361
- from: start,
4362
- next: start + slice.length,
4363
- skipped: start - offset
4364
- };
4365
- }
4366
- text() {
4367
- return Buffer.concat(this.#chunks).toString("utf8");
4368
- }
4369
- };
4370
- function newCommandId() {
4371
- return `cmd_${randomBytes4(9).toString("base64url")}`;
4372
- }
4373
- function clampInt(value, fallback, max, min = 1) {
4374
- if (value === void 0 || value === null) return fallback;
4375
- if (typeof value !== "number" || !Number.isFinite(value)) {
4376
- throw new HostCommandError(
4377
- "invalid_request",
4378
- `Expected a number, got ${typeof value}.`
4379
- );
4380
- }
4381
- return Math.min(Math.max(Math.floor(value), min), max);
4382
- }
4383
- function isUtf8Continuation(byte) {
4384
- return (byte & 192) === 128;
4385
- }
4386
- function shellFor(env) {
4387
- const shell = env.SHELL;
4388
- return shell && isAbsolute3(shell) ? shell : "/bin/sh";
4389
- }
4390
- function killTree(child, signal) {
4391
- if (child.pid === void 0) return;
4392
- if (process.platform === "win32") {
4393
- void killWindowsTree(child.pid, {
4394
- leaderExited: child.exitCode !== null || child.signalCode !== null
4395
- });
4396
- return;
4397
- }
4398
- try {
4399
- process.kill(-child.pid, signal);
4400
- } catch {
4401
- try {
4402
- child.kill(signal);
4403
- } catch {
4404
- }
4405
- }
4406
- }
4407
- function stoppedOutcome(outcome, stoppedByKody) {
4408
- if (!stoppedByKody || process.platform !== "win32") return outcome;
4409
- return { ...outcome, code: null, signal: outcome.signal ?? "SIGKILL" };
4410
- }
4411
- function inheritedCommandEnv(env = process.env) {
4412
- return Object.fromEntries(
4413
- Object.entries(env).filter(([key]) => !/^KODY_/i.test(key))
4414
- );
4415
- }
4416
- var HostCommands = class {
4417
- #jobs = /* @__PURE__ */ new Map();
4418
- #onFinished = null;
4419
- /** Finishes that could not be sent yet (no live connection); sent on the next reporter. */
4420
- #unreported = [];
4421
- #foreground = /* @__PURE__ */ new Map();
4422
- #pendingStarts = 0;
4423
- #localEnabled;
4424
- /** The server grant's commands flag (off from website/API/CLI). */
4425
- #grantEnabled = false;
4426
- #platform;
4427
- #deniedPaths;
4428
- constructor(options = {}) {
4429
- this.#localEnabled = options.localEnabled === true;
4430
- this.#platform = options.platform ?? process.platform;
4431
- this.#deniedPaths = options.deniedPaths ?? credentialDenylist();
4432
- }
4433
- /** Both layers allow commands. */
4434
- get enabled() {
4435
- return this.#localEnabled && this.#grantEnabled;
4436
- }
4437
- setLocalEnabled(enabled) {
4438
- this.#localEnabled = enabled;
4439
- if (!enabled) this.killAll("commands_off");
4440
- }
4441
- setGrantEnabled(enabled) {
4442
- this.#grantEnabled = enabled;
4443
- if (!enabled) this.killAll("commands_off");
4444
- }
4445
- /** Clears the reporter if it is still `report` (a newer connection may own it). */
4446
- clearReporter(report) {
4447
- if (this.#onFinished === report) this.#onFinished = null;
4448
- }
4449
- setReporter(report) {
4450
- this.#onFinished = report;
4451
- if (!report) return;
4452
- const queued = this.#unreported.splice(0);
4453
- for (const finished of queued) this.#report(finished);
4454
- }
4455
- /** Throws the denial a run sees when it may not run commands here. */
4456
- assertAvailable() {
4457
- if (!this.#localEnabled) {
4458
- throw new HostCommandError(
4459
- "execution_context_commands_off",
4460
- "Host commands are off on this machine: its owner has not opted in. Turn them on on the machine with `kody context commands on` or the Kody desktop app (Machine > Allow commands)."
4461
- );
4462
- }
4463
- if (!this.#grantEnabled) {
4464
- throw new HostCommandError(
4465
- "execution_context_commands_off",
4466
- "Host commands were turned off for this machine (from the website, API or CLI). Its owner turns them back on on the machine with `kody context commands on` or the Kody desktop app."
4467
- );
4468
- }
4469
- }
4470
- /** Dispatches one `kody.command.<name>(args)` call from a run. */
4471
- async call(name, args, run) {
4472
- this.assertAvailable();
4473
- if (name === "status" || name === "output" || name === "kill" || name === "list") {
4474
- await run.authorize({ lifecycle: name });
4475
- this.assertAvailable();
4476
- }
4477
- switch (name) {
4478
- case "run":
4479
- return await this.run(args, run);
4480
- case "start":
4481
- return await this.start(args, run);
4482
- case "status":
4483
- return this.status(args, run);
4484
- case "output":
4485
- return this.output(args, run);
4486
- case "kill":
4487
- return this.kill(args, run);
4488
- case "list":
4489
- return this.list(run);
4490
- default:
4491
- throw new HostCommandError(
4492
- "invalid_request",
4493
- `Unknown kody.command.${name}. Use run, start, status, output, kill or list.`
4494
- );
4495
- }
4496
- }
4497
- async #prepare(input, background) {
4498
- const raw = typeof input === "string" ? { command: input } : input;
4499
- const spec = raw ?? {};
4500
- if (typeof spec !== "object" || Array.isArray(spec)) {
4501
- throw new HostCommandError(
4502
- "invalid_request",
4503
- "Pass { command } or { file, args }."
4504
- );
4505
- }
4506
- const hasCommand = typeof spec.command === "string" && spec.command.length > 0;
4507
- const hasFile = typeof spec.file === "string" && spec.file.length > 0;
4508
- if (hasCommand === hasFile) {
4509
- throw new HostCommandError(
4510
- "invalid_request",
4511
- "Pass exactly one of `command` (a shell command line) or `file` (an executable, with optional `args`)."
4512
- );
4513
- }
4514
- const args = spec.args ?? [];
4515
- if (!Array.isArray(args) || !args.every((arg2) => typeof arg2 === "string")) {
4516
- throw new HostCommandError(
4517
- "invalid_request",
4518
- "`args` must be an array of strings."
4519
- );
4520
- }
4521
- if (hasCommand && spec.args !== void 0) {
4522
- throw new HostCommandError(
4523
- "invalid_request",
4524
- "`args` goes with `file`, not `command`."
4525
- );
4526
- }
4527
- const display = hasCommand ? spec.command : [spec.file, ...args].join(" ");
4528
- if (display.length > hostCommandLimits.maxCommandChars) {
4529
- throw new HostCommandError("invalid_request", "The command is too long.");
4530
- }
4531
- const cwd = spec.cwd ?? homedir3();
4532
- if (typeof cwd !== "string" || !isAbsolute3(cwd)) {
4533
- throw new HostCommandError(
4534
- "invalid_request",
4535
- "`cwd` must be an absolute path on the machine."
4536
- );
4537
- }
4538
- const cwdStat = await stat(cwd).catch(() => null);
4539
- if (!cwdStat?.isDirectory()) {
4540
- throw new HostCommandError(
4541
- "invalid_request",
4542
- `cwd ${cwd} is not a folder on this machine.`
4543
- );
4544
- }
4545
- const realCwd = await realpath(cwd).catch(() => cwd);
4546
- if (isDeniedPath(cwd, this.#deniedPaths, this.#platform) || isDeniedPath(realCwd, this.#deniedPaths, this.#platform)) {
4547
- throw new HostCommandError(
4548
- "invalid_request",
4549
- `cwd ${cwd} holds credentials (the Kody CLI login and context keys, SSH, git, cloud or package-manager logins, or the OS keyring), so commands cannot run there.`
4550
- );
4551
- }
4552
- const extraEnv = spec.env ?? {};
4553
- if (typeof extraEnv !== "object" || Array.isArray(extraEnv) || !Object.entries(extraEnv).every(
4554
- ([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === "string"
4555
- )) {
4556
- throw new HostCommandError(
4557
- "invalid_request",
4558
- "`env` must map variable names to string values."
4559
- );
4560
- }
4561
- if (spec.stdin !== void 0 && typeof spec.stdin !== "string") {
4562
- throw new HostCommandError("invalid_request", "`stdin` must be a string.");
4563
- }
4564
- if ((spec.stdin?.length ?? 0) > hostCommandLimits.maxStdinBytes) {
4565
- throw new HostCommandError(
4566
- "invalid_request",
4567
- "`stdin` is larger than 5 MB."
4568
- );
4569
- }
4570
- const timeoutMs = background ? clampInt(
4571
- spec.timeoutMs,
4572
- hostCommandLimits.backgroundDefaultTimeoutMs,
4573
- hostCommandLimits.backgroundMaxTimeoutMs,
4574
- 1e3
4575
- ) : clampInt(
4576
- spec.timeoutMs,
4577
- hostCommandLimits.foregroundDefaultTimeoutMs,
4578
- hostCommandLimits.foregroundMaxTimeoutMs,
4579
- 100
4580
- );
4581
- const maxOutputBytes = clampInt(
4582
- spec.maxOutputBytes,
4583
- hostCommandLimits.defaultOutputBytes,
4584
- hostCommandLimits.maxOutputBytes,
4585
- 1024
4586
- );
4587
- if (spec.shell !== void 0 && (!hasCommand || spec.shell !== "powershell" && spec.shell !== "cmd")) {
4588
- throw new HostCommandError(
4589
- "invalid_request",
4590
- "`shell` goes with `command` and is 'powershell' or 'cmd' (Windows only)."
4591
- );
4592
- }
4593
- const env = { ...inheritedCommandEnv(), ...extraEnv };
4594
- const launch = this.#platform !== "win32" ? {
4595
- file: hasCommand ? shellFor(env) : spec.file,
4596
- argv: hasCommand ? ["-c", spec.command] : args,
4597
- verbatim: false
4598
- } : hasCommand ? windowsShellLaunch(
4599
- spec.command,
4600
- spec.shell ?? "powershell",
4601
- env
4602
- ) : windowsFileLaunch(spec.file, args, env);
4603
- return {
4604
- display,
4605
- cwd,
4606
- env,
4607
- envKeys: Object.keys(extraEnv).sort(),
4608
- stdin: spec.stdin,
4609
- timeoutMs,
4610
- maxOutputBytes,
4611
- file: launch.file,
4612
- argv: launch.argv,
4613
- verbatim: launch.verbatim
4614
- };
4615
- }
4616
- #spawn(prepared) {
4617
- const child = spawn3(prepared.file, prepared.argv, {
4618
- cwd: prepared.cwd,
4619
- env: prepared.env,
4620
- // POSIX: own a process group so killTree reaches grandchildren.
4621
- // Windows: taskkill /T walks the tree; detached would open a console.
4622
- detached: this.#platform !== "win32",
4623
- windowsHide: true,
4624
- windowsVerbatimArguments: prepared.verbatim,
4625
- stdio: [prepared.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
4626
- });
4627
- if (prepared.stdin !== void 0 && child.stdin) {
4628
- child.stdin.on("error", () => {
4629
- });
4630
- child.stdin.end(prepared.stdin);
4631
- }
4632
- return child;
4633
- }
4634
- #report(finished) {
4635
- const requeue = () => {
4636
- if (this.#unreported.length < 256) this.#unreported.push(finished);
4637
- };
4638
- const report = this.#onFinished;
4639
- if (!report) return requeue();
4640
- try {
4641
- void Promise.resolve(report(finished)).catch(requeue);
4642
- } catch {
4643
- requeue();
4644
- }
4645
- }
4646
- async run(raw, run) {
4647
- const prepared = await this.#prepare(raw, false);
4648
- const commandId = newCommandId();
4649
- await run.authorize({
4650
- commandId,
4651
- command: prepared.display,
4652
- cwd: prepared.cwd,
4653
- envKeys: prepared.envKeys,
4654
- background: false
4655
- });
4656
- this.assertAvailable();
4657
- const startedAt = Date.now();
4658
- const stdout = new OutputBuffer(prepared.maxOutputBytes);
4659
- const stderr = new OutputBuffer(prepared.maxOutputBytes);
4660
- const ended = { reason: "exited" };
4661
- const child = this.#spawn(prepared);
4662
- this.#foreground.set(child, ended);
4663
- child.stdout?.on("data", (chunk) => stdout.write(chunk));
4664
- child.stderr?.on("data", (chunk) => stderr.write(chunk));
4665
- const timer = setTimeout(() => {
4666
- ended.reason = "timed_out";
4667
- killTree(child, "SIGKILL");
4668
- }, prepared.timeoutMs);
4669
- const onAbort = () => {
4670
- ended.reason = "cancelled";
4671
- killTree(child, "SIGKILL");
4672
- };
4673
- run.signal.addEventListener("abort", onAbort, { once: true });
4674
- if (run.signal.aborted) onAbort();
4675
- const exited = await new Promise((resolve) => {
4676
- child.once(
4677
- "error",
4678
- (error) => resolve({ code: null, signal: null, error: error.message })
4679
- );
4680
- child.once("close", (code, signal) => resolve({ code, signal }));
4681
- });
4682
- const outcome = stoppedOutcome(exited, ended.reason !== "exited");
4683
- clearTimeout(timer);
4684
- this.#foreground.delete(child);
4685
- run.signal.removeEventListener("abort", onAbort);
4686
- if (outcome.error) ended.reason = "spawn_failed";
4687
- const durationMs = Date.now() - startedAt;
4688
- this.#report({
4689
- commandId,
4690
- runId: run.runId,
4691
- command: prepared.display,
4692
- cwd: prepared.cwd,
4693
- exitCode: outcome.code,
4694
- signal: outcome.signal,
4695
- durationMs,
4696
- background: false,
4697
- reason: ended.reason
4698
- });
4699
- if (outcome.error) {
4700
- throw new HostCommandError(
4701
- "invalid_request",
4702
- `Could not start the command: ${outcome.error}`
4703
- );
4704
- }
4705
- return {
4706
- commandId,
4707
- exitCode: outcome.code,
4708
- signal: outcome.signal,
4709
- timedOut: ended.reason === "timed_out",
4710
- stdout: stdout.text(),
4711
- stderr: stderr.text(),
4712
- stdoutTruncated: stdout.dropped > 0,
4713
- stderrTruncated: stderr.dropped > 0,
4714
- durationMs
4715
- };
4716
- }
4717
- async start(raw, run) {
4718
- this.#sweep();
4719
- const running = [...this.#jobs.values()].filter(
4720
- (job2) => job2.state === "running"
4721
- );
4722
- if (running.length + this.#pendingStarts >= hostCommandLimits.maxBackgroundJobs) {
4723
- throw new HostCommandError(
4724
- "invalid_request",
4725
- `This machine already runs ${running.length + this.#pendingStarts} background commands. Kill one (kody.command.kill) first.`
4726
- );
4727
- }
4728
- this.#pendingStarts++;
4729
- let prepared;
4730
- let commandId;
4731
- let child;
4732
- try {
4733
- prepared = await this.#prepare(raw, true);
4734
- commandId = newCommandId();
4735
- await run.authorize({
4736
- commandId,
4737
- command: prepared.display,
4738
- cwd: prepared.cwd,
4739
- envKeys: prepared.envKeys,
4740
- background: true
4741
- });
4742
- this.assertAvailable();
4743
- child = this.#spawn(prepared);
4744
- } finally {
4745
- this.#pendingStarts--;
4746
- }
4747
- const job = {
4748
- id: commandId,
4749
- runId: run.runId,
4750
- ownerUserId: run.requesterUserId,
4751
- command: prepared.display,
4752
- cwd: prepared.cwd,
4753
- child,
4754
- pid: child.pid,
4755
- startedAt: Date.now(),
4756
- endedAt: null,
4757
- exitCode: null,
4758
- signal: null,
4759
- state: "running",
4760
- stdout: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
4761
- stderr: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
4762
- done: Promise.resolve(),
4763
- timer: null,
4764
- error: null
4765
- };
4766
- child.stdout?.on("data", (chunk) => job.stdout.write(chunk));
4767
- child.stderr?.on("data", (chunk) => job.stderr.write(chunk));
4768
- job.timer = setTimeout(() => {
4769
- if (job.state !== "running") return;
4770
- job.state = "timed_out";
4771
- killTree(child, "SIGKILL");
4772
- }, prepared.timeoutMs);
4773
- job.timer.unref?.();
4774
- job.done = new Promise((resolve) => {
4775
- const finish = (code, signal, error) => {
4776
- if (job.endedAt !== null) return resolve();
4777
- if (job.timer) clearTimeout(job.timer);
4778
- ({ code, signal } = stoppedOutcome(
4779
- { code, signal },
4780
- job.state === "killed" || job.state === "timed_out"
4781
- ));
4782
- job.endedAt = Date.now();
4783
- job.exitCode = code;
4784
- job.signal = signal;
4785
- if (error) {
4786
- job.state = "failed";
4787
- job.error = error;
4788
- } else if (job.state === "running") {
4789
- job.state = "exited";
4790
- }
4791
- this.#report({
4792
- commandId,
4793
- runId: job.runId,
4794
- command: job.command,
4795
- cwd: job.cwd,
4796
- exitCode: code,
4797
- signal,
4798
- durationMs: job.endedAt - job.startedAt,
4799
- background: true,
4800
- reason: job.state === "failed" ? "spawn_failed" : job.state === "killed" ? job.error === "commands_off" ? "commands_off" : "killed" : job.state === "timed_out" ? "timed_out" : "exited"
4801
- });
4802
- resolve();
4803
- };
4804
- child.once("error", (error) => finish(null, null, error.message));
4805
- child.once("close", (code, signal) => finish(code, signal));
4806
- });
4807
- this.#jobs.set(commandId, job);
4808
- return {
4809
- commandId,
4810
- pid: job.pid ?? null,
4811
- startedAt: new Date(job.startedAt).toISOString(),
4812
- timeoutMs: prepared.timeoutMs
4813
- };
4814
- }
4815
- #job(raw, run) {
4816
- const id = typeof raw === "string" ? raw : raw?.commandId;
4817
- const job = typeof id === "string" ? this.#jobs.get(id) : void 0;
4818
- if (!job || job.ownerUserId !== run.requesterUserId) {
4819
- throw new HostCommandError(
4820
- "not_found",
4821
- `No background command ${String(id)} on this machine for you. kody.command.list() shows yours.`
4822
- );
4823
- }
4824
- return job;
4825
- }
4826
- #describe(job) {
4827
- return {
4828
- commandId: job.id,
4829
- command: job.command,
4830
- cwd: job.cwd,
4831
- state: job.state,
4832
- pid: job.pid ?? null,
4833
- exitCode: job.exitCode,
4834
- signal: job.signal,
4835
- startedAt: new Date(job.startedAt).toISOString(),
4836
- endedAt: job.endedAt === null ? null : new Date(job.endedAt).toISOString(),
4837
- durationMs: (job.endedAt ?? Date.now()) - job.startedAt,
4838
- stdoutBytes: job.stdout.total,
4839
- stderrBytes: job.stderr.total,
4840
- ...job.error && job.state === "failed" ? { error: job.error } : {}
4841
- };
4842
- }
4843
- status(raw, run) {
4844
- return this.#describe(this.#job(raw, run));
4845
- }
4846
- output(raw, run) {
4847
- const job = this.#job(raw, run);
4848
- const input = typeof raw === "object" && raw ? raw : {};
4849
- const maxBytes = clampInt(
4850
- input.maxBytes,
4851
- hostCommandLimits.defaultOutputBytes,
4852
- hostCommandLimits.maxOutputReadBytes
4853
- );
4854
- const stdout = job.stdout.read(
4855
- clampInt(input.stdoutOffset, 0, Number.MAX_SAFE_INTEGER, 0),
4856
- maxBytes
4857
- );
4858
- const stderr = job.stderr.read(
4859
- clampInt(input.stderrOffset, 0, Number.MAX_SAFE_INTEGER, 0),
4860
- maxBytes
4861
- );
4862
- return {
4863
- commandId: job.id,
4864
- state: job.state,
4865
- exitCode: job.exitCode,
4866
- stdout: stdout.text,
4867
- stderr: stderr.text,
4868
- stdoutOffset: stdout.next,
4869
- stderrOffset: stderr.next,
4870
- stdoutSkipped: stdout.skipped,
4871
- stderrSkipped: stderr.skipped,
4872
- done: job.state !== "running" && stdout.next >= job.stdout.total && stderr.next >= job.stderr.total
4873
- };
4874
- }
4875
- kill(raw, run) {
4876
- const job = this.#job(raw, run);
4877
- const requested = raw?.signal;
4878
- const signal = requested === "SIGINT" || requested === "SIGKILL" || requested === "SIGTERM" ? requested : "SIGTERM";
4879
- if (job.state === "running") {
4880
- job.state = "killed";
4881
- killTree(job.child, signal);
4882
- if (signal !== "SIGKILL") {
4883
- const escalate = setTimeout(() => killTree(job.child, "SIGKILL"), 5e3);
4884
- escalate.unref?.();
4885
- }
4886
- }
4887
- return this.#describe(job);
4888
- }
4889
- list(run) {
4890
- this.#sweep();
4891
- return {
4892
- commands: [...this.#jobs.values()].filter((job) => job.ownerUserId === run.requesterUserId).map((job) => this.#describe(job))
4893
- };
4894
- }
4895
- /** Commands were turned off (or the daemon stops): end every background job. */
4896
- killAll(reason) {
4897
- for (const [child, ended] of this.#foreground) {
4898
- ended.reason = reason === "commands_off" ? "commands_off" : "cancelled";
4899
- killTree(child, "SIGKILL");
4900
- }
4901
- for (const job of this.#jobs.values()) {
4902
- if (job.state !== "running") continue;
4903
- job.state = "killed";
4904
- job.error = reason === "commands_off" ? "commands_off" : null;
4905
- killTree(job.child, "SIGKILL");
4906
- }
4907
- }
4908
- /** Background jobs still running (auto-update waits for them). */
4909
- runningBackground() {
4910
- let count = 0;
4911
- for (const job of this.#jobs.values()) if (job.state === "running") count++;
4912
- return count;
4913
- }
4914
- async idle() {
4915
- await Promise.all([...this.#jobs.values()].map((job) => job.done));
4916
- }
4917
- #sweep() {
4918
- const cutoff = Date.now() - hostCommandLimits.keepFinishedJobsMs;
4919
- for (const [id, job] of this.#jobs) {
4920
- if (job.endedAt !== null && job.endedAt < cutoff) this.#jobs.delete(id);
4921
- }
4922
- }
4923
- };
4924
-
4925
- // src/execution-context/package-graph-cache.ts
4926
- import { createHash as createHash2 } from "node:crypto";
4927
- function createPackageGraphCache(options = {}) {
4928
- const maxEntries = options.maxEntries ?? 32;
4929
- const ttlMs = options.ttlMs ?? 6e4;
4930
- const now = options.now ?? Date.now;
4931
- const entries = /* @__PURE__ */ new Map();
4932
- return {
4933
- get size() {
4934
- return entries.size;
4935
- },
4936
- slot(scope) {
4937
- const key = createHash2("sha256").update(
4938
- JSON.stringify([
4939
- scope.apiUrl,
4940
- scope.userId,
4941
- scope.orgId,
4942
- scope.conversationId ?? null,
4943
- scope.code
4944
- ])
4945
- ).digest("hex");
4946
- return {
4947
- get: () => {
4948
- const entry = entries.get(key);
4949
- if (!entry) return void 0;
4950
- entries.delete(key);
4951
- if (entry.expiresAt <= now()) return void 0;
4952
- entries.set(key, entry);
4953
- return entry.graph;
4954
- },
4955
- set: (graph) => {
4956
- entries.delete(key);
4957
- entries.set(key, { graph, expiresAt: now() + ttlMs });
4958
- while (entries.size > maxEntries) {
4959
- const oldest = entries.keys().next().value;
4960
- if (oldest === void 0) break;
4961
- entries.delete(oldest);
4962
- }
4963
- }
4964
- };
4965
- }
4966
- };
4967
- }
4968
-
4969
- // src/execution-context/host-access.ts
4970
- var grantUsage = "Usage: kody context grant [show] [--context <name>] | kody context grant allow <path> [--mode ro|rw] [--context <name>] | kody context grant remove <path> [--context <name>] | kody context grant lan on|off [--context <name>]";
4971
- function arg(value) {
4972
- return /^[\w@%+=:,./\\-]+$/.test(value) ? value : JSON.stringify(value);
4973
- }
4974
- function overlaps(a, b) {
4975
- return isWithin(a, b) || isWithin(b, a);
4976
- }
4977
- function contextPageUrl(apiUrl, context) {
4978
- const slug = context.ownerOrg?.slug;
4979
- return slug ? `${apiUrl.replace(/\/+$/, "")}/@${slug}/-/execution-contexts/${context.id}` : null;
4980
- }
4981
- function lanState(mode) {
4982
- return mode === "public-and-lan" ? "on" : mode === "allowlist" ? "allowlist only" : "off";
4983
- }
4984
- function hostAccessNotes(context, policyFs) {
4985
- const name = arg(context.name);
4986
- const grantFs = context.hostAccess?.fs;
4987
- if (!grantFs) {
4988
- const count = context.grantSummary?.fs;
4989
- if (count === void 0) return [];
4990
- if (policyFs.length > 0 && count === 0) {
4991
- return [
4992
- `This machine's local policy allows host folders, but ${context.name}'s server grant lists none (grant.fs: 0), so runs cannot use them. Someone with Contribute or Manage on ${context.name} can turn it on with: kody context grant allow <folder> --mode ro|rw --context ${name}`
4993
- ];
4994
- }
4995
- if (policyFs.length === 0 && count > 0) {
4996
- return [
4997
- `${context.name}'s server grant lists host folders, but this machine's local policy allows none, so runs cannot use them. The machine owner can allow one with: kody context policy allow <folder> --mode ro|rw`
4998
- ];
4999
- }
5000
- return [];
5001
- }
5002
- const notes = [];
5003
- for (const rule of policyFs) {
5004
- if (grantFs.some((entry) => overlaps(entry.path, rule.path))) continue;
5005
- notes.push(
5006
- `${rule.path} (local policy ${rule.mode}) is not in ${context.name}'s server grant, so runs cannot use it. Turn it on with: kody context grant allow ${arg(rule.path)} --mode ${rule.mode} --context ${name}`
5007
- );
5008
- }
5009
- for (const entry of grantFs) {
5010
- if (policyFs.some((rule) => overlaps(entry.path, rule.path))) continue;
5011
- notes.push(
5012
- `${entry.path} (server grant ${entry.mode}) is not allowed by this machine's local policy, so runs cannot use it. The machine owner can allow it with: kody context policy allow ${arg(entry.path)} --mode ${entry.mode}`
5013
- );
5014
- }
5015
- return notes;
5016
- }
5017
- function describeServerGrant(apiUrl, context) {
5018
- const fs = context.hostAccess?.fs;
5019
- const egress = context.hostAccess?.egress.mode ?? context.grantSummary?.egress.mode;
5020
- const page = contextPageUrl(apiUrl, context);
5021
- return [
5022
- `Server grant for ${context.name} (Kody's side; changing it needs Contribute or Manage on the context):`,
5023
- fs ? fs.length === 0 ? " Host folders (grant.fs): none" : [
5024
- " Host folders (grant.fs):",
5025
- ...fs.map((entry) => ` ${entry.mode} ${entry.path}`)
5026
- ].join("\n") : ` Host folders (grant.fs): ${context.grantSummary?.fs ?? 0}`,
5027
- ...egress ? [` Local network (grant.egress ${egress}): ${lanState(egress)}`] : [],
5028
- ...page ? [` Page: ${page}`] : []
5029
- ].join("\n");
5030
- }
5031
- async function getContext(api, id) {
5032
- const body = await apiJson({
5033
- ...api,
5034
- method: "GET",
5035
- path: `/v1/execution-contexts/${encodeURIComponent(id)}`
5036
- });
5037
- return body.context;
5038
- }
5039
- async function resolveId(api, ref) {
5040
- if (ref.startsWith("ec_")) return ref;
5041
- const body = await apiJson({
5042
- ...api,
5043
- method: "GET",
5044
- path: "/v1/execution-contexts"
5045
- });
5046
- const match = (body.contexts ?? []).find((c) => c.name === ref);
5047
- if (!match) throw new Error(`No execution context named ${ref} in this org.`);
5048
- return match.id;
5049
- }
5050
- async function machineGrantNotes(input) {
5051
- const ids = storedContextIds(input.apiUrl);
5052
- if (ids.length === 0) return [];
5053
- let token;
5054
- try {
5055
- token = await input.token();
5056
- } catch (error) {
5057
- return [
5058
- {
5059
- id: null,
5060
- name: null,
5061
- notes: [],
5062
- error: `Could not check the server grant (grant.fs) for this machine's contexts: ${firstLine(error)}`
5063
- }
5064
- ];
5065
- }
5066
- return await Promise.all(
5067
- ids.map(async (id) => {
5068
- try {
5069
- const context = await getContext({ ...input, token }, id);
5070
- return {
5071
- id,
5072
- name: context.name,
5073
- notes: hostAccessNotes(context, input.policyFs)
5074
- };
5075
- } catch (error) {
5076
- return {
5077
- id,
5078
- name: null,
5079
- notes: [],
5080
- error: `Could not check the server grant for ${id}: ${firstLine(error)}`
5081
- };
5082
- }
5083
- })
5084
- );
5085
- }
5086
- function describeMachineGrantNotes(results) {
5087
- if (results.length === 0) return "";
5088
- const lines = results.flatMap(
5089
- (result) => "error" in result && result.error ? [` ${result.error}`] : result.notes.length === 0 ? [` ${result.name}: server grant and local policy agree.`] : result.notes.map((note) => ` ${note}`)
5090
- );
5091
- return `
5092
- Server grant check (a run can use a folder only if both layers allow it):
5093
- ${lines.join("\n")}`;
5094
- }
5095
- function firstLine(error) {
5096
- return (error instanceof Error ? error.message : String(error)).split("\n")[0];
5097
- }
5098
- async function runGrantCommand(input) {
5099
- const [action = "show", target, ...extra] = input.positionals;
5100
- const valid = action === "show" && target === void 0 || (action === "allow" || action === "remove") && target !== void 0 || action === "lan" && (target === "on" || target === "off");
5101
- if (!valid || extra.length > 0) throw new Error(grantUsage);
5102
- const ref = input.values.context ?? localContextId(input.apiUrl);
5103
- if (!ref) {
5104
- throw new Error(
5105
- `No execution context is registered on this machine; pass --context <name>.
5106
- ${grantUsage}`
5107
- );
5108
- }
5109
- const api = {
5110
- apiUrl: input.apiUrl,
5111
- ...input.org ? { org: input.org } : {},
5112
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
5113
- token: await input.token()
5114
- };
5115
- const onThisMachine = localContextId(input.apiUrl, ref);
5116
- const id = onThisMachine ?? await resolveId(api, ref);
5117
- let context = await getContext(api, id);
5118
- const emit = async (summary) => {
5119
- const policy = onThisMachine ? await readLocalPolicy() : null;
5120
- const notes = policy ? hostAccessNotes(context, policy.fs) : [];
5121
- const text = [
5122
- ...summary ? [summary] : [],
5123
- describeServerGrant(input.apiUrl, context),
5124
- ...notes.length > 0 ? [
5125
- "This machine (a run can use a folder only if both layers allow it):",
5126
- ...notes.map((note) => ` ${note}`)
5127
- ] : []
5128
- ].join("\n");
5129
- input.write(
5130
- input.values.json ? `${JSON.stringify({ context, ...policy ? { localPolicy: policy.fs, notes } : {} }, null, 2)}
5131
- ` : `${text}
5132
- `
5133
- );
5134
- return 0;
5135
- };
5136
- if (action === "show") return await emit(null);
5137
- const access = context.hostAccess;
5138
- if (!access) {
5139
- throw new Error(
5140
- `Changing ${context.name}'s server grant needs Contribute or Manage on it (the same check as executionContextUpdate). Ask its operator or someone who manages it${contextPageUrl(input.apiUrl, context) ? `: ${contextPageUrl(input.apiUrl, context)}` : "."}`
5141
- );
5142
- }
5143
- const patch = async (grant) => {
5144
- const body = await apiJson({
5145
- ...api,
5146
- method: "PATCH",
5147
- path: `/v1/execution-contexts/${encodeURIComponent(id)}`,
5148
- body: { grant }
5149
- });
5150
- context = body.context ?? context;
5151
- };
5152
- if (action === "lan") {
5153
- const mode2 = access.egress.mode;
5154
- if (target === "on") {
5155
- if (mode2 === "public-and-lan") {
5156
- return await emit(
5157
- `The local network is already on for ${context.name}.`
5158
- );
5159
- }
5160
- if (mode2 !== "public") {
5161
- throw new Error(
5162
- `${context.name}'s egress is ${mode2}, not public. \`kody context grant lan on\` only switches public to public-and-lan; change a ${mode2} egress with executionContextUpdate grant.egress or on the context page.`
5163
- );
5164
- }
5165
- await patch({ egress: { mode: "public-and-lan" } });
5166
- return await emit(
5167
- `Turned the local network on in ${context.name}'s server grant (grant.egress public-and-lan).`
5168
- );
5169
- }
5170
- if (mode2 !== "public-and-lan") {
5171
- return await emit(`The local network is already off for ${context.name}.`);
5172
- }
5173
- await patch({ egress: { mode: "public" } });
5174
- return await emit(
5175
- `Turned the local network off in ${context.name}'s server grant (grant.egress public).`
5176
- );
5177
- }
5178
- const raw = plainPath(target);
5179
- if (!isAbsolute(raw)) throw new Error(`${target} is not an absolute path.`);
5180
- const path = onThisMachine ? await canonicalHostPath(raw).catch((error) => {
5181
- if (action === "remove") return raw;
5182
- throw error;
5183
- }) : raw;
5184
- const rest = access.fs.filter((entry) => !samePath(entry.path, path));
5185
- if (action === "remove") {
5186
- if (rest.length === access.fs.length) {
5187
- return await emit(`${path} was not in ${context.name}'s server grant.`);
5188
- }
5189
- await patch({ fs: rest });
5190
- return await emit(`Removed ${path} from ${context.name}'s server grant.`);
5191
- }
5192
- const mode = input.values.mode ?? "ro";
5193
- if (mode !== "ro" && mode !== "rw") {
5194
- throw new Error("--mode must be ro (read-only) or rw (read-write).");
5195
- }
5196
- const fs = [...rest, { path, mode }].sort(
5197
- (a, b) => a.path.localeCompare(b.path)
5198
- );
5199
- await patch({ fs });
5200
- return await emit(
5201
- `Added ${path} (${mode}) to ${context.name}'s server grant. Running daemons pick this up right away.`
5202
- );
5203
- }
5204
-
5205
- // src/execution-context/worker-tracker.ts
5206
- import { execFileSync as execFileSync3 } from "node:child_process";
5207
- import {
5208
- mkdirSync as mkdirSync5,
5209
- readFileSync as readFileSync7,
5210
- readdirSync as readdirSync3,
5211
- rmSync as rmSync5,
5212
- writeFileSync as writeFileSync5
5213
- } from "node:fs";
5214
- import { dirname as dirname5, join as join4 } from "node:path";
5215
- var defaultOps = {
5216
- isAlive(pid) {
5217
- try {
5218
- process.kill(pid, 0);
5219
- return true;
5220
- } catch (error) {
5221
- return error.code === "EPERM";
5222
- }
5223
- },
5224
- commandLine(pid) {
5225
- try {
5226
- if (process.platform === "linux") {
5227
- return readFileSync7(`/proc/${pid}/cmdline`, "utf8").replaceAll(
5228
- "\0",
5229
- " "
5230
- );
5231
- }
5232
- if (process.platform === "win32") return windowsCommandLine(pid);
5233
- return execFileSync3("ps", ["-p", String(pid), "-o", "command="], {
5234
- encoding: "utf8",
5235
- stdio: ["ignore", "pipe", "ignore"]
5236
- });
5237
- } catch {
5238
- return null;
5239
- }
5240
- },
5241
- kill(pid) {
5242
- try {
5243
- process.kill(pid, "SIGKILL");
5244
- } catch {
5245
- }
5246
- }
5247
- };
5248
- function readRecord(path) {
5249
- try {
5250
- const value = JSON.parse(readFileSync7(path, "utf8"));
5251
- return Number.isInteger(value.pid) && value.pid > 0 && typeof value.configPath === "string" && value.configPath.endsWith("config.capnp") && Number.isInteger(value.ownerPid) ? value : null;
5252
- } catch {
5253
- return null;
5254
- }
5255
- }
5256
- function reapLeftoverWorkers(dir, input = {}) {
5257
- const ops = input.ops ?? defaultOps;
5258
- const selfPid = input.selfPid ?? process.pid;
5259
- let entries;
5260
- try {
5261
- entries = readdirSync3(dir).filter((name) => name.endsWith(".json"));
5262
- } catch {
5263
- return [];
5264
- }
5265
- const killed = [];
5266
- for (const name of entries) {
5267
- const path = join4(dir, name);
5268
- const record = readRecord(path);
5269
- if (!record) {
5270
- rmSync5(path, { force: true });
5271
- continue;
5272
- }
5273
- if (record.ownerPid !== selfPid && ops.isAlive(record.ownerPid)) continue;
5274
- if (ops.isAlive(record.pid) && ops.commandLine(record.pid)?.includes(record.configPath)) {
5275
- ops.kill(record.pid);
5276
- killed.push(record.pid);
5277
- }
5278
- rmSync5(dirname5(record.configPath), { recursive: true, force: true });
5279
- rmSync5(path, { force: true });
5280
- }
5281
- return killed;
5282
- }
5283
- function createLocalWorkerTracker(dir, input = {}) {
5284
- const ops = input.ops ?? defaultOps;
5285
- const live = /* @__PURE__ */ new Set();
5286
- const recordPath = (pid) => join4(dir, `${pid}.json`);
5287
- const killAll = () => {
5288
- for (const pid of live) {
5289
- ops.kill(pid);
5290
- rmSync5(recordPath(pid), { force: true });
5291
- }
5292
- live.clear();
5293
- };
5294
- process.on("exit", killAll);
5295
- return {
5296
- started({ pid, configPath }) {
5297
- live.add(pid);
5298
- try {
5299
- mkdirSync5(dir, { recursive: true, mode: 448 });
5300
- const record = {
5301
- pid,
5302
- configPath,
5303
- ownerPid: process.pid
5304
- };
5305
- writeFileSync5(recordPath(pid), JSON.stringify(record), {
5306
- mode: 384
5307
- });
5308
- } catch {
5309
- }
5310
- },
5311
- exited(pid) {
5312
- live.delete(pid);
5313
- rmSync5(recordPath(pid), { force: true });
5314
- },
5315
- killAll,
5316
- dispose() {
5317
- process.off("exit", killAll);
5318
- }
5319
- };
5320
- }
5321
-
5322
- // src/execution-context/commands.ts
5323
- var defaultMaxConcurrentRuns = 2;
5324
- var loginCheckIntervalMs = 6 * 60 * 6e4;
5325
- function maxConcurrentRuns(value = process.env.KODY_CONTEXT_MAX_CONCURRENT) {
5326
- if (value === void 0 || value === "") return defaultMaxConcurrentRuns;
5327
- const parsed = Number(value);
5328
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > ecpMaxConcurrentRunsCap) {
5329
- throw new Error(
5330
- `--max-concurrent (or KODY_CONTEXT_MAX_CONCURRENT) must be a whole number from 1 to ${ecpMaxConcurrentRunsCap}; got ${value}.`
5331
- );
5332
- }
5333
- return parsed;
5334
- }
5335
- function localCapabilities(maxConcurrent = defaultMaxConcurrentRuns) {
5336
- return {
5337
- runtime: "workerd",
5338
- node: process.versions.node,
5339
- os: platform(),
5340
- cpuCount: cpus().length,
5341
- memoryMb: Math.round(totalmem() / (1024 * 1024)),
5342
- maxConcurrent,
5343
- features: []
5344
- };
5345
- }
5346
- function out(input, value, text) {
5347
- input.write(
5348
- input.values.json ? `${JSON.stringify(value, null, 2)}
5349
- ` : `${text}
5350
- `
5351
- );
5352
- }
5353
- async function runExecutionContextCommand(input) {
5354
- try {
5355
- return await runCommand2(input);
5356
- } catch (error) {
5357
- if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
5358
- throw error;
5359
- }
5360
- }
5361
- async function runCommand2(input) {
5362
- const [sub, ...rest] = input.positionals;
5363
- const base = {
5364
- apiUrl: input.apiUrl,
5365
- ...input.org ? { org: input.org } : {},
5366
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
5367
- };
5368
- if (input.command === "context" && sub === "commands") {
5369
- return await runCommandsOptInCommand(input, rest);
5370
- }
5371
- if (input.command === "context" && sub === "policy") {
5372
- return await runPolicyCommand(input, rest);
5373
- }
5374
- if (input.command === "context" && sub === "grant") {
5375
- return await runGrantCommand({ ...input, ...base, positionals: rest });
5376
- }
5377
- const serviceEnv = {
5378
- apiUrl: input.apiUrl,
5379
- clientVersion: input.clientVersion,
5380
- write: input.write,
5381
- ...input.values.json ? { json: true } : {},
5382
- ...input.values.yes ? { yes: true } : {},
5383
- confirm: input.values.json ? null : terminalConfirm(),
5384
- ...input.service
5385
- };
5386
- const maxConcurrentFlag = () => {
5387
- if (input.values.maxConcurrent === "") {
5388
- throw new Error("--max-concurrent needs a value.");
5389
- }
5390
- return input.values.maxConcurrent === void 0 ? void 0 : maxConcurrentRuns(input.values.maxConcurrent);
5391
- };
5392
- if (input.command === "update") return await runUpdate(serviceEnv);
5393
- if (input.command === "daemon" && sub === "env") {
5394
- return await runDaemonEnvCommand(serviceEnv, {
5395
- action: rest[0],
5396
- args: rest.slice(1),
5397
- ...input.values.context ? { context: input.values.context } : {}
5398
- });
5399
- }
5400
- if (input.command === "daemon" && sub === "install" && input.values.env?.length) {
5401
- await saveServiceEnvAssignments(input.values.env);
5402
- }
5403
- if (input.command === "daemon" && sub === "auto-update") {
5404
- return await runAutoUpdateCommand(serviceEnv, rest[0]);
5405
- }
5406
- if (input.command === "daemon" && isRemoteDaemonCommand({
5407
- sub,
5408
- apiUrl: input.apiUrl,
5409
- ...input.values.context ? { context: input.values.context } : {},
5410
- ...input.values.remote ? { remote: true } : {}
5411
- })) {
5412
- return await runRemoteDaemonCommand({
5413
- ...base,
5414
- sub,
5415
- args: rest,
5416
- token: input.token,
5417
- write: input.write,
5418
- ...input.values.context ? { context: input.values.context } : {},
5419
- ...input.values.reason ? { reason: input.values.reason } : {},
5420
- ...input.values.cancelRuns ? { cancelRuns: true } : {},
5421
- ...input.values.lines ? { lines: input.values.lines } : {},
5422
- ...input.values.json ? { json: true } : {}
5423
- });
5424
- }
5425
- if (input.command === "daemon" && sub === "update") {
5426
- return await runUpdate(serviceEnv);
5427
- }
5428
- if (input.command === "daemon" && sub !== void 0) {
5429
- const maxConcurrent = maxConcurrentFlag();
5430
- return await runDaemonServiceCommand(serviceEnv, {
5431
- sub,
5432
- ...input.values.context ? { context: input.values.context } : {},
5433
- ...maxConcurrent === void 0 ? {} : { maxConcurrent },
5434
- ...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
5435
- ...input.values.lines ? { lines: input.values.lines } : {},
5436
- ...input.values.follow ? { follow: true } : {},
5437
- ...input.values.unregister === void 0 ? {} : { unregister: input.values.unregister },
5438
- revoke: async (ecid) => {
5439
- await apiJson({
5440
- ...base,
5441
- token: await input.token(),
5442
- method: "DELETE",
5443
- path: `/v1/execution-contexts/${encodeURIComponent(ecid)}`
5444
- });
5445
- }
5446
- });
5447
- }
5448
- if (input.command === "connect" && !input.values.name && !sub && localContextId(input.apiUrl, input.values.context)) {
5449
- const ecid = localContextId(input.apiUrl, input.values.context);
5450
- input.write(`This machine is already registered as ${ecid}.
5451
- `);
5452
- const maxConcurrent = maxConcurrentFlag();
5453
- await offerInstall(serviceEnv, {
5454
- ecid,
5455
- install: input.values.install ?? true,
5456
- ...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
5457
- ...maxConcurrent === void 0 ? {} : { maxConcurrent }
5458
- });
5459
- return 0;
5460
- }
5461
- if (input.command === "context" && sub === "register" || input.command === "connect") {
5462
- const connect = input.command === "connect";
5463
- const name = input.values.name ?? (connect ? sub : rest[0]);
5464
- if (!name) throw new Error("Pass --name <name> for this machine.");
5465
- const maxConcurrent = maxConcurrentFlag();
5466
- if (input.values.keyStorage !== void 0 && input.values.keyStorage !== "file" && input.values.keyStorage !== "keyring") {
5467
- throw new Error("--key-storage must be keyring or file.");
5468
- }
5469
- const wrappingFor = async (ecid) => {
5470
- if (input.values.keyStorage === "file") {
5471
- return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
5472
- }
5473
- try {
5474
- const source = resolveWrappingKey({ ecid, create: true });
5475
- if (source.kind === "keyring") source.key(Buffer.alloc(16));
5476
- return source;
5477
- } catch (error) {
5478
- if (input.values.keyStorage === "keyring") throw error;
5479
- const question = `No unlocked OS keyring is available (${error instanceof Error ? error.message : String(error)}).
5480
- Store the machine key wrapping key in a file instead (only readable by your user, 600 permissions, in the kody state directory)?`;
5481
- const useFile = serviceEnv.yes ? true : serviceEnv.confirm ? await serviceEnv.confirm(question, true) : false;
5482
- if (!useFile) {
5483
- throw new Error(
5484
- `${error instanceof Error ? error.message : String(error)} Or re-run with --key-storage file.`
5485
- );
5486
- }
5487
- return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
5488
- }
5489
- };
5490
- const { publicKeyJwk, privateKeyJwk } = await generateContextKey();
5491
- const privateKey = await importContextKey(privateKeyJwk);
5492
- const thumbprint = await ed25519JwkThumbprint(publicKeyJwk);
5493
- const registered = await registerContext({
5494
- ...base,
5495
- token: await input.token(),
5496
- name,
5497
- publicKeyJwk,
5498
- privateKey,
5499
- thumbprint,
5500
- capabilities: localCapabilities(),
5501
- client: { name: "kody-cli", version: input.clientVersion }
5502
- });
5503
- try {
5504
- saveContext({
5505
- context: {
5506
- version: 1,
5507
- ecid: registered.ecid,
5508
- name: registered.name,
5509
- apiUrl: input.apiUrl,
5510
- orgSlug: registered.owner.orgSlug,
5511
- publicKeyJwk
5512
- },
5513
- privateJwk: privateKeyJwk,
5514
- wrapping: await wrappingFor(registered.ecid)
5515
- });
5516
- } catch (error) {
5517
- const path = `/v1/execution-contexts/${encodeURIComponent(registered.ecid)}`;
5518
- const token = await input.token();
5519
- await apiJson({ ...base, token, method: "DELETE", path }).then(
5520
- () => apiJson({ ...base, token, method: "POST", path: `${path}/delete` })
5521
- ).catch(() => {
5522
- });
5523
- throw error;
5524
- }
5525
- const steps = (registered.nextSteps ?? []).map(
5526
- (step) => ` ${step.text ?? ""}${step.cli ? `
5527
- ${step.cli}` : ""}`
5528
- ).join("\n");
5529
- out(
5530
- input,
5531
- registered,
5532
- [
5533
- registered.notice ?? `Registered ${registered.name} (${registered.ecid}).`,
5534
- steps ? `Next steps:
5535
- ${steps}` : ""
5536
- ].filter(Boolean).join("\n")
5537
- );
5538
- if (input.values.json && input.values.install === void 0) return 0;
5539
- const install = {
5540
- ecid: registered.ecid,
5541
- ...input.values.install !== void 0 ? { install: input.values.install } : connect && !serviceEnv.confirm ? { install: true } : {},
5542
- ...maxConcurrent === void 0 ? {} : { maxConcurrent }
5543
- };
5544
- if (input.values.install === true) {
5545
- const installEnv = input.values.json ? {
5546
- ...serviceEnv,
5547
- write: (text) => {
5548
- process.stderr.write(text);
5549
- }
5550
- } : serviceEnv;
5551
- return await offerInstall(installEnv, install) ? 0 : 1;
5552
- }
5553
- try {
5554
- await offerInstall(serviceEnv, install);
5555
- } catch (error) {
5556
- input.write(
5557
- `Registered, but the background service was not installed: ${error instanceof Error ? error.message : String(error)}
5558
- Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --context ${registered.ecid}
5559
- `
5560
- );
5561
- }
5562
- return 0;
5563
- }
5564
- if (input.command === "context" && (sub === "list" || sub === void 0)) {
5565
- const body = await apiJson({
5566
- ...base,
5567
- token: await input.token(),
5568
- method: "GET",
5569
- path: "/v1/execution-contexts"
5570
- });
5571
- const contexts = body.contexts ?? [];
5572
- const local = new Set(storedContextIds(input.apiUrl));
5573
- const policyFs = contexts.some((c) => local.has(c.id)) ? (await readLocalPolicy()).fs : [];
5574
- const notesFor = (c) => local.has(c.id) ? hostAccessNotes(c, policyFs) : [];
5575
- out(
5576
- input,
5577
- {
5578
- ...body,
5579
- ...local.size > 0 ? {
5580
- thisMachine: {
5581
- localPolicy: policyFs,
5582
- notes: Object.fromEntries(
5583
- contexts.filter((c) => local.has(c.id)).map((c) => [c.name, notesFor(c)])
5584
- )
5585
- }
5586
- } : {}
5587
- },
5588
- contexts.length === 0 ? "No execution contexts yet. Register this machine with `kody context register --name <name>`." : contexts.map(
5589
- (c) => [
5590
- `${c.name} (${c.id}) ${c.status}${c.usable ? "" : `, not usable: ${c.unusableReason}`}${c.grantSummary ? `; server grant: ${c.grantSummary.fs} host folder${c.grantSummary.fs === 1 ? "" : "s"}, LAN ${lanState(c.grantSummary.egress.mode)}` : ""}${local.has(c.id) ? " (this machine)" : ""}`,
5591
- ...notesFor(c).map((note) => ` ${note}`)
5592
- ].join("\n")
5593
- ).join("\n")
5594
- );
5595
- return 0;
5596
- }
5597
- if (input.command === "context" && (sub === "revoke" || sub === "delete")) {
5598
- const ref = rest[0];
5599
- if (!ref) throw new Error(`Usage: kody context ${sub} <name|ec id>`);
5600
- const id = encodeURIComponent(ref);
5601
- const body = await apiJson({
5602
- ...base,
5603
- token: await input.token(),
5604
- ...sub === "revoke" ? { method: "DELETE", path: `/v1/execution-contexts/${id}` } : { method: "POST", path: `/v1/execution-contexts/${id}/delete` }
5605
- });
5606
- out(
5607
- input,
5608
- body,
5609
- sub === "revoke" ? `Revoked ${ref}. Delete it for good with: kody context delete ${ref}` : `Deleted ${ref}.`
5610
- );
5611
- const revokedId = typeof body.id === "string" ? body.id : typeof body.context?.id === "string" ? body.context.id : null;
5612
- await offerUninstallAfterRevoke(
5613
- input.values.json ? { ...serviceEnv, write: () => {
5614
- } } : serviceEnv,
5615
- {
5616
- ref,
5617
- ecid: revokedId && localContextId(input.apiUrl, revokedId) ? revokedId : null
5618
- }
5619
- );
5620
- return 0;
5621
- }
5622
- if (input.command === "context" && sub === "cancel-run") {
5623
- const [ref, runId] = rest;
5624
- if (!ref || !runId) {
5625
- throw new Error("Usage: kody context cancel-run <name|ec id> <run id>");
5626
- }
5627
- const body = await apiJson({
5628
- ...base,
5629
- token: await input.token(),
5630
- method: "POST",
5631
- path: `/v1/execution-contexts/${encodeURIComponent(ref)}/runs/${encodeURIComponent(runId)}/cancel`
5632
- });
5633
- out(
5634
- input,
5635
- body,
5636
- body.cancelled === true ? `Cancelled run ${runId} on ${ref}.` : `Run ${runId} already ended (${typeof body.state === "string" ? body.state : "finished"}).`
5637
- );
5638
- return 0;
5639
- }
5640
- if (input.command === "chain") {
5641
- const token = await input.token();
5642
- const read = await apiJson({
5643
- ...base,
5644
- token,
5645
- method: "GET",
5646
- path: "/v1/execution-chain"
5647
- });
5648
- const current = chainOf(read);
5649
- const contexts = async () => contextsById(
5650
- await apiJson({
5651
- ...base,
5652
- token,
5653
- method: "GET",
5654
- path: "/v1/execution-contexts"
5655
- })
5656
- );
5657
- const contextMetadata = async () => {
5658
- if (input.values.json) return /* @__PURE__ */ new Map();
5659
- try {
5660
- return await contexts();
5661
- } catch {
5662
- return /* @__PURE__ */ new Map();
5663
- }
5664
- };
5665
- if (sub === "show" || sub === void 0) {
5666
- out(input, read, describeChain(current, await contextMetadata()));
5667
- return 0;
5668
- }
5669
- if (sub !== "add" && sub !== "remove") {
5670
- throw new Error("Usage: kody chain show | add <name> | remove <name>");
5671
- }
5672
- const ref = rest[0];
5673
- if (!ref) throw new Error(`Pass the context name: kody chain ${sub} <name>`);
5674
- const id = await resolveContextId({
5675
- ...base,
5676
- token,
5677
- ref
5678
- });
5679
- const entries = (current.entries ?? []).map(
5680
- (entry) => entry.kind === "cloud" ? { kind: "cloud" } : { kind: "context", id: entry.id }
5681
- ).filter((entry) => !(entry.kind === "context" && entry.id === id));
5682
- if (sub === "add") {
5683
- if (entries.length === 0) entries.push({ kind: "cloud" });
5684
- const cloudAt = entries.findIndex((entry) => entry.kind === "cloud");
5685
- entries.splice(cloudAt === -1 ? entries.length : cloudAt, 0, {
5686
- kind: "context",
5687
- id
5688
- });
5689
- }
5690
- const updated = await apiJson({
5691
- ...base,
5692
- token,
5693
- method: "PUT",
5694
- path: "/v1/execution-chain",
5695
- body: {
5696
- entries,
5697
- strict: !entries.some((entry) => entry.kind === "cloud"),
5698
- ifMatch: current.updatedAt ?? null
5699
- }
5700
- });
5701
- out(
5702
- input,
5703
- updated,
5704
- describeChain(chainOf(updated), await contextMetadata())
5705
- );
5706
- return 0;
5707
- }
5708
- if (input.command === "daemon") {
5709
- if (input.values.maxConcurrent === "") {
5710
- throw new Error("--max-concurrent needs a value.");
5711
- }
5712
- const maxConcurrent = maxConcurrentRuns(input.values.maxConcurrent);
5713
- const ecid = input.values.context ? localContextId(input.apiUrl, input.values.context) ?? input.values.context : storedContextIds(input.apiUrl)[0];
5714
- if (!ecid) {
5715
- throw new Error(
5716
- "This machine has no registered execution context. Run `kody connect --name <name>` first."
5717
- );
5718
- }
5719
- const asService = process.env[serviceEnvVar];
5720
- const manager = isServiceManager(asService) ? asService : null;
5721
- const paths = manager ? servicePaths({ apiUrl: input.apiUrl, ecid, manager }) : null;
5722
- const supervised = process.env[supervisedEnvVar] === "1";
5723
- if (paths && !supervised) rotateLog(paths.logPath);
5724
- if (paths && manager === "taskscheduler") appendOutputTo(paths.logPath);
5725
- const readAutoUpdate = async () => autoUpdateSetting(await readLocalPolicy().catch(() => null));
5726
- const relaunchArgs = [
5727
- "daemon",
5728
- "--context",
5729
- ecid,
5730
- "--api-url",
5731
- input.apiUrl,
5732
- ...input.values.maxConcurrent === void 0 ? [] : ["--max-concurrent", input.values.maxConcurrent]
5733
- ];
5734
- const recentLog = [];
5735
- const log = (line) => {
5736
- recentLog.push(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
5737
- if (recentLog.length > daemonLogBufferLines) recentLog.shift();
5738
- input.write(`${line}
5739
- `);
5740
- };
5741
- if (!supervised && (await readAutoUpdate()).enabled) {
5742
- const newer = newerInstalledVersion({ selfVersion: input.clientVersion });
5743
- if (newer) {
5744
- const outcome = await superviseNewerVersion({
5745
- first: newer,
5746
- selfVersion: input.clientVersion,
5747
- args: relaunchArgs,
5748
- log
5749
- });
5750
- if (outcome.kind === "exit") return outcome.code;
5751
- }
5752
- }
5753
- let started;
5754
- try {
5755
- const { context: context2, privateJwk } = loadContext({
5756
- apiUrl: input.apiUrl,
5757
- ecid,
5758
- wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
5759
- });
5760
- started = {
5761
- context: context2,
5762
- privateKey: await importContextKey(privateJwk),
5763
- serverKeys: await fetchServerKeys({ apiUrl: input.apiUrl })
5764
- };
5765
- } catch (error) {
5766
- if (!supervised) throw error;
5767
- log(
5768
- `Could not start: ${error instanceof Error ? error.message : String(error)}`
5769
- );
5770
- return startupRefusedExitCode;
5771
- }
5772
- const { context, privateKey } = started;
5773
- let { serverKeys } = started;
5774
- const { runContextRun } = await import("./run-executor-NMZGN2MG.js");
5775
- const hostCommands = new HostCommands({
5776
- localEnabled: await readLocalCommandsEnabled().catch(() => false)
5777
- });
5778
- const commandsPolicyPath = localPolicyPath();
5779
- const onCommandsPolicyChange = () => {
5780
- void readLocalCommandsEnabled().catch(() => false).then((enabled) => hostCommands.setLocalEnabled(enabled));
5781
- };
5782
- watchFile(commandsPolicyPath, { interval: 2e3 }, onCommandsPolicyChange);
5783
- const lockStatePath = servicePaths({
5784
- apiUrl: input.apiUrl,
5785
- ecid,
5786
- manager: serviceManagerFor() ?? "systemd"
5787
- }).statePath;
5788
- const launcher = manager ?? (process.env[launcherEnvVar] === "desktop" ? "desktop" : "terminal");
5789
- const lockInfo = {
5790
- version: input.clientVersion,
5791
- launcher,
5792
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
5793
- };
5794
- let lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
5795
- if (!lock.ok && manager) {
5796
- let holder = lock.holder;
5797
- log(
5798
- `Another kody daemon already runs ${context.name} (${describeHolder(holder)}). One runner per context: this service waits for it to stop instead of replacing it.`
5799
- );
5800
- let stopWaiting = false;
5801
- const onWaitSignal = () => {
5802
- stopWaiting = true;
5803
- };
5804
- process.on("SIGINT", onWaitSignal);
5805
- process.on("SIGTERM", onWaitSignal);
5806
- try {
5807
- while (!lock.ok && !stopWaiting) {
5808
- await new Promise((resolve) => setTimeout(resolve, 15e3));
5809
- lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
5810
- if (!lock.ok && lock.holder.pid !== holder.pid) {
5811
- holder = lock.holder;
5812
- log(
5813
- `The runner for ${context.name} is now ${describeHolder(holder)}. Still waiting.`
5814
- );
5815
- }
5816
- }
5817
- } finally {
5818
- process.off("SIGINT", onWaitSignal);
5819
- process.off("SIGTERM", onWaitSignal);
5820
- }
5821
- if (!lock.ok) {
5822
- unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
5823
- return stayStoppedExitCode;
5824
- }
5825
- log(`The other daemon stopped. Starting ${context.name}.`);
5826
- serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
5827
- }
5828
- if (!lock.ok) {
5829
- unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
5830
- 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).`;
5831
- if (!supervised) throw new Error(message);
5832
- log(message);
5833
- return startupRefusedExitCode;
5834
- }
5835
- const releaseLock = lock.release;
5836
- const abort = new AbortController();
5837
- const drain = new AbortController();
5838
- let hardStop;
5839
- let signalled = false;
5840
- let signalledAt = 0;
5841
- let updateTo = null;
5842
- let forcedUpdate = false;
5843
- let restartRequested = false;
5844
- let paused = null;
5845
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
5846
- const onSignal = () => {
5847
- if (signalled) {
5848
- if (Date.now() - signalledAt < 2e3) return;
5849
- return abort.abort();
5850
- }
5851
- signalled = true;
5852
- signalledAt = Date.now();
5853
- updateTo = null;
5854
- if (!drain.signal.aborted) drain.abort();
5855
- hardStop = setTimeout(() => abort.abort(), 8e4);
5856
- hardStop.unref();
5857
- };
5858
- process.on("SIGINT", onSignal);
5859
- process.on("SIGTERM", onSignal);
5860
- input.write(
5861
- `Starting ${context.name} (${context.ecid}) against ${input.apiUrl}${manager ? ` as a ${manager} service` : ""}.
5862
- `
5863
- );
5864
- if (!manager && serviceManagerFor()) {
5865
- input.write(
5866
- "Tip: keep it running after reboots and crashes with: kody daemon install\n"
5867
- );
5868
- }
5869
- const statePath = servicePaths({
5870
- apiUrl: input.apiUrl,
5871
- ecid,
5872
- manager: serviceManagerFor() ?? "systemd"
5873
- }).statePath;
5874
- writeJson(statePath, {
5875
- pid: process.pid,
5876
- version: input.clientVersion,
5877
- service: manager,
5878
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
5879
- ...supervised ? { supervisorPid: process.ppid } : {}
5880
- });
5881
- const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
5882
- const reaped = reapLeftoverWorkers(workersDir);
5883
- if (reaped.length > 0) {
5884
- input.write(
5885
- `Stopped ${reaped.length} local worker(s) left running by an earlier daemon for this context.
5886
- `
5887
- );
5888
- }
5889
- const workerTracker = createLocalWorkerTracker(workersDir);
5890
- const packageGraphCache = createPackageGraphCache();
5891
- let stop = "shutdown";
5892
- let autoUpdateEnabled = (await readAutoUpdate()).enabled;
5893
- let reportedServerFsOff = false;
5894
- const activity = { runs: 0 };
5895
- const updater = startDaemonUpdater({
5896
- selfVersion: input.clientVersion,
5897
- setting: async () => {
5898
- const setting = await readAutoUpdate();
5899
- autoUpdateEnabled = setting.enabled;
5900
- return setting;
5901
- },
5902
- busy: () => ({
5903
- runs: activity.runs,
5904
- background: hostCommands.runningBackground()
5905
- }),
5906
- log,
5907
- onReady: (current, forced) => {
5908
- if (signalled) return;
5909
- updateTo = current;
5910
- forcedUpdate = forced;
5911
- if (!drain.signal.aborted) drain.abort();
5912
- }
5913
- });
5914
- const checkLogin = async () => {
5915
- try {
5916
- const result = await checkContextLogin({
5917
- apiUrl: input.apiUrl,
5918
- ecid: context.ecid,
5919
- privateKey,
5920
- token: await input.token(),
5921
- org: context.orgSlug,
5922
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
5923
- });
5924
- if (result.changed) {
5925
- log(
5926
- `Recorded this machine's login (${result.login.kind === "profile" ? "agent profile" : "person"}) with Kody.`
5927
- );
5928
- }
5929
- } catch (error) {
5930
- log(
5931
- `Could not check this machine's login with Kody: ${error instanceof Error ? error.message : String(error)}`
5932
- );
5933
- }
5934
- };
5935
- void checkLogin();
5936
- const loginTimer = setInterval(
5937
- () => void checkLogin(),
5938
- loginCheckIntervalMs
5939
- );
5940
- loginTimer.unref();
5941
- try {
5942
- stop = await runDaemon({
5943
- apiUrl: input.apiUrl,
5944
- ecid: context.ecid,
5945
- privateKey,
5946
- serverKeys,
5947
- maxConcurrent,
5948
- client: { name: "kody-cli", version: input.clientVersion },
5949
- capabilities: {
5950
- ...localCapabilities(maxConcurrent),
5951
- ...manager ? { service: manager } : {}
5952
- },
5953
- extraCapabilities: () => ({
5954
- autoUpdate: autoUpdateEnabled ? "on" : "off"
5955
- }),
5956
- activity,
5957
- // An update drain also waits for background host commands.
5958
- drainHold: () => updateTo !== null && !signalled && !forcedUpdate && hostCommands.runningBackground() > 0,
5959
- hostCommands,
5960
- execute: (run) => runContextRun({
5961
- ...run,
5962
- apiUrl: input.apiUrl,
5963
- workerTracker,
5964
- packageGraphCache
5965
- }),
5966
- fs: {
5967
- effective: async (grantFs) => {
5968
- const policy = await readLocalPolicy();
5969
- autoUpdateEnabled = autoUpdateSetting(policy).enabled;
5970
- const serverOff = grantFs.length === 0 && policy.fs.length > 0;
5971
- if (serverOff && !reportedServerFsOff) {
5972
- log(
5973
- "This machine's local policy allows host folders, but this context's server grant (grant.fs) lists none, so runs get no host folders. Someone with Contribute or Manage on the context can turn it on with: kody context grant allow <folder> --mode ro|rw"
5974
- );
5975
- }
5976
- reportedServerFsOff = serverOff;
5977
- return await effectiveFs(grantFs, policy.fs);
5978
- },
5979
- onChange: (listener) => {
5980
- const path = localPolicyPath();
5981
- watchFile(path, { interval: 2e3 }, listener);
5982
- return () => unwatchFile(path, listener);
5983
- }
5984
- },
5985
- log,
5986
- onPaused: (next) => {
5987
- if (JSON.stringify(next) === JSON.stringify(paused)) return;
5988
- log(
5989
- next ? `Paused in Kody${next.by ? ` by @${next.by}` : ""}${next.reason ? `: ${next.reason}` : ""}. This daemon stays connected but gets no runs and no host commands until it is resumed (kody daemon resume).` : paused ? "Resumed in Kody. Taking runs again." : ""
5990
- );
5991
- paused = next;
5992
- },
5993
- control: async (op, args) => {
5994
- const restartable = Boolean(manager) || supervised;
5995
- const busyDraining = () => {
5996
- if (drain.signal.aborted) {
5997
- throw new DaemonControlError(
5998
- "daemon_busy",
5999
- "This daemon is already stopping for a restart or update."
6000
- );
6001
- }
6002
- };
6003
- switch (op) {
6004
- case "status":
6005
- return {
6006
- version: input.clientVersion,
6007
- service: manager,
6008
- supervised,
6009
- pid: process.pid,
6010
- platform: platform(),
6011
- startedAt,
6012
- autoUpdate: autoUpdateEnabled ? "on" : "off",
6013
- maxConcurrent,
6014
- runs: activity.runs,
6015
- backgroundCommands: hostCommands.runningBackground(),
6016
- draining: drain.signal.aborted,
6017
- paused
6018
- };
6019
- case "restart": {
6020
- if (!restartable) {
6021
- throw new DaemonControlError(
6022
- "not_service_managed",
6023
- "This daemon runs in a terminal, so nothing would start it again."
6024
- );
6025
- }
6026
- busyDraining();
6027
- log(
6028
- "Restart requested from Kody. Stopping after runs in flight finish; the service manager starts it again."
6029
- );
6030
- restartRequested = true;
6031
- setTimeout(() => {
6032
- if (!drain.signal.aborted) drain.abort();
6033
- }, 250).unref();
6034
- return { restarting: true, runs: activity.runs };
6035
- }
6036
- case "update": {
6037
- busyDraining();
6038
- const result = await checkForUpdate({
6039
- selfVersion: input.clientVersion,
6040
- enabled: true
6041
- });
6042
- if (result.kind === "ready") {
6043
- log(
6044
- `Update requested from Kody: moving kody ${input.clientVersion} to ${result.current.version} after runs in flight finish.`
6045
- );
6046
- updateTo = result.current;
6047
- setTimeout(() => {
6048
- if (!drain.signal.aborted) drain.abort();
6049
- }, 250).unref();
6050
- return {
6051
- version: input.clientVersion,
6052
- updatingTo: result.current.version,
6053
- message: `Updating to kody ${result.current.version} after runs in flight finish.`
6054
- };
6055
- }
6056
- if (result.kind === "up-to-date") {
6057
- return {
6058
- version: input.clientVersion,
6059
- latest: result.latest,
6060
- message: `Already on the latest kody (${input.clientVersion}).`
6061
- };
6062
- }
6063
- throw new DaemonControlError(
6064
- "daemon_control_failed",
6065
- result.kind === "failed" ? `Could not update to ${result.version}: ${result.error}` : result.kind === "backoff" ? `${result.version} failed before; next try after ${result.until}.` : "Another update check is running. Try again shortly."
6066
- );
6067
- }
6068
- case "auto-update": {
6069
- const enabled = args.enabled === true;
6070
- await setLocalAutoUpdateEnabled({ enabled });
6071
- autoUpdateEnabled = (await readAutoUpdate()).enabled;
6072
- log(
6073
- `Auto-update turned ${enabled ? "on" : "off"} from Kody (for every kody daemon on this machine).`
6074
- );
6075
- return { autoUpdate: autoUpdateEnabled ? "on" : "off" };
6076
- }
6077
- case "logs": {
6078
- const lines = Math.max(
6079
- 1,
6080
- Math.min(
6081
- daemonLogBufferLines,
6082
- typeof args.lines === "number" ? Math.floor(args.lines) : 100
6083
- )
6084
- );
6085
- return {
6086
- lines: recentDaemonLog(paths?.logPath, recentLog, lines)
6087
- };
6088
- }
6089
- default:
6090
- throw new DaemonControlError(
6091
- "daemon_control_failed",
6092
- `Unknown daemon operation ${op}. Update kody on this machine.`
6093
- );
6094
- }
6095
- },
6096
- signal: abort.signal,
6097
- drainSignal: drain.signal
6098
- });
6099
- } finally {
6100
- clearInterval(loginTimer);
6101
- updater.stop();
6102
- unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
6103
- hostCommands.killAll("shutdown");
6104
- workerTracker.killAll();
6105
- workerTracker.dispose();
6106
- if (hardStop) clearTimeout(hardStop);
6107
- process.off("SIGINT", onSignal);
6108
- process.off("SIGTERM", onSignal);
6109
- rmSync6(statePath, { force: true });
6110
- releaseLock();
6111
- }
6112
- if (stop === "replaced") {
6113
- const others = await otherLocalDaemons({ ecid: context.ecid });
6114
- log(
6115
- 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.`
6116
- );
6117
- if (manager) return stayStoppedExitCode;
6118
- return supervised ? startupRefusedExitCode : 1;
6119
- }
6120
- const target = updateTo;
6121
- if (stop === "shutdown" && restartRequested && !target && !signalled) {
6122
- return relaunchExitCode;
6123
- }
6124
- if (stop === "shutdown" && target && !signalled) {
6125
- if (manager || supervised) return relaunchExitCode;
6126
- const outcome = await superviseNewerVersion({
6127
- first: target,
6128
- selfVersion: input.clientVersion,
6129
- args: relaunchArgs,
6130
- log
6131
- });
6132
- if (outcome.kind === "exit") return outcome.code;
6133
- log(`Auto-update: back on kody ${input.clientVersion}.`);
6134
- return await runExecutionContextCommand(input);
6135
- }
6136
- if (stop === "revoked" || stop === "unknown_context") {
6137
- const reason = stop === "revoked" ? "Kody revoked this context" : "Kody no longer knows this context (deleted)";
6138
- writeJson(
6139
- servicePaths({
6140
- apiUrl: input.apiUrl,
6141
- ecid,
6142
- manager: serviceManagerFor() ?? "systemd"
6143
- }).stoppedPath,
6144
- { reason, at: (/* @__PURE__ */ new Date()).toISOString() }
6145
- );
6146
- if (manager) disableOwnService({ manager, ecid });
6147
- input.write(
6148
- `${reason}. Stopping for good${manager ? " and disabling the service" : ""}. Register again with: kody connect --name <name>
6149
- `
6150
- );
6151
- }
6152
- return stayStoppedExitCode;
6153
- }
6154
- throw new Error(
6155
- "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 grant [show | allow <path> [--mode ro|rw] | remove <path> | lan on|off] [--context <name>] | 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"
6156
- );
6157
- }
6158
- async function resolveContextId(input) {
6159
- if (input.ref.startsWith("ec_")) return input.ref;
6160
- const body = await apiJson({
6161
- ...input,
6162
- method: "GET",
6163
- path: "/v1/execution-contexts"
6164
- });
6165
- const match = (body.contexts ?? []).find((c) => c.name === input.ref);
6166
- if (!match)
6167
- throw new Error(`No execution context named ${input.ref} in this org.`);
6168
- return match.id;
6169
- }
6170
- function chainOf(body) {
6171
- return body.chain ?? {};
6172
- }
6173
- function contextsById(body) {
6174
- const contexts = body.contexts ?? [];
6175
- return new Map(contexts.map((context) => [context.id, context]));
6176
- }
6177
- function describeChain(chain, contexts = /* @__PURE__ */ new Map()) {
6178
- const entries = chain.entries ?? [];
6179
- const lines = entries.map((entry, index) => {
6180
- if (entry.kind === "cloud") return `${index + 1}. Kody cloud (always last)`;
6181
- const known = entry.id ? contexts.get(entry.id) : void 0;
6182
- const name = entry.name ?? known?.name;
6183
- const label = name ? `${name} (${entry.id})` : String(entry.id);
6184
- const offline = known?.paused ? " [paused]" : known?.status && known.status !== "online" ? ` [${known.status}]` : "";
6185
- const skipped = entry.usable === false ? ` (skipped: ${entry.unusableReason})` : "";
6186
- return `${index + 1}. ${label}${offline}${skipped}`;
6187
- });
6188
- if (chain.strict) lines.push("Strict: Kody cloud is not in this chain.");
6189
- return lines.join("\n") || "Empty chain.";
6190
- }
6191
- var policyUsage = "Usage: kody context policy [show] | kody context policy allow <path> [--mode ro|rw] | kody context policy remove <path>";
6192
- var commandsUsage = "Usage: kody context commands [status | on | off] [--context <name>] [--json]";
6193
- async function runCommandsOptInCommand(input, [action = "status", ...extra]) {
6194
- if (extra.length > 0 || !["status", "on", "off"].includes(action)) {
6195
- throw new Error(commandsUsage);
6196
- }
6197
- const ecids = input.values.context ? [
6198
- localContextId(input.apiUrl, input.values.context) ?? input.values.context
6199
- ] : storedContextIds(input.apiUrl);
6200
- if (action === "on" && input.values.context) {
6201
- loadContext({
6202
- apiUrl: input.apiUrl,
6203
- ecid: ecids[0],
6204
- wrapping: wrappingKeyForStoredContext({
6205
- apiUrl: input.apiUrl,
6206
- ecid: ecids[0]
6207
- })
6208
- });
6209
- }
6210
- if (action !== "status") {
6211
- await setLocalCommandsEnabled({ enabled: action === "on" });
6212
- }
6213
- const local = await readLocalCommandsEnabled();
6214
- const contexts = [];
6215
- for (const ecid of ecids) {
6216
- try {
6217
- const { context, privateJwk } = loadContext({
6218
- apiUrl: input.apiUrl,
6219
- ecid,
6220
- wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
6221
- });
6222
- const result = await setContextCommands({
6223
- apiUrl: input.apiUrl,
6224
- ecid: context.ecid,
6225
- privateKey: await importContextKey(privateJwk),
6226
- ...action === "status" ? {} : { enabled: action === "on" },
6227
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
6228
- });
6229
- contexts.push({
6230
- id: result.id,
6231
- name: result.name,
6232
- commands: result.commands
6233
- });
6234
- } catch (error) {
6235
- contexts.push({
6236
- id: ecid,
6237
- name: ecid,
6238
- commands: null,
6239
- error: error instanceof Error ? error.message : String(error)
6240
- });
6241
- }
6242
- }
6243
- const lines = [
6244
- `Host commands on this machine: ${local ? "on" : "off"} (local opt-in, ${localPolicyPath()}).`,
6245
- ...contexts.map(
6246
- (context) => context.commands ? ` ${context.name}: ${context.commands.enabled ? "on" : "off"} in Kody` : ` ${context.name}: could not reach Kody (${context.error})`
6247
- )
6248
- ];
6249
- if (contexts.length === 0) {
6250
- lines.push(
6251
- " This machine has no registered execution context. Run `kody connect --name <name>` first."
6252
- );
6253
- }
6254
- if (action === "on") {
6255
- lines.push(
6256
- "Your own runs on this context can now run any command as your OS user, with no per-command approval (runs by people you share it with never can). Every command is recorded in the context audit log. Turn it off any time: kody context commands off, the desktop app, or the website."
6257
- );
6258
- } else if (action === "off") {
6259
- lines.push("Background commands started by runs were stopped.");
6260
- } else if (!local) {
6261
- lines.push("Turn them on with: kody context commands on");
6262
- }
6263
- out(
6264
- input,
6265
- { local: { enabled: local, path: localPolicyPath() }, contexts },
6266
- lines.join("\n")
6267
- );
6268
- return contexts.some((context) => context.error) ? 1 : 0;
6269
- }
6270
- async function runPolicyCommand(input, [action, path, ...extra]) {
6271
- const file = localPolicyPath();
6272
- const describe = (rules) => rules.length === 0 ? `No host folders are allowed on this machine (${file}). Execution-context runs only see their virtual filesystem.` : [
6273
- `Host folders this machine allows (${file}):`,
6274
- ...rules.map((rule) => ` ${rule.mode} ${rule.path}`),
6275
- "This is the local policy. A run can use a folder only if its context server grant (grant.fs) also lists it; the narrower mode wins."
6276
- ].join("\n");
6277
- const grantNotes = (fs) => machineGrantNotes({
6278
- apiUrl: input.apiUrl,
6279
- ...input.org ? { org: input.org } : {},
6280
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
6281
- token: input.token,
6282
- policyFs: fs
6283
- });
6284
- if (action === void 0 || action === "show") {
6285
- const policy = await readLocalPolicy(file);
6286
- const serverGrant = await grantNotes(policy.fs);
6287
- out(
6288
- input,
6289
- { path: file, ...policy, serverGrant },
6290
- `${describe(policy.fs)}${describeMachineGrantNotes(serverGrant)}`
6291
- );
6292
- return 0;
6293
- }
6294
- if (!path || extra.length > 0) throw new Error(policyUsage);
6295
- if (action === "allow") {
6296
- const mode = input.values.mode ?? "ro";
6297
- if (mode !== "ro" && mode !== "rw") {
6298
- throw new Error("--mode must be ro (read-only) or rw (read-write).");
6299
- }
6300
- const { policy, added } = await allowLocalPath({
6301
- path,
6302
- mode,
6303
- policyPath: file
6304
- });
6305
- const serverGrant = await grantNotes(policy.fs);
6306
- out(
6307
- input,
6308
- { path: file, ...policy, serverGrant },
6309
- `Allowed ${added.path} (${added.mode}) in this machine's local policy. Running daemons pick this up within a few seconds. This does not change the context's server grant.
6310
- ${describe(policy.fs)}${describeMachineGrantNotes(serverGrant)}`
6311
- );
6312
- return 0;
6313
- }
6314
- if (action === "remove") {
6315
- const { policy, removed } = await removeLocalPath({
6316
- path,
6317
- policyPath: file
6318
- });
6319
- out(
6320
- input,
6321
- { path: file, removed, ...policy },
6322
- `${removed ? `Removed ${path}.` : `${path} was not in the policy.`}
6323
- ${describe(policy.fs)}`
6324
- );
6325
- return 0;
6326
- }
6327
- throw new Error(policyUsage);
6328
- }
6329
- var daemonLogBufferLines = 500;
6330
- function recentDaemonLog(logPath, buffered, lines) {
6331
- if (logPath && existsSync5(logPath)) {
6332
- try {
6333
- const text = readFileSync8(logPath, "utf8");
6334
- return text.split(/\r?\n/).filter(Boolean).slice(-lines);
6335
- } catch {
6336
- }
6337
- }
6338
- return buffered.slice(-lines);
6339
- }
6340
- function appendOutputTo(path) {
6341
- for (const stream of [process.stdout, process.stderr]) {
6342
- const write = stream.write.bind(stream);
6343
- stream.write = ((chunk, ...rest) => {
6344
- try {
6345
- appendFileSync(path, chunk, { mode: 384 });
6346
- } catch {
6347
- }
6348
- return write(chunk, ...rest);
6349
- });
6350
- }
6351
- }
6352
3644
  export {
6353
- maxConcurrentRuns,
6354
- runExecutionContextCommand
3645
+ ecpContextKeyId,
3646
+ ecpPingFrame,
3647
+ ed25519JwkThumbprint,
3648
+ importEd25519PublicKey,
3649
+ decodeEnvelopePayload,
3650
+ ecpProtocolVersion,
3651
+ ecpMaxConcurrentRunsCap,
3652
+ ecpDefaultGrant,
3653
+ ecpHostOperatorOnlyFeature,
3654
+ classifyFrameText,
3655
+ signFrame,
3656
+ verifyFrame,
3657
+ publishedKeyJwk,
3658
+ executionContextsPath,
3659
+ isPermanentContextRefusal,
3660
+ experimentOffError,
3661
+ isExperimentOffError,
3662
+ signedFetch,
3663
+ generateContextKey,
3664
+ importContextKey,
3665
+ registerContext,
3666
+ requestConnectTicket,
3667
+ setContextCommands,
3668
+ checkContextLogin,
3669
+ fetchServerKeys,
3670
+ apiJson,
3671
+ relaunchExitCode,
3672
+ startupRefusedExitCode,
3673
+ supervisedEnvVar,
3674
+ newerInstalledVersion,
3675
+ autoUpdateSetting,
3676
+ checkForUpdate,
3677
+ superviseNewerVersion,
3678
+ startDaemonUpdater,
3679
+ launcherEnvVar,
3680
+ lockPathFor,
3681
+ acquireRunnerLock,
3682
+ describeHolder,
3683
+ otherLocalDaemons,
3684
+ contextWorkersDir,
3685
+ resolveWrappingKey,
3686
+ fileWrappingKey,
3687
+ wrappingKeyForStoredContext,
3688
+ saveContext,
3689
+ loadContext,
3690
+ saveServiceEnvAssignments,
3691
+ serviceEnvVar,
3692
+ stayStoppedExitCode,
3693
+ serviceManagerFor,
3694
+ isServiceManager,
3695
+ servicePaths,
3696
+ writeJson,
3697
+ disableOwnService,
3698
+ rotateLog,
3699
+ terminalConfirm,
3700
+ storedContextIds,
3701
+ localContextId,
3702
+ runDaemonEnvCommand,
3703
+ runAutoUpdateCommand,
3704
+ runDaemonServiceCommand,
3705
+ offerInstall,
3706
+ offerUninstallAfterRevoke,
3707
+ runUpdate,
3708
+ isRemoteDaemonCommand,
3709
+ runRemoteDaemonCommand
6355
3710
  };
6356
- //# sourceMappingURL=commands-FNEOMNRD.js.map
3711
+ //# sourceMappingURL=chunk-Z2NJN47S.js.map